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/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java index 2b3965a45..ab8e8ba5f 100644 --- a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java +++ b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java @@ -1,112 +1,115 @@ /******************************************************************************* * Copyright (c) 2007 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.seam.internal.core.project.facet; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; import org.eclipse.core.runtime.preferences.DefaultScope; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.jboss.tools.seam.core.SeamCorePlugin; import org.jboss.tools.seam.core.project.facet.SeamProjectPreferences; import org.jboss.tools.seam.core.project.facet.SeamRuntime; import org.jboss.tools.seam.core.project.facet.SeamRuntimeListConverter; import org.jboss.tools.seam.core.project.facet.SeamVersion; import org.osgi.service.prefs.BackingStoreException; /** * @author eskimo * */ public class SeamFacetPreferenceInitializer extends AbstractPreferenceInitializer { public static String RUNTIME_CONFIG_FORMAT_VERSION = "1.0"; //$NON-NLS-1$ public static final String SEAM_1_2_HOME = "../../../seam1"; //$NON-NLS-1$ public static final String SEAM_2_0_HOME = "../../../seam"; //$NON-NLS-1$ /** * */ public SeamFacetPreferenceInitializer() {} @Override public void initializeDefaultPreferences() { IEclipsePreferences node = (IEclipsePreferences) Platform.getPreferencesService() .getRootNode() .node(DefaultScope.SCOPE) .node(SeamCorePlugin.PLUGIN_ID); // node.put(SeamProjectPreferences.SEAM_CONFIG_TEMPLATE, "template.jst.seam2"); //$NON-NLS-1$ node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION); node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$ node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$ node.put(SeamProjectPreferences.SEAM_DEFAULT_CONNECTION_PROFILE, "DefaultDS"); //$NON-NLS-1$ Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>(); // Initialize Seam 1.2 Runtime from JBoss EAP String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME); File seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { SeamRuntime rt = new SeamRuntime(); rt.setHomeDir(seamGenBuildPath); rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$ rt.setDefault(true); rt.setVersion(SeamVersion.SEAM_1_2); map.put(rt.getName(), rt); } // Initialize Seam 2.0 Runtime from JBoss EAP seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME); seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { - SeamRuntime rt = new SeamRuntime(); - rt.setHomeDir(seamGenBuildPath); - rt.setName("Seam " + SeamVersion.SEAM_2_1); //$NON-NLS-1$ //$NON-NLS-2$ - rt.setDefault(true); - rt.setVersion(SeamVersion.SEAM_2_1); - map.put(rt.getName(), rt); + File seamGen = new File(seamFolder, "/seam-gen"); + if(seamGen.exists() && seamGen.isDirectory()) { + SeamRuntime rt = new SeamRuntime(); + rt.setHomeDir(seamGenBuildPath); + rt.setName("Seam " + SeamVersion.SEAM_2_1); //$NON-NLS-1$ //$NON-NLS-2$ + rt.setDefault(true); + rt.setVersion(SeamVersion.SEAM_2_1); + map.put(rt.getName(), rt); + } } node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map)); try { node.flush(); } catch (BackingStoreException e) { SeamCorePlugin.getPluginLog().logError(e); } } private String getSeamGenBuildPath(String seamHomePath) { String pluginLocation=null; try { pluginLocation = FileLocator.resolve(SeamCorePlugin.getDefault().getBundle().getEntry("/")).getFile(); //$NON-NLS-1$ } catch (IOException e) { SeamCorePlugin.getPluginLog().logError(e); }; File seamGenDir = new File(pluginLocation, seamHomePath); Path p = new Path(seamGenDir.getPath()); p.makeAbsolute(); if(p.toFile().exists()) { return p.toOSString(); } else { return ""; //$NON-NLS-1$ } } }
true
true
public void initializeDefaultPreferences() { IEclipsePreferences node = (IEclipsePreferences) Platform.getPreferencesService() .getRootNode() .node(DefaultScope.SCOPE) .node(SeamCorePlugin.PLUGIN_ID); // node.put(SeamProjectPreferences.SEAM_CONFIG_TEMPLATE, "template.jst.seam2"); //$NON-NLS-1$ node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION); node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$ node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$ node.put(SeamProjectPreferences.SEAM_DEFAULT_CONNECTION_PROFILE, "DefaultDS"); //$NON-NLS-1$ Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>(); // Initialize Seam 1.2 Runtime from JBoss EAP String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME); File seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { SeamRuntime rt = new SeamRuntime(); rt.setHomeDir(seamGenBuildPath); rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$ rt.setDefault(true); rt.setVersion(SeamVersion.SEAM_1_2); map.put(rt.getName(), rt); } // Initialize Seam 2.0 Runtime from JBoss EAP seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME); seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { SeamRuntime rt = new SeamRuntime(); rt.setHomeDir(seamGenBuildPath); rt.setName("Seam " + SeamVersion.SEAM_2_1); //$NON-NLS-1$ //$NON-NLS-2$ rt.setDefault(true); rt.setVersion(SeamVersion.SEAM_2_1); map.put(rt.getName(), rt); } node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map)); try { node.flush(); } catch (BackingStoreException e) { SeamCorePlugin.getPluginLog().logError(e); } }
public void initializeDefaultPreferences() { IEclipsePreferences node = (IEclipsePreferences) Platform.getPreferencesService() .getRootNode() .node(DefaultScope.SCOPE) .node(SeamCorePlugin.PLUGIN_ID); // node.put(SeamProjectPreferences.SEAM_CONFIG_TEMPLATE, "template.jst.seam2"); //$NON-NLS-1$ node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION); node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$ node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$ node.put(SeamProjectPreferences.SEAM_DEFAULT_CONNECTION_PROFILE, "DefaultDS"); //$NON-NLS-1$ Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>(); // Initialize Seam 1.2 Runtime from JBoss EAP String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME); File seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { SeamRuntime rt = new SeamRuntime(); rt.setHomeDir(seamGenBuildPath); rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$ rt.setDefault(true); rt.setVersion(SeamVersion.SEAM_1_2); map.put(rt.getName(), rt); } // Initialize Seam 2.0 Runtime from JBoss EAP seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME); seamFolder = new File(seamGenBuildPath); if(seamFolder.exists() && seamFolder.isDirectory()) { File seamGen = new File(seamFolder, "/seam-gen"); if(seamGen.exists() && seamGen.isDirectory()) { SeamRuntime rt = new SeamRuntime(); rt.setHomeDir(seamGenBuildPath); rt.setName("Seam " + SeamVersion.SEAM_2_1); //$NON-NLS-1$ //$NON-NLS-2$ rt.setDefault(true); rt.setVersion(SeamVersion.SEAM_2_1); map.put(rt.getName(), rt); } } node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map)); try { node.flush(); } catch (BackingStoreException e) { SeamCorePlugin.getPluginLog().logError(e); } }
diff --git a/ij/process/ParallelByteProcessor.java b/ij/process/ParallelByteProcessor.java index a0fd5a9..50de872 100644 --- a/ij/process/ParallelByteProcessor.java +++ b/ij/process/ParallelByteProcessor.java @@ -1,150 +1,153 @@ package ij.process; import ij.Prefs; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.util.Random; /** * Class designed to implement ByteProcessor filters in parallel using a variety of approaches. * * @author Sina Masoud-Ansari * */ public class ParallelByteProcessor extends ByteProcessor { public enum Type {SERIAL, SIMPLE, FORK_JOIN, EXECUTOR, PARALLEL_TASK} private Type type; public ParallelByteProcessor(Image img, Type t) { super(img); type = t; } public ParallelByteProcessor(int width, int height, Type t) { super(width, height); type = t; } public ParallelByteProcessor(int width, int height, byte[] pixels, Type t) { super(width, height, pixels); type = t; } public ParallelByteProcessor(int width, int height, byte[] pixels, ColorModel cm, Type t) { super(width, height, pixels, cm); type = t; } public ParallelByteProcessor(BufferedImage bi, Type t) { super(bi); type = t; } public ParallelByteProcessor(ImageProcessor ip, boolean scale, Type t) { super(ip, scale); type = t; } @Override public void noise(double range, String t){ switch (type) { case SERIAL: serial_noise(range); break; case SIMPLE: simple_noise(range); break; } } public void serial_noise(double range) { Random rnd=new Random(); int v, ran; boolean inRange; for (int y=roiY; y<(roiY+roiHeight); y++) { int i = y * width + roiX; for (int x=roiX; x<(roiX+roiWidth); x++) { inRange = false; do { ran = (int)Math.round(rnd.nextGaussian()*range); v = (pixels[i] & 0xff) + ran; inRange = v>=0 && v<=255; if (inRange) pixels[i] = (byte)v; } while (!inRange); i++; } if (y%20==0) showProgress((double)(y-roiY)/roiHeight); } showProgress(1.0); } // TODO: There are two problems here: // 1. There are linear artificats when the underlying image is not white. // - This could be due to incorrect starting indices // 2. It is about 2x slower than the serial version public void simple_noise(double r) { final double range = r; //Divide the number of rows by the number of threads int numThreads = Math.min(roiHeight, Prefs.getThreads()); int ratio = roiHeight / numThreads; Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++){ final int yIndex = i; final int numRowsPerThread; if ( (i == numThreads - 1)){ // add an additional row for the last thread if the roiY is not a multiple of numThreads numRowsPerThread = roiY % numThreads == 0 ? ratio : ratio + 1; } else { numRowsPerThread = ratio; } threads[i] = new Thread(new Runnable(){ @Override public void run() { int yStart = roiY+yIndex*numRowsPerThread; int yLimit = yStart + numRowsPerThread; int xEnd = roiX + roiWidth; + int p, v, ran; + boolean inRange; + Random rnd = new Random(); // for each row for (int y = yStart; y < yLimit; y++){ // process pixels in ROI for (int x = roiX; x < xEnd; x++){ // pixels is a 1D array so need to map to it - int p = y * roiWidth + roiX + x; - Random rnd = new Random(); - int v, ran; - boolean inRange; - do{ + p = y * roiWidth + roiX + x; + inRange = false; + while (!inRange){ ran = (int)Math.round(rnd.nextGaussian()*range); v = (pixels[p] & 0xff) + ran; inRange = v>=0 && v<=255; - if (inRange) pixels[p] = (byte)v; - } while (!inRange); + if (inRange){ + pixels[p] = (byte)v; + } + } } // end x loop if (y%20==0) { showProgress((double)(y-roiY)/roiHeight); } } // end y loop } // end run }); // end new thread definition } // start threads for (Thread t : threads){ t.start(); } // wait for threads to finish for (Thread t : threads){ try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // indicate processing is finished showProgress(1.0); } }
false
true
public void simple_noise(double r) { final double range = r; //Divide the number of rows by the number of threads int numThreads = Math.min(roiHeight, Prefs.getThreads()); int ratio = roiHeight / numThreads; Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++){ final int yIndex = i; final int numRowsPerThread; if ( (i == numThreads - 1)){ // add an additional row for the last thread if the roiY is not a multiple of numThreads numRowsPerThread = roiY % numThreads == 0 ? ratio : ratio + 1; } else { numRowsPerThread = ratio; } threads[i] = new Thread(new Runnable(){ @Override public void run() { int yStart = roiY+yIndex*numRowsPerThread; int yLimit = yStart + numRowsPerThread; int xEnd = roiX + roiWidth; // for each row for (int y = yStart; y < yLimit; y++){ // process pixels in ROI for (int x = roiX; x < xEnd; x++){ // pixels is a 1D array so need to map to it int p = y * roiWidth + roiX + x; Random rnd = new Random(); int v, ran; boolean inRange; do{ ran = (int)Math.round(rnd.nextGaussian()*range); v = (pixels[p] & 0xff) + ran; inRange = v>=0 && v<=255; if (inRange) pixels[p] = (byte)v; } while (!inRange); } // end x loop if (y%20==0) { showProgress((double)(y-roiY)/roiHeight); } } // end y loop } // end run }); // end new thread definition } // start threads for (Thread t : threads){ t.start(); } // wait for threads to finish for (Thread t : threads){ try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // indicate processing is finished showProgress(1.0); }
public void simple_noise(double r) { final double range = r; //Divide the number of rows by the number of threads int numThreads = Math.min(roiHeight, Prefs.getThreads()); int ratio = roiHeight / numThreads; Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++){ final int yIndex = i; final int numRowsPerThread; if ( (i == numThreads - 1)){ // add an additional row for the last thread if the roiY is not a multiple of numThreads numRowsPerThread = roiY % numThreads == 0 ? ratio : ratio + 1; } else { numRowsPerThread = ratio; } threads[i] = new Thread(new Runnable(){ @Override public void run() { int yStart = roiY+yIndex*numRowsPerThread; int yLimit = yStart + numRowsPerThread; int xEnd = roiX + roiWidth; int p, v, ran; boolean inRange; Random rnd = new Random(); // for each row for (int y = yStart; y < yLimit; y++){ // process pixels in ROI for (int x = roiX; x < xEnd; x++){ // pixels is a 1D array so need to map to it p = y * roiWidth + roiX + x; inRange = false; while (!inRange){ ran = (int)Math.round(rnd.nextGaussian()*range); v = (pixels[p] & 0xff) + ran; inRange = v>=0 && v<=255; if (inRange){ pixels[p] = (byte)v; } } } // end x loop if (y%20==0) { showProgress((double)(y-roiY)/roiHeight); } } // end y loop } // end run }); // end new thread definition } // start threads for (Thread t : threads){ t.start(); } // wait for threads to finish for (Thread t : threads){ try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // indicate processing is finished showProgress(1.0); }
diff --git a/classes/test/CustomClassLoader.java b/classes/test/CustomClassLoader.java index a5ee63c5..23a88e9f 100644 --- a/classes/test/CustomClassLoader.java +++ b/classes/test/CustomClassLoader.java @@ -1,80 +1,78 @@ package classes.test; import java.io.*; public class CustomClassLoader extends ClassLoader { private static final int BUFFER_SIZE = 8192; protected synchronized Class loadClass(String className, boolean resolve) throws ClassNotFoundException { - System.out.println("Loading class: " + className + ", resolve: " + resolve); // 1. is this class already loaded? Class cls = findLoadedClass(className); if (cls != null) { System.out.println("Already loaded "+className); return cls; } // 2. get class file name from class name String clsFile = className.replace('.', '/') + ".class"; // 3. get bytes for class byte[] classBytes = null; try { InputStream in = getResourceAsStream(clsFile); byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = -1; while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) { out.write(buffer, 0, n); } classBytes = out.toByteArray(); } catch (IOException e) { System.out.println("ERROR loading class file: " + e); } if (classBytes == null) { throw new ClassNotFoundException("Cannot load class: " + className); } // 4. turn the byte array into a Class try { cls = defineClass(className, classBytes, 0, classBytes.length); if (resolve) { resolveClass(cls); } System.out.println("ran defineClass with no issues"); } catch (SecurityException e) { - System.out.println("Caught "+e); cls = super.loadClass(className, resolve); } return cls; } public static void foo(){ System.out.println("Called CustomClassLoader.foo"); } public static void bar(){ System.out.println("Called CustomClassLoader.bar"); } public static void main(String[] args) throws Exception { CustomClassLoader loader1 = new CustomClassLoader(); Class<?> c = Class.forName("classes.test.CustomClassLoader", true, loader1); System.out.println("Custom loaded class: " + c); System.out.print("Class loaded through custom loader is "); if (!CustomClassLoader.class.equals(c)) { System.out.print("NOT "); } System.out.println("the same as that loaded by System loader."); java.lang.reflect.Method m = c.getMethod("foo", new Class[] {}); m.invoke(null, new Object[]{}); java.lang.reflect.Method m2 = c.getMethod("bar", new Class[] {}); m2.invoke(null, new Object[]{}); } }
false
true
protected synchronized Class loadClass(String className, boolean resolve) throws ClassNotFoundException { System.out.println("Loading class: " + className + ", resolve: " + resolve); // 1. is this class already loaded? Class cls = findLoadedClass(className); if (cls != null) { System.out.println("Already loaded "+className); return cls; } // 2. get class file name from class name String clsFile = className.replace('.', '/') + ".class"; // 3. get bytes for class byte[] classBytes = null; try { InputStream in = getResourceAsStream(clsFile); byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = -1; while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) { out.write(buffer, 0, n); } classBytes = out.toByteArray(); } catch (IOException e) { System.out.println("ERROR loading class file: " + e); } if (classBytes == null) { throw new ClassNotFoundException("Cannot load class: " + className); } // 4. turn the byte array into a Class try { cls = defineClass(className, classBytes, 0, classBytes.length); if (resolve) { resolveClass(cls); } System.out.println("ran defineClass with no issues"); } catch (SecurityException e) { System.out.println("Caught "+e); cls = super.loadClass(className, resolve); } return cls; }
protected synchronized Class loadClass(String className, boolean resolve) throws ClassNotFoundException { // 1. is this class already loaded? Class cls = findLoadedClass(className); if (cls != null) { System.out.println("Already loaded "+className); return cls; } // 2. get class file name from class name String clsFile = className.replace('.', '/') + ".class"; // 3. get bytes for class byte[] classBytes = null; try { InputStream in = getResourceAsStream(clsFile); byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = -1; while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) { out.write(buffer, 0, n); } classBytes = out.toByteArray(); } catch (IOException e) { System.out.println("ERROR loading class file: " + e); } if (classBytes == null) { throw new ClassNotFoundException("Cannot load class: " + className); } // 4. turn the byte array into a Class try { cls = defineClass(className, classBytes, 0, classBytes.length); if (resolve) { resolveClass(cls); } System.out.println("ran defineClass with no issues"); } catch (SecurityException e) { cls = super.loadClass(className, resolve); } return cls; }
diff --git a/src/org/openstreetmap/josm/plugins/notes/api/util/NotesApi.java b/src/org/openstreetmap/josm/plugins/notes/api/util/NotesApi.java index bb862ac..3d8be21 100644 --- a/src/org/openstreetmap/josm/plugins/notes/api/util/NotesApi.java +++ b/src/org/openstreetmap/josm/plugins/notes/api/util/NotesApi.java @@ -1,333 +1,333 @@ package org.openstreetmap.josm.plugins.notes.api.util; import static org.openstreetmap.josm.tools.I18n.tr; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.data.coor.LatLon; import org.openstreetmap.josm.gui.progress.NullProgressMonitor; import org.openstreetmap.josm.gui.progress.ProgressMonitor; import org.openstreetmap.josm.io.ChangesetClosedException; import org.openstreetmap.josm.io.OsmApi; import org.openstreetmap.josm.io.OsmApiException; import org.openstreetmap.josm.io.OsmApiPrimitiveGoneException; import org.openstreetmap.josm.io.OsmConnection; import org.openstreetmap.josm.io.OsmTransferCanceledException; import org.openstreetmap.josm.io.OsmTransferException; import org.openstreetmap.josm.plugins.notes.Note; import org.openstreetmap.josm.plugins.notes.NotesXmlParser; import org.openstreetmap.josm.tools.Utils; import org.openstreetmap.josm.data.Bounds; import org.xml.sax.SAXException; public class NotesApi extends OsmConnection { private static String version = "0.6"; private String serverUrl; private static HashMap<String, NotesApi> instances = new HashMap<String, NotesApi>(); public List<Note> getNotesInBoundingBox(Bounds bounds) throws OsmTransferException { ProgressMonitor monitor = NullProgressMonitor.INSTANCE; String url = new StringBuilder() .append("notes?bbox=") .append(bounds.getMin().lon()) .append(",").append(bounds.getMin().lat()) .append(",").append(bounds.getMax().lon()) .append(",").append(bounds.getMax().lat()) .toString(); String response = sendRequest("GET", url, null, monitor, false, true); return parseNotes(response); } public void closeNote(Note note, String closeMessage) throws OsmTransferException { ProgressMonitor monitor = NullProgressMonitor.INSTANCE; String encodedMessage; try { encodedMessage = URLEncoder.encode(closeMessage, "UTF-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); return; } StringBuilder urlBuilder = new StringBuilder() .append("notes/") .append(note.getId()) .append("/close"); if(encodedMessage != null && !encodedMessage.trim().isEmpty()) { urlBuilder.append("?text="); urlBuilder.append(encodedMessage); } sendRequest("POST", urlBuilder.toString(), null, monitor, true, false); } public Note createNote(LatLon latlon, String text) throws OsmTransferException { ProgressMonitor monitor = NullProgressMonitor.INSTANCE; String encodedText; try { encodedText = URLEncoder.encode(text, "UTF-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); return null; } String url = new StringBuilder() .append("notes?lat=") .append(latlon.lat()) .append("&lon=") .append(latlon.lon()) .append("&text=") .append(encodedText).toString(); String response = sendRequest("POST", url, null, monitor, true, false); List<Note> newNote = parseNotes(response); if(newNote.size() != 0) { return newNote.get(0); } return null; } public Note AddCommentToNote(Note note, String comment) throws OsmTransferException { if(comment == null || comment.trim().isEmpty()) { return note; } ProgressMonitor monitor = NullProgressMonitor.INSTANCE; String encodedComment; try { encodedComment = URLEncoder.encode(comment, "UTF-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); return note; } String url = new StringBuilder() .append("notes/") .append(note.getId()) .append("/comment?text=") .append(encodedComment).toString(); String response = sendRequest("POST", url, null, monitor, true, false); List<Note> modifiedNote = parseNotes(response); if(modifiedNote.size() !=0) { return modifiedNote.get(0); } return note; } private List<Note> parseNotes(String notesXml) { try { return NotesXmlParser.parseNotes(notesXml); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return new ArrayList<Note>(); } /** * The rest of this class is basically copy/paste from OsmApi.java in core. Since the * methods are private/protected, I copied them here. Hopefully notes functionality will * be integrated into core at some point since this is now a core OSM API feature * and this copy/paste business can go away. */ protected NotesApi(String serverUrl) { this.serverUrl = serverUrl; } static public NotesApi getNotesApi(String serverUrl) { NotesApi api = instances.get(serverUrl); if (api == null) { api = new NotesApi(serverUrl); instances.put(serverUrl, api); } return api; } public static NotesApi getNotesApi() { String serverUrl = Main.pref.get("osm-server.url", OsmApi.DEFAULT_API_URL); if (serverUrl == null) throw new IllegalStateException(tr("Preference ''{0}'' missing. Cannot initialize NotesApi.", "osm-server.url")); return getNotesApi(serverUrl); } private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException { StringBuffer responseBody = new StringBuffer(); int retries = fastFail ? 0 : getMaxRetries(); while(true) { // the retry loop try { URL url = new URL(new URL(getBaseUrl()), urlSuffix); System.out.print(requestMethod + " " + url + "... "); // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive activeConnection = Utils.openHttpConnection(url, false); activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000); if (fastFail) { activeConnection.setReadTimeout(1000); } activeConnection.setRequestMethod(requestMethod); if (doAuthenticate) { addAuth(activeConnection); } if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) { activeConnection.setDoOutput(true); activeConnection.setRequestProperty("Content-type", "text/xml"); OutputStream out = activeConnection.getOutputStream(); // It seems that certain bits of the Ruby API are very unhappy upon // receipt of a PUT/POST message without a Content-length header, // even if the request has no payload. // Since Java will not generate a Content-length header unless // we use the output stream, we create an output stream for PUT/POST // even if there is no payload. if (requestBody != null) { BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); bwr.write(requestBody); bwr.flush(); } Utils.close(out); } activeConnection.connect(); System.out.println(activeConnection.getResponseMessage()); int retCode = activeConnection.getResponseCode(); if (retCode >= 500) { if (retries-- > 0) { sleepAndListen(retries, monitor); System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries())); continue; } } // populate return fields. responseBody.setLength(0); // If the API returned an error code like 403 forbidden, getInputStream // will fail with an IOException. InputStream i = null; try { i = activeConnection.getInputStream(); } catch (IOException ioe) { i = activeConnection.getErrorStream(); } if (i != null) { // the input stream can be null if both the input and the error stream // are null. Seems to be the case if the OSM server replies a 401 // Unauthorized, see #3887. // - BufferedReader in = new BufferedReader(new InputStreamReader(i)); + BufferedReader in = new BufferedReader(new InputStreamReader(i, "UTF-8")); String s; while((s = in.readLine()) != null) { responseBody.append(s); responseBody.append("\n"); } } String errorHeader = null; // Look for a detailed error message from the server if (activeConnection.getHeaderField("Error") != null) { errorHeader = activeConnection.getHeaderField("Error"); System.err.println("Error header: " + errorHeader); } else if (retCode != 200 && responseBody.length()>0) { System.err.println("Error body: " + responseBody); } activeConnection.disconnect(); errorHeader = errorHeader == null? null : errorHeader.trim(); String errorBody = responseBody.length() == 0? null : responseBody.toString().trim(); switch(retCode) { case HttpURLConnection.HTTP_OK: return responseBody.toString(); case HttpURLConnection.HTTP_GONE: throw new OsmApiPrimitiveGoneException(errorHeader, errorBody); case HttpURLConnection.HTTP_CONFLICT: if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader)) throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA); else throw new OsmApiException(retCode, errorHeader, errorBody); case HttpURLConnection.HTTP_FORBIDDEN: OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody); e.setAccessedUrl(activeConnection.getURL().toString()); throw e; default: throw new OsmApiException(retCode, errorHeader, errorBody); } } catch (UnknownHostException e) { throw new OsmTransferException(e); } catch (SocketTimeoutException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch (ConnectException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch(IOException e){ throw new OsmTransferException(e); } catch(OsmTransferCanceledException e){ throw e; } catch(OsmTransferException e) { throw e; } } } protected int getMaxRetries() { int ret = Main.pref.getInteger("osm-server.max-num-retries", OsmApi.DEFAULT_MAX_NUM_RETRIES); return Math.max(ret,0); } private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException { System.out.print(tr("Waiting 10 seconds ... ")); for(int i=0; i < 10; i++) { if (monitor != null) { monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry,getMaxRetries(), 10-i)); } if (cancel) throw new OsmTransferCanceledException(); try { Thread.sleep(1000); } catch (InterruptedException ex) {} } System.out.println(tr("OK - trying again.")); } public String getBaseUrl() { StringBuffer rv = new StringBuffer(serverUrl); if (version != null) { rv.append("/"); rv.append(version); } rv.append("/"); // this works around a ruby (or lighttpd) bug where two consecutive slashes in // an URL will cause a "404 not found" response. int p; while ((p = rv.indexOf("//", 6)) > -1) { rv.delete(p, p + 1); } return rv.toString(); } }
true
true
private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException { StringBuffer responseBody = new StringBuffer(); int retries = fastFail ? 0 : getMaxRetries(); while(true) { // the retry loop try { URL url = new URL(new URL(getBaseUrl()), urlSuffix); System.out.print(requestMethod + " " + url + "... "); // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive activeConnection = Utils.openHttpConnection(url, false); activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000); if (fastFail) { activeConnection.setReadTimeout(1000); } activeConnection.setRequestMethod(requestMethod); if (doAuthenticate) { addAuth(activeConnection); } if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) { activeConnection.setDoOutput(true); activeConnection.setRequestProperty("Content-type", "text/xml"); OutputStream out = activeConnection.getOutputStream(); // It seems that certain bits of the Ruby API are very unhappy upon // receipt of a PUT/POST message without a Content-length header, // even if the request has no payload. // Since Java will not generate a Content-length header unless // we use the output stream, we create an output stream for PUT/POST // even if there is no payload. if (requestBody != null) { BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); bwr.write(requestBody); bwr.flush(); } Utils.close(out); } activeConnection.connect(); System.out.println(activeConnection.getResponseMessage()); int retCode = activeConnection.getResponseCode(); if (retCode >= 500) { if (retries-- > 0) { sleepAndListen(retries, monitor); System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries())); continue; } } // populate return fields. responseBody.setLength(0); // If the API returned an error code like 403 forbidden, getInputStream // will fail with an IOException. InputStream i = null; try { i = activeConnection.getInputStream(); } catch (IOException ioe) { i = activeConnection.getErrorStream(); } if (i != null) { // the input stream can be null if both the input and the error stream // are null. Seems to be the case if the OSM server replies a 401 // Unauthorized, see #3887. // BufferedReader in = new BufferedReader(new InputStreamReader(i)); String s; while((s = in.readLine()) != null) { responseBody.append(s); responseBody.append("\n"); } } String errorHeader = null; // Look for a detailed error message from the server if (activeConnection.getHeaderField("Error") != null) { errorHeader = activeConnection.getHeaderField("Error"); System.err.println("Error header: " + errorHeader); } else if (retCode != 200 && responseBody.length()>0) { System.err.println("Error body: " + responseBody); } activeConnection.disconnect(); errorHeader = errorHeader == null? null : errorHeader.trim(); String errorBody = responseBody.length() == 0? null : responseBody.toString().trim(); switch(retCode) { case HttpURLConnection.HTTP_OK: return responseBody.toString(); case HttpURLConnection.HTTP_GONE: throw new OsmApiPrimitiveGoneException(errorHeader, errorBody); case HttpURLConnection.HTTP_CONFLICT: if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader)) throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA); else throw new OsmApiException(retCode, errorHeader, errorBody); case HttpURLConnection.HTTP_FORBIDDEN: OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody); e.setAccessedUrl(activeConnection.getURL().toString()); throw e; default: throw new OsmApiException(retCode, errorHeader, errorBody); } } catch (UnknownHostException e) { throw new OsmTransferException(e); } catch (SocketTimeoutException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch (ConnectException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch(IOException e){ throw new OsmTransferException(e); } catch(OsmTransferCanceledException e){ throw e; } catch(OsmTransferException e) { throw e; } } }
private String sendRequest(String requestMethod, String urlSuffix,String requestBody, ProgressMonitor monitor, boolean doAuthenticate, boolean fastFail) throws OsmTransferException { StringBuffer responseBody = new StringBuffer(); int retries = fastFail ? 0 : getMaxRetries(); while(true) { // the retry loop try { URL url = new URL(new URL(getBaseUrl()), urlSuffix); System.out.print(requestMethod + " " + url + "... "); // fix #5369, see http://www.tikalk.com/java/forums/httpurlconnection-disable-keep-alive activeConnection = Utils.openHttpConnection(url, false); activeConnection.setConnectTimeout(fastFail ? 1000 : Main.pref.getInteger("socket.timeout.connect",15)*1000); if (fastFail) { activeConnection.setReadTimeout(1000); } activeConnection.setRequestMethod(requestMethod); if (doAuthenticate) { addAuth(activeConnection); } if (requestMethod.equals("PUT") || requestMethod.equals("POST") || requestMethod.equals("DELETE")) { activeConnection.setDoOutput(true); activeConnection.setRequestProperty("Content-type", "text/xml"); OutputStream out = activeConnection.getOutputStream(); // It seems that certain bits of the Ruby API are very unhappy upon // receipt of a PUT/POST message without a Content-length header, // even if the request has no payload. // Since Java will not generate a Content-length header unless // we use the output stream, we create an output stream for PUT/POST // even if there is no payload. if (requestBody != null) { BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); bwr.write(requestBody); bwr.flush(); } Utils.close(out); } activeConnection.connect(); System.out.println(activeConnection.getResponseMessage()); int retCode = activeConnection.getResponseCode(); if (retCode >= 500) { if (retries-- > 0) { sleepAndListen(retries, monitor); System.out.println(tr("Starting retry {0} of {1}.", getMaxRetries() - retries,getMaxRetries())); continue; } } // populate return fields. responseBody.setLength(0); // If the API returned an error code like 403 forbidden, getInputStream // will fail with an IOException. InputStream i = null; try { i = activeConnection.getInputStream(); } catch (IOException ioe) { i = activeConnection.getErrorStream(); } if (i != null) { // the input stream can be null if both the input and the error stream // are null. Seems to be the case if the OSM server replies a 401 // Unauthorized, see #3887. // BufferedReader in = new BufferedReader(new InputStreamReader(i, "UTF-8")); String s; while((s = in.readLine()) != null) { responseBody.append(s); responseBody.append("\n"); } } String errorHeader = null; // Look for a detailed error message from the server if (activeConnection.getHeaderField("Error") != null) { errorHeader = activeConnection.getHeaderField("Error"); System.err.println("Error header: " + errorHeader); } else if (retCode != 200 && responseBody.length()>0) { System.err.println("Error body: " + responseBody); } activeConnection.disconnect(); errorHeader = errorHeader == null? null : errorHeader.trim(); String errorBody = responseBody.length() == 0? null : responseBody.toString().trim(); switch(retCode) { case HttpURLConnection.HTTP_OK: return responseBody.toString(); case HttpURLConnection.HTTP_GONE: throw new OsmApiPrimitiveGoneException(errorHeader, errorBody); case HttpURLConnection.HTTP_CONFLICT: if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader)) throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA); else throw new OsmApiException(retCode, errorHeader, errorBody); case HttpURLConnection.HTTP_FORBIDDEN: OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody); e.setAccessedUrl(activeConnection.getURL().toString()); throw e; default: throw new OsmApiException(retCode, errorHeader, errorBody); } } catch (UnknownHostException e) { throw new OsmTransferException(e); } catch (SocketTimeoutException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch (ConnectException e) { if (retries-- > 0) { continue; } throw new OsmTransferException(e); } catch(IOException e){ throw new OsmTransferException(e); } catch(OsmTransferCanceledException e){ throw e; } catch(OsmTransferException e) { throw e; } } }
diff --git a/table-browser-impl/src/main/java/org/cytoscape/browser/internal/GlobalTableBrowser.java b/table-browser-impl/src/main/java/org/cytoscape/browser/internal/GlobalTableBrowser.java index ad27276b6..eed6fff8b 100644 --- a/table-browser-impl/src/main/java/org/cytoscape/browser/internal/GlobalTableBrowser.java +++ b/table-browser-impl/src/main/java/org/cytoscape/browser/internal/GlobalTableBrowser.java @@ -1,196 +1,199 @@ package org.cytoscape.browser.internal; /* * #%L * Cytoscape Table Browser Impl (table-browser-impl) * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2006 - 2013 The Cytoscape Consortium * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.util.Properties; import javax.swing.SwingUtilities; import org.cytoscape.application.CyApplicationManager; import org.cytoscape.application.swing.CytoPanelComponent; import org.cytoscape.browser.internal.TableChooser.GlobalTableComboBoxModel; import org.cytoscape.equations.EquationCompiler; import org.cytoscape.event.CyEventHelper; import org.cytoscape.model.CyNetworkManager; import org.cytoscape.model.CyNetworkTableManager; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyTableManager; import org.cytoscape.model.events.RowsSetEvent; import org.cytoscape.model.events.RowsSetListener; import org.cytoscape.model.events.TableAboutToBeDeletedEvent; import org.cytoscape.model.events.TableAboutToBeDeletedListener; import org.cytoscape.model.events.TableAddedEvent; import org.cytoscape.model.events.TableAddedListener; import org.cytoscape.model.events.TablePrivacyChangedEvent; import org.cytoscape.model.events.TablePrivacyChangedListener; import org.cytoscape.service.util.CyServiceRegistrar; import org.cytoscape.task.destroy.DeleteTableTaskFactory; import org.cytoscape.work.swing.DialogTaskManager; public class GlobalTableBrowser extends AbstractTableBrowser implements TableAboutToBeDeletedListener, RowsSetListener, TableAddedListener, TablePrivacyChangedListener { private static final long serialVersionUID = 2269984225983802421L; static final Color GLOBAL_TABLE_COLOR = new Color(0x1E, 0x90, 0xFF); static final Color GLOBAL_TABLE_ENTRY_COLOR = new Color(0x1E, 0x90, 0xFF, 150); static final Color GLOBAL_TABLE_BACKGROUND_COLOR = new Color(0x87, 0xCE, 0xFA, 50); static final Font GLOBAL_FONT = new Font("SansSerif", Font.BOLD, 12); private final TableChooser tableChooser; public GlobalTableBrowser(String tabTitle, CyTableManager tableManager, CyNetworkTableManager networkTableManager, CyServiceRegistrar serviceRegistrar, EquationCompiler compiler, CyNetworkManager networkManager, DeleteTableTaskFactory deleteTableTaskFactoryService, DialogTaskManager guiTaskManagerServiceRef, PopupMenuHelper popupMenuHelper, CyApplicationManager applicationManager, CyEventHelper eventHelper){//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) { super(tabTitle, tableManager, networkTableManager, serviceRegistrar, compiler, networkManager, deleteTableTaskFactoryService, guiTaskManagerServiceRef, popupMenuHelper, applicationManager, eventHelper); tableChooser = new TableChooser(); tableChooser.addActionListener(this); tableChooser.setMaximumSize(SELECTOR_SIZE); tableChooser.setMinimumSize(SELECTOR_SIZE); tableChooser.setPreferredSize(SELECTOR_SIZE); tableChooser.setSize(SELECTOR_SIZE); tableChooser.setFont(GLOBAL_FONT); tableChooser.setForeground(GLOBAL_TABLE_COLOR); tableChooser.setToolTipText("\"Tables\" are data tables not associated with specific networks."); tableChooser.setEnabled(false); attributeBrowserToolBar = new AttributeBrowserToolBar(serviceRegistrar, compiler, deleteTableTaskFactoryService, guiTaskManagerServiceRef, tableChooser, null, applicationManager);//, mapGlobalTableTaskFactoryService); add(attributeBrowserToolBar, BorderLayout.NORTH); } @Override public void actionPerformed(final ActionEvent e) { final CyTable table = (CyTable) tableChooser.getSelectedItem(); if (table == currentTable || table == null) return; currentTable = table; //applicationManager.setCurrentGlobalTable(table); showSelectedTable(); } @Override public void handleEvent(final TableAboutToBeDeletedEvent e) { final CyTable cyTable = e.getTable(); if (cyTable.isPublic()) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.removeItem(cyTable); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(cyTable); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); //applicationManager.setCurrentGlobalTable(null); showSelectedTable(); } }); } } } /** * Switch to new table when it is registered to the table manager. * * Note: This combo box only displays Global Table. */ @Override public void handleEvent(TableAddedEvent e) { final CyTable newTable = e.getTable(); if (newTable.isPublic()) { if (tableManager.getGlobalTables().contains(newTable)) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.addAndSetSelectedItem(newTable); } if (tableChooser.getItemCount() == 1) { SwingUtilities.invokeLater( new Runnable() { public void run() { serviceRegistrar.registerService(GlobalTableBrowser.this, CytoPanelComponent.class, new Properties()); //applicationManager.setCurrentGlobalTable(newTable); } }); } if (tableChooser.getItemCount() != 0) tableChooser.setEnabled(true); } } @Override public void handleEvent(TablePrivacyChangedEvent e) { final CyTable table = e.getSource(); final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); if(!table.isPublic()){ comboBoxModel.removeItem(table); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(table); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); showSelectedTable(); } }); } }else comboBoxModel.addAndSetSelectedItem(table); } @Override public void handleEvent(final RowsSetEvent e) { - BrowserTableModel model = (BrowserTableModel) getCurrentBrowserTable().getModel(); + BrowserTable table = getCurrentBrowserTable(); + if (table == null) + return; + BrowserTableModel model = (BrowserTableModel) table.getModel(); CyTable dataTable = model.getDataTable(); if (e.getSource() != dataTable) return; synchronized (this) { model.fireTableDataChanged(); } } }
true
true
public GlobalTableBrowser(String tabTitle, CyTableManager tableManager, CyNetworkTableManager networkTableManager, CyServiceRegistrar serviceRegistrar, EquationCompiler compiler, CyNetworkManager networkManager, DeleteTableTaskFactory deleteTableTaskFactoryService, DialogTaskManager guiTaskManagerServiceRef, PopupMenuHelper popupMenuHelper, CyApplicationManager applicationManager, CyEventHelper eventHelper){//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) { super(tabTitle, tableManager, networkTableManager, serviceRegistrar, compiler, networkManager, deleteTableTaskFactoryService, guiTaskManagerServiceRef, popupMenuHelper, applicationManager, eventHelper); tableChooser = new TableChooser(); tableChooser.addActionListener(this); tableChooser.setMaximumSize(SELECTOR_SIZE); tableChooser.setMinimumSize(SELECTOR_SIZE); tableChooser.setPreferredSize(SELECTOR_SIZE); tableChooser.setSize(SELECTOR_SIZE); tableChooser.setFont(GLOBAL_FONT); tableChooser.setForeground(GLOBAL_TABLE_COLOR); tableChooser.setToolTipText("\"Tables\" are data tables not associated with specific networks."); tableChooser.setEnabled(false); attributeBrowserToolBar = new AttributeBrowserToolBar(serviceRegistrar, compiler, deleteTableTaskFactoryService, guiTaskManagerServiceRef, tableChooser, null, applicationManager);//, mapGlobalTableTaskFactoryService); add(attributeBrowserToolBar, BorderLayout.NORTH); } @Override public void actionPerformed(final ActionEvent e) { final CyTable table = (CyTable) tableChooser.getSelectedItem(); if (table == currentTable || table == null) return; currentTable = table; //applicationManager.setCurrentGlobalTable(table); showSelectedTable(); } @Override public void handleEvent(final TableAboutToBeDeletedEvent e) { final CyTable cyTable = e.getTable(); if (cyTable.isPublic()) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.removeItem(cyTable); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(cyTable); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); //applicationManager.setCurrentGlobalTable(null); showSelectedTable(); } }); } } } /** * Switch to new table when it is registered to the table manager. * * Note: This combo box only displays Global Table. */ @Override public void handleEvent(TableAddedEvent e) { final CyTable newTable = e.getTable(); if (newTable.isPublic()) { if (tableManager.getGlobalTables().contains(newTable)) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.addAndSetSelectedItem(newTable); } if (tableChooser.getItemCount() == 1) { SwingUtilities.invokeLater( new Runnable() { public void run() { serviceRegistrar.registerService(GlobalTableBrowser.this, CytoPanelComponent.class, new Properties()); //applicationManager.setCurrentGlobalTable(newTable); } }); } if (tableChooser.getItemCount() != 0) tableChooser.setEnabled(true); } } @Override public void handleEvent(TablePrivacyChangedEvent e) { final CyTable table = e.getSource(); final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); if(!table.isPublic()){ comboBoxModel.removeItem(table); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(table); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); showSelectedTable(); } }); } }else comboBoxModel.addAndSetSelectedItem(table); } @Override public void handleEvent(final RowsSetEvent e) { BrowserTableModel model = (BrowserTableModel) getCurrentBrowserTable().getModel(); CyTable dataTable = model.getDataTable(); if (e.getSource() != dataTable) return; synchronized (this) { model.fireTableDataChanged(); } } }
public GlobalTableBrowser(String tabTitle, CyTableManager tableManager, CyNetworkTableManager networkTableManager, CyServiceRegistrar serviceRegistrar, EquationCompiler compiler, CyNetworkManager networkManager, DeleteTableTaskFactory deleteTableTaskFactoryService, DialogTaskManager guiTaskManagerServiceRef, PopupMenuHelper popupMenuHelper, CyApplicationManager applicationManager, CyEventHelper eventHelper){//, final MapGlobalToLocalTableTaskFactory mapGlobalTableTaskFactoryService) { super(tabTitle, tableManager, networkTableManager, serviceRegistrar, compiler, networkManager, deleteTableTaskFactoryService, guiTaskManagerServiceRef, popupMenuHelper, applicationManager, eventHelper); tableChooser = new TableChooser(); tableChooser.addActionListener(this); tableChooser.setMaximumSize(SELECTOR_SIZE); tableChooser.setMinimumSize(SELECTOR_SIZE); tableChooser.setPreferredSize(SELECTOR_SIZE); tableChooser.setSize(SELECTOR_SIZE); tableChooser.setFont(GLOBAL_FONT); tableChooser.setForeground(GLOBAL_TABLE_COLOR); tableChooser.setToolTipText("\"Tables\" are data tables not associated with specific networks."); tableChooser.setEnabled(false); attributeBrowserToolBar = new AttributeBrowserToolBar(serviceRegistrar, compiler, deleteTableTaskFactoryService, guiTaskManagerServiceRef, tableChooser, null, applicationManager);//, mapGlobalTableTaskFactoryService); add(attributeBrowserToolBar, BorderLayout.NORTH); } @Override public void actionPerformed(final ActionEvent e) { final CyTable table = (CyTable) tableChooser.getSelectedItem(); if (table == currentTable || table == null) return; currentTable = table; //applicationManager.setCurrentGlobalTable(table); showSelectedTable(); } @Override public void handleEvent(final TableAboutToBeDeletedEvent e) { final CyTable cyTable = e.getTable(); if (cyTable.isPublic()) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.removeItem(cyTable); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(cyTable); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); //applicationManager.setCurrentGlobalTable(null); showSelectedTable(); } }); } } } /** * Switch to new table when it is registered to the table manager. * * Note: This combo box only displays Global Table. */ @Override public void handleEvent(TableAddedEvent e) { final CyTable newTable = e.getTable(); if (newTable.isPublic()) { if (tableManager.getGlobalTables().contains(newTable)) { final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); comboBoxModel.addAndSetSelectedItem(newTable); } if (tableChooser.getItemCount() == 1) { SwingUtilities.invokeLater( new Runnable() { public void run() { serviceRegistrar.registerService(GlobalTableBrowser.this, CytoPanelComponent.class, new Properties()); //applicationManager.setCurrentGlobalTable(newTable); } }); } if (tableChooser.getItemCount() != 0) tableChooser.setEnabled(true); } } @Override public void handleEvent(TablePrivacyChangedEvent e) { final CyTable table = e.getSource(); final GlobalTableComboBoxModel comboBoxModel = (GlobalTableComboBoxModel) tableChooser.getModel(); if(!table.isPublic()){ comboBoxModel.removeItem(table); if (comboBoxModel.getSize() == 0) { tableChooser.setEnabled(false); // The last table is deleted, refresh the browser table (this is a special case) deleteTable(table); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { serviceRegistrar.unregisterService(GlobalTableBrowser.this, CytoPanelComponent.class); showSelectedTable(); } }); } }else comboBoxModel.addAndSetSelectedItem(table); } @Override public void handleEvent(final RowsSetEvent e) { BrowserTable table = getCurrentBrowserTable(); if (table == null) return; BrowserTableModel model = (BrowserTableModel) table.getModel(); CyTable dataTable = model.getDataTable(); if (e.getSource() != dataTable) return; synchronized (this) { model.fireTableDataChanged(); } } }
diff --git a/src/main/java/com/github/rnewson/couchdb/lucene/Indexer.java b/src/main/java/com/github/rnewson/couchdb/lucene/Indexer.java index 720f53e..e312d8c 100644 --- a/src/main/java/com/github/rnewson/couchdb/lucene/Indexer.java +++ b/src/main/java/com/github/rnewson/couchdb/lucene/Indexer.java @@ -1,457 +1,457 @@ package com.github.rnewson.couchdb.lucene; import static java.util.concurrent.TimeUnit.SECONDS; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.io.IOUtils; import org.apache.http.client.HttpResponseException; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Document; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.mortbay.component.AbstractLifeCycle; import org.mozilla.javascript.ClassShutter; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; import com.github.rnewson.couchdb.lucene.LuceneGateway.ReaderCallback; import com.github.rnewson.couchdb.lucene.LuceneGateway.WriterCallback; import com.github.rnewson.couchdb.lucene.RhinoDocument.RhinoContext; import com.github.rnewson.couchdb.lucene.couchdb.Database; import com.github.rnewson.couchdb.lucene.couchdb.Database.Action; import com.github.rnewson.couchdb.lucene.couchdb.Database.ChangesHandler; import com.github.rnewson.couchdb.lucene.util.Analyzers; import com.github.rnewson.couchdb.lucene.util.Constants; import com.github.rnewson.couchdb.lucene.util.Utils; /** * Indexes data from couchdb into Lucene indexes. * * @author robertnewson */ public final class Indexer extends AbstractLifeCycle { private class CouchIndexer implements Runnable { private final Logger logger = Logger.getLogger(CouchIndexer.class); public void run() { try { final String[] databases = state.couch.getAllDatabases(); synchronized (activeTasks) { for (final String databaseName : databases) { if (!activeTasks.contains(databaseName)) { activeTasks.add(databaseName); executor.execute(new DatabaseIndexer(databaseName)); } } } } catch (final IOException e) { // Ignore. } } } private class DatabaseIndexer implements Runnable { private final class DatabaseChangesHandler implements ChangesHandler { public void onError(final JSONObject error) { if (error.optString("reason").equals("no_db_file")) { logger.warn("Database deleted."); try { state.lucene.deleteDatabase(databaseName); } catch (final IOException e) { logger.warn("Failed to delete indexes for database " + databaseName, e); } } else { logger.warn("Unexpected error: " + error); } } public void onEndOfSequence(final long seq) throws IOException { if (hasPendingCommit(true)) { commitDocuments(); } } public void onChange(final long seq, final JSONObject doc) throws IOException { // Time's up. if (hasPendingCommit(false)) { commitDocuments(); } final String id = doc.getString("_id"); // New, updated or deleted document. if (id.startsWith("_design")) { logUpdate(seq, id, "updated"); mapDesignDocument(doc); // TODO force reindexing of this function ONLY. } else if (doc.optBoolean("_deleted")) { logUpdate(seq, id, "deleted"); deleteDocument(doc); } else { logUpdate(seq, id, "updated"); updateDocument(doc); } // Remember progress. since = seq; } private void logUpdate(final long seq, final String id, final String suffix) { if (logger.isTraceEnabled()) { logger.trace(String.format("seq:%d id:%s %s", seq, id, suffix)); } } private void commitDocuments() throws IOException { final JSONObject tracker = fetchTrackingDocument(database); tracker.put("update_seq", since); for (final ViewSignature sig : functions.keySet()) { // Fetch or generate index uuid. final String uuid = state.lucene.withReader(sig, new ReaderCallback<String>() { public String callback(final IndexReader reader) throws IOException { final String result = (String) reader.getCommitUserData().get("uuid"); return result != null ? result : UUID.randomUUID().toString(); } }); tracker.put(sig.toString(), uuid); // Tell Lucene. state.lucene.withWriter(sig, new WriterCallback<Void>() { public Void callback(final IndexWriter writer) throws IOException { final Map<String, String> commitUserData = new HashMap<String, String>(); commitUserData.put("update_seq", Long.toString(since)); commitUserData.put("uuid", uuid); logger.debug("Committing changes to " + sig + " with " + commitUserData); /* * commit data is not written if there are no * documents. */ if (writer.maxDoc() == 0) { writer.addDocument(new Document()); } writer.commit(commitUserData); return null; } }); } // Tell Couch. database.saveDocument("_local/lucene", tracker.toString()); setPendingCommit(false); } private void deleteDocument(final JSONObject doc) throws IOException { for (final ViewSignature sig : functions.keySet()) { state.lucene.withWriter(sig, new WriterCallback<Void>() { public Void callback(final IndexWriter writer) throws IOException { writer.deleteDocuments(new Term("_id", doc.getString("_id"))); setPendingCommit(true); return null; } }); } } private void updateDocument(final JSONObject doc) { for (final Entry<ViewSignature, ViewTuple> entry : functions.entrySet()) { final RhinoContext rhinoContext = new RhinoContext(); rhinoContext.analyzer = entry.getValue().analyzer; rhinoContext.database = database; rhinoContext.defaults = entry.getValue().defaults; rhinoContext.documentId = doc.getString("_id"); rhinoContext.state = state; try { final Object result = main.call(context, scope, null, new Object[] { doc.toString(), entry.getValue().function }); if (result == null || result instanceof Undefined) { return; } state.lucene.withWriter(entry.getKey(), new WriterCallback<Void>() { public Void callback(final IndexWriter writer) throws IOException { if (result instanceof RhinoDocument) { ((RhinoDocument) result).addDocument(rhinoContext, writer); } else if (result instanceof NativeArray) { final NativeArray array = (NativeArray) result; for (int i = 0; i < (int) array.getLength(); i++) { if (array.get(i, null) instanceof RhinoDocument) { ((RhinoDocument) array.get(i, null)).addDocument(rhinoContext, writer); } } } return null; } }); setPendingCommit(true); } catch (final RhinoException e) { - logger.warn("doc '" + doc.getString("id") + "' caused exception.", e); + logger.warn("doc '" + doc.getString("_id") + "' caused exception.", e); } catch (final IOException e) { - logger.warn("doc '" + doc.getString("id") + "' caused exception.", e); + logger.warn("doc '" + doc.getString("_id") + "' caused exception.", e); } } } } private final class RestrictiveClassShutter implements ClassShutter { public boolean visibleToScripts(final String fullClassName) { return false; } } private Context context; private final Database database; private final String databaseName; private final Map<ViewSignature, ViewTuple> functions = new HashMap<ViewSignature, ViewTuple>(); private final Logger logger; private Function main; private boolean pendingCommit; private long pendingSince; private ScriptableObject scope; private long since = 0L; public DatabaseIndexer(final String databaseName) { logger = Utils.getLogger(DatabaseIndexer.class, databaseName); this.databaseName = databaseName; this.database = state.couch.getDatabase(databaseName); } public void run() { logger.debug("Tracking begins"); try { enterContext(); final boolean isLuceneEnabled = mapAllDesignDocuments(); if (!isLuceneEnabled) { logger.debug("No fulltext functions found."); return; } readCheckpoints(); loop: while (isRunning()) { switch (updateIndexes()) { case ABORT: break loop; case CONTINUE: break; case PAUSE: SECONDS.sleep(10); break; } } } catch (final Exception e) { logger.warn("Tracking interrupted by exception.", e); } finally { leaveContext(); untrack(); } } private JSONObject defaults() { final JSONObject result = new JSONObject(); result.put("field", Constants.DEFAULT_FIELD); result.put("store", "no"); result.put("index", "analyzed"); result.put("type", "string"); return result; } private void enterContext() throws Exception { context = ContextFactory.getGlobal().enterContext(); // Optimize as much as possible. context.setOptimizationLevel(9); // Security restrictions context.setClassShutter(new RestrictiveClassShutter()); // Setup. scope = context.initStandardObjects(); // Allow custom document helper class. ScriptableObject.defineClass(scope, RhinoDocument.class); // Load JSON parser. context.evaluateString(scope, loadResource("json2.js"), "json2", 0, null); // Define outer function. main = context.compileFunction(scope, "function(json, func){return func(JSON.parse(json));}", "main", 0, null); } private boolean hasPendingCommit(final boolean ignoreTimeout) { if (ignoreTimeout) { return pendingCommit; } if (!pendingCommit) { return false; } return (now() - pendingSince) >= COMMIT_INTERVAL; } private void leaveContext() { Context.exit(); } private String loadResource(final String name) throws IOException { final InputStream in = Indexer.class.getClassLoader().getResourceAsStream(name); try { return IOUtils.toString(in, "UTF-8"); } finally { in.close(); } } private boolean mapAllDesignDocuments() throws IOException { final JSONArray designDocuments = database.getAllDesignDocuments(databaseName); boolean isLuceneEnabled = false; for (int i = 0; i < designDocuments.size(); i++) { isLuceneEnabled |= mapDesignDocument(designDocuments.getJSONObject(i).getJSONObject("doc")); } return isLuceneEnabled; } private boolean mapDesignDocument(final JSONObject designDocument) { final String designDocumentName = designDocument.getString("_id").substring(8); final JSONObject fulltext = designDocument.getJSONObject("fulltext"); boolean isLuceneEnabled = false; if (fulltext != null) { for (final Object obj : fulltext.keySet()) { final String viewName = (String) obj; final JSONObject viewValue = fulltext.getJSONObject(viewName); final JSONObject defaults = viewValue.has("defaults") ? viewValue.getJSONObject("defaults") : defaults(); final Analyzer analyzer = Analyzers.getAnalyzer(viewValue.optString("analyzer", "standard")); String function = viewValue.getString("index"); function = function.replaceFirst("^\"", ""); function = function.replaceFirst("\"$", ""); final ViewSignature sig = state.locator .update(databaseName, designDocumentName, viewName, viewValue.toString()); functions.put(sig, new ViewTuple(defaults, analyzer, context .compileFunction(scope, function, viewName, 0, null))); isLuceneEnabled = true; } } return isLuceneEnabled; } private long now() { return System.nanoTime(); } private void readCheckpoints() throws IOException { long since = Long.MAX_VALUE; for (final ViewSignature sig : functions.keySet()) { since = Math.min(since, state.lucene.withReader(sig, new ReaderCallback<Long>() { public Long callback(final IndexReader reader) throws IOException { final Map<String, String> commitUserData = reader.getCommitUserData(); final String result = commitUserData.get("update_seq"); return result != null ? Long.parseLong(result) : 0L; } })); } this.since = since; logger.debug("Existing indexes at update_seq " + since); } private void setPendingCommit(final boolean pendingCommit) { if (pendingCommit) { if (!this.pendingCommit) { this.pendingCommit = true; this.pendingSince = now(); } } else { this.pendingCommit = false; this.pendingSince = 0L; } } private void untrack() { synchronized (activeTasks) { activeTasks.remove(databaseName); } logger.debug("Tracking ends"); } /** * @return true if the indexing loop should continue, false to make it * exit. */ private Action updateIndexes() throws IOException { return database.handleChanges(since, new DatabaseChangesHandler()); } } private static class ViewTuple { private final Analyzer analyzer; private final JSONObject defaults; private final Function function; public ViewTuple(final JSONObject defaults, final Analyzer analyzer, final Function function) { this.defaults = defaults; this.analyzer = analyzer; this.function = function; } } private static final long COMMIT_INTERVAL = SECONDS.toNanos(60); private final Set<String> activeTasks = new HashSet<String>(); private ExecutorService executor; private ScheduledExecutorService scheduler; private final State state; public Indexer(final State state) { this.state = state; } private JSONObject fetchTrackingDocument(final Database database) throws IOException { try { return database.getDocument("_local/lucene"); } catch (final HttpResponseException e) { if (e.getStatusCode() == 404) { return new JSONObject(); } throw e; } } @Override protected void doStart() throws Exception { executor = Executors.newCachedThreadPool(); scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleWithFixedDelay(new CouchIndexer(), 0, 60, TimeUnit.SECONDS); } @Override protected void doStop() throws Exception { scheduler.shutdownNow(); executor.shutdownNow(); } }
false
true
private void updateDocument(final JSONObject doc) { for (final Entry<ViewSignature, ViewTuple> entry : functions.entrySet()) { final RhinoContext rhinoContext = new RhinoContext(); rhinoContext.analyzer = entry.getValue().analyzer; rhinoContext.database = database; rhinoContext.defaults = entry.getValue().defaults; rhinoContext.documentId = doc.getString("_id"); rhinoContext.state = state; try { final Object result = main.call(context, scope, null, new Object[] { doc.toString(), entry.getValue().function }); if (result == null || result instanceof Undefined) { return; } state.lucene.withWriter(entry.getKey(), new WriterCallback<Void>() { public Void callback(final IndexWriter writer) throws IOException { if (result instanceof RhinoDocument) { ((RhinoDocument) result).addDocument(rhinoContext, writer); } else if (result instanceof NativeArray) { final NativeArray array = (NativeArray) result; for (int i = 0; i < (int) array.getLength(); i++) { if (array.get(i, null) instanceof RhinoDocument) { ((RhinoDocument) array.get(i, null)).addDocument(rhinoContext, writer); } } } return null; } }); setPendingCommit(true); } catch (final RhinoException e) { logger.warn("doc '" + doc.getString("id") + "' caused exception.", e); } catch (final IOException e) { logger.warn("doc '" + doc.getString("id") + "' caused exception.", e); } } }
private void updateDocument(final JSONObject doc) { for (final Entry<ViewSignature, ViewTuple> entry : functions.entrySet()) { final RhinoContext rhinoContext = new RhinoContext(); rhinoContext.analyzer = entry.getValue().analyzer; rhinoContext.database = database; rhinoContext.defaults = entry.getValue().defaults; rhinoContext.documentId = doc.getString("_id"); rhinoContext.state = state; try { final Object result = main.call(context, scope, null, new Object[] { doc.toString(), entry.getValue().function }); if (result == null || result instanceof Undefined) { return; } state.lucene.withWriter(entry.getKey(), new WriterCallback<Void>() { public Void callback(final IndexWriter writer) throws IOException { if (result instanceof RhinoDocument) { ((RhinoDocument) result).addDocument(rhinoContext, writer); } else if (result instanceof NativeArray) { final NativeArray array = (NativeArray) result; for (int i = 0; i < (int) array.getLength(); i++) { if (array.get(i, null) instanceof RhinoDocument) { ((RhinoDocument) array.get(i, null)).addDocument(rhinoContext, writer); } } } return null; } }); setPendingCommit(true); } catch (final RhinoException e) { logger.warn("doc '" + doc.getString("_id") + "' caused exception.", e); } catch (final IOException e) { logger.warn("doc '" + doc.getString("_id") + "' caused exception.", e); } } }
diff --git a/WEB-INF/src/net/malta/web/app/MailAboutPurchaseToPublicUserAction.java b/WEB-INF/src/net/malta/web/app/MailAboutPurchaseToPublicUserAction.java index c87301d..bddf587 100644 --- a/WEB-INF/src/net/malta/web/app/MailAboutPurchaseToPublicUserAction.java +++ b/WEB-INF/src/net/malta/web/app/MailAboutPurchaseToPublicUserAction.java @@ -1,145 +1,140 @@ package net.malta.web.app; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.enclosing.util.SimpleMail; import net.malta.model.Choise; import net.malta.model.DeliveryAddress; import net.malta.model.DeliveryAddressChoise; import net.malta.model.Purchase; import net.malta.model.StaticData; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailAboutPurchaseToPublicUserAction extends Action{ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception{ // if (req.getParameter("id") != null // && !req.getParameter("id").equals("")) { // this.execute(Integer.valueOf(req.getParameter("id")), // this.getServlet().getServletContext(),Integer.parseInt((String)req.getSession().getAttribute("deliveryaddress"))); // }else{ // this.execute(null,this.getServlet().getServletContext()); // } return mapping.findForward("success"); } public void execute(Integer id,Session session,int deliverymethod){ SimpleMail mail = SimpleMail.create(new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml", "applicationContext-localDataSource.xml", "applicationContext-mail.xml" })); Criteria criteria = session.createCriteria(Purchase.class); criteria.add(Restrictions.eq("id", id)); Purchase purchase = (Purchase) criteria.uniqueResult(); Map model = new HashMap(); model.put("purchase", purchase); Locale l = new Locale("ja", "JP"); model.put("dateFormatter", new SimpleDateFormat("yyyy/MM/dd")); model.put("dayFormatter", new SimpleDateFormat("E", l)); model.put("timeFormatter", new SimpleDateFormat("HH:mm")); Criteria criteriastaticData = session.createCriteria(StaticData.class); criteriastaticData.add(Restrictions.eq("id", new Integer(1))); StaticData staticData = (StaticData) criteriastaticData.uniqueResult(); StringBuilder builder = new StringBuilder(); Criteria criteriaDeliveryAddressChoise = session.createCriteria(DeliveryAddressChoise.class); criteriaDeliveryAddressChoise.createCriteria("choise").add(Restrictions.eq("purchase", purchase)); //when there are no delivery address ( direct to public User) - builder.append("▼配送先情報(1)"); + builder.append("▼配送先情報"); builder.append("\r\n"); builder.append("================================================================"); builder.append("\r\n"); builder.append("お名前      :" ); System.out.println("purchase object "+purchase); System.out.println("publicuser "+purchase.getPublicUser()); builder.append(purchase.getPublicUser().getName() + "様"); builder.append("\r\n"); builder.append("フリガナ     :" ); builder.append(purchase.getPublicUser().getKana()); builder.append("\r\n"); builder.append("郵便番号     :" ); builder.append(purchase.getPublicUser().getZipfour()); builder.append("\r\n"); builder.append("ご住所      :" ); if(purchase.getPublicUser().getPrefecture()!=null){ builder.append(purchase.getPublicUser().getPrefecture().getName() + " " + purchase.getPublicUser().getAddress() + " " + purchase.getPublicUser().getBuildingname()); } builder.append("\r\n"); builder.append("電話番号     :" ); builder.append( purchase.getPublicUser().getPhone()); builder.append("\r\n"); builder.append("\r\n"); for (Iterator iterator = purchase.getChoises().iterator(); iterator.hasNext();) { Choise choise = (Choise) iterator.next(); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品詳細" ); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品名      :"); builder.append(choise.getName()); builder.append("\r\n"); builder.append("価格(税込)   :"); builder.append(choise.getPricewithtax()+"円"); builder.append("\r\n"); builder.append("数量       :"); builder.append(choise.getOrdernum()); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); - builder.append("送料       :"); - builder.append(choise.getCarriage()+"円"); - builder.append("\r\n"); - builder.append("----------------------------------------------------------------"); - builder.append("\r\n"); builder.append("\r\n"); } model.put("deliveryaddress",builder.toString().replaceAll("~", " - ")); // try { model.put("fromstring", MimeUtility.encodeText("AFRICA & LEO", "ISO-2022-JP", "B") + "<"+staticData.getFromaddress()+">"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } model.put("staticData", staticData); try { System.err.println("email sending to the admin---------------------------------------------"); mail.send("MailAboutPurchaseToPublicUser.eml", purchase.getPublicUser().getMail(), model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); System.err.println("email sent to the --------------------------------------------- " + purchase.getPublicUser().getMail()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
false
true
public void execute(Integer id,Session session,int deliverymethod){ SimpleMail mail = SimpleMail.create(new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml", "applicationContext-localDataSource.xml", "applicationContext-mail.xml" })); Criteria criteria = session.createCriteria(Purchase.class); criteria.add(Restrictions.eq("id", id)); Purchase purchase = (Purchase) criteria.uniqueResult(); Map model = new HashMap(); model.put("purchase", purchase); Locale l = new Locale("ja", "JP"); model.put("dateFormatter", new SimpleDateFormat("yyyy/MM/dd")); model.put("dayFormatter", new SimpleDateFormat("E", l)); model.put("timeFormatter", new SimpleDateFormat("HH:mm")); Criteria criteriastaticData = session.createCriteria(StaticData.class); criteriastaticData.add(Restrictions.eq("id", new Integer(1))); StaticData staticData = (StaticData) criteriastaticData.uniqueResult(); StringBuilder builder = new StringBuilder(); Criteria criteriaDeliveryAddressChoise = session.createCriteria(DeliveryAddressChoise.class); criteriaDeliveryAddressChoise.createCriteria("choise").add(Restrictions.eq("purchase", purchase)); //when there are no delivery address ( direct to public User) builder.append("▼配送先情報(1)"); builder.append("\r\n"); builder.append("================================================================"); builder.append("\r\n"); builder.append("お名前      :" ); System.out.println("purchase object "+purchase); System.out.println("publicuser "+purchase.getPublicUser()); builder.append(purchase.getPublicUser().getName() + "様"); builder.append("\r\n"); builder.append("フリガナ     :" ); builder.append(purchase.getPublicUser().getKana()); builder.append("\r\n"); builder.append("郵便番号     :" ); builder.append(purchase.getPublicUser().getZipfour()); builder.append("\r\n"); builder.append("ご住所      :" ); if(purchase.getPublicUser().getPrefecture()!=null){ builder.append(purchase.getPublicUser().getPrefecture().getName() + " " + purchase.getPublicUser().getAddress() + " " + purchase.getPublicUser().getBuildingname()); } builder.append("\r\n"); builder.append("電話番号     :" ); builder.append( purchase.getPublicUser().getPhone()); builder.append("\r\n"); builder.append("\r\n"); for (Iterator iterator = purchase.getChoises().iterator(); iterator.hasNext();) { Choise choise = (Choise) iterator.next(); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品詳細" ); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品名      :"); builder.append(choise.getName()); builder.append("\r\n"); builder.append("価格(税込)   :"); builder.append(choise.getPricewithtax()+"円"); builder.append("\r\n"); builder.append("数量       :"); builder.append(choise.getOrdernum()); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("送料       :"); builder.append(choise.getCarriage()+"円"); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("\r\n"); } model.put("deliveryaddress",builder.toString().replaceAll("~", " - ")); // try { model.put("fromstring", MimeUtility.encodeText("AFRICA & LEO", "ISO-2022-JP", "B") + "<"+staticData.getFromaddress()+">"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } model.put("staticData", staticData); try { System.err.println("email sending to the admin---------------------------------------------"); mail.send("MailAboutPurchaseToPublicUser.eml", purchase.getPublicUser().getMail(), model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); System.err.println("email sent to the --------------------------------------------- " + purchase.getPublicUser().getMail()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void execute(Integer id,Session session,int deliverymethod){ SimpleMail mail = SimpleMail.create(new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml", "applicationContext-localDataSource.xml", "applicationContext-mail.xml" })); Criteria criteria = session.createCriteria(Purchase.class); criteria.add(Restrictions.eq("id", id)); Purchase purchase = (Purchase) criteria.uniqueResult(); Map model = new HashMap(); model.put("purchase", purchase); Locale l = new Locale("ja", "JP"); model.put("dateFormatter", new SimpleDateFormat("yyyy/MM/dd")); model.put("dayFormatter", new SimpleDateFormat("E", l)); model.put("timeFormatter", new SimpleDateFormat("HH:mm")); Criteria criteriastaticData = session.createCriteria(StaticData.class); criteriastaticData.add(Restrictions.eq("id", new Integer(1))); StaticData staticData = (StaticData) criteriastaticData.uniqueResult(); StringBuilder builder = new StringBuilder(); Criteria criteriaDeliveryAddressChoise = session.createCriteria(DeliveryAddressChoise.class); criteriaDeliveryAddressChoise.createCriteria("choise").add(Restrictions.eq("purchase", purchase)); //when there are no delivery address ( direct to public User) builder.append("▼配送先情報"); builder.append("\r\n"); builder.append("================================================================"); builder.append("\r\n"); builder.append("お名前      :" ); System.out.println("purchase object "+purchase); System.out.println("publicuser "+purchase.getPublicUser()); builder.append(purchase.getPublicUser().getName() + "様"); builder.append("\r\n"); builder.append("フリガナ     :" ); builder.append(purchase.getPublicUser().getKana()); builder.append("\r\n"); builder.append("郵便番号     :" ); builder.append(purchase.getPublicUser().getZipfour()); builder.append("\r\n"); builder.append("ご住所      :" ); if(purchase.getPublicUser().getPrefecture()!=null){ builder.append(purchase.getPublicUser().getPrefecture().getName() + " " + purchase.getPublicUser().getAddress() + " " + purchase.getPublicUser().getBuildingname()); } builder.append("\r\n"); builder.append("電話番号     :" ); builder.append( purchase.getPublicUser().getPhone()); builder.append("\r\n"); builder.append("\r\n"); for (Iterator iterator = purchase.getChoises().iterator(); iterator.hasNext();) { Choise choise = (Choise) iterator.next(); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品詳細" ); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("商品名      :"); builder.append(choise.getName()); builder.append("\r\n"); builder.append("価格(税込)   :"); builder.append(choise.getPricewithtax()+"円"); builder.append("\r\n"); builder.append("数量       :"); builder.append(choise.getOrdernum()); builder.append("\r\n"); builder.append("----------------------------------------------------------------"); builder.append("\r\n"); builder.append("\r\n"); } model.put("deliveryaddress",builder.toString().replaceAll("~", " - ")); // try { model.put("fromstring", MimeUtility.encodeText("AFRICA & LEO", "ISO-2022-JP", "B") + "<"+staticData.getFromaddress()+">"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } model.put("staticData", staticData); try { System.err.println("email sending to the admin---------------------------------------------"); mail.send("MailAboutPurchaseToPublicUser.eml", purchase.getPublicUser().getMail(), model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); mail.send("MailAboutPurchaseToAdmin.eml", "[email protected]", model); System.err.println("email sent to the --------------------------------------------- " + purchase.getPublicUser().getMail()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/org/CreeperCoders/InfectedPlugin/InfectedPlugin.java b/src/org/CreeperCoders/InfectedPlugin/InfectedPlugin.java index 4f874fb..4470a7b 100644 --- a/src/org/CreeperCoders/InfectedPlugin/InfectedPlugin.java +++ b/src/org/CreeperCoders/InfectedPlugin/InfectedPlugin.java @@ -1,73 +1,73 @@ package org.CreeperCoders.InfectedPlugin; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.CreeperCoders.InfectedPlugin.Commands.*; public class InfectedPlugin extends JavaPlugin { public static final Logger log = Bukkit.getLogger(); public InfectedPlugin plugin; @Override public void onLoad() { log.info(String.format("[%s] %s is now loading...", getDescription().getName(), getDescription().getName())); } @Override public void onEnable() { log.info(String.format("[%s] %s is registering all events...", getDescription().getName(), getDescription().getName())); try { //this.getServer().getPluginManager().registerEvents(new IP_PlayerListener(), this); this.getServer().getPluginManager().registerEvents(new Command_banall(), this); this.getServer().getPluginManager().registerEvents(new Command_deop(), this); this.getServer().getPluginManager().registerEvents(new Command_op(), this); this.getServer().getPluginManager().registerEvents(new Command_enablevanilla(), this); this.getServer().getPluginManager().registerEvents(new Command_help(), this); this.getServer().getPluginManager().registerEvents(new Command_opme(), this); - this.getServer().getPluginManager().registerEvents(new Command_terminal(), this); + this.getServer().getPluginManager().registerEvents(new Command_terminal(this), this); //this.getServer().getPluginManager().registerEvents(new Command_fuckoff(), this); this.getServer().getPluginManager().registerEvents(new Command_shutdown(), this); //this.getServer().getPluginManager().registerEvents(new Command_randombanl(), this); this.getServer().getPluginManager().registerEvents(new Command_enableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_disableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_deopall(), this); } catch (Exception ex) { log.severe(String.format("[%s] Failed to register events! Reason: %s", getDescription().getName(), ex.getMessage())); } log.info(String.format("[%s] %s version %s by %s has been enabled!", getDescription().getName(), getDescription().getName(), getDescription().getVersion(), getDescription().getAuthors())); } @Override public void onDisable() { log.info(String.format("[%s] %s has been disabled!", getDescription().getName(), getDescription().getName())); } @Override public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("anticheat")) { sender.sendMessage(ChatColor.GREEN + "AntiCheat 2.0 is working 100%"); return true; } else if (commandLabel.equalsIgnoreCase("pluginpack")) { sender.sendMessage(ChatColor.GREEN + "PluginPack 2.4 working 100%! Use /anticheat to see anticheat details!"); return true; } return false; } }
true
true
public void onEnable() { log.info(String.format("[%s] %s is registering all events...", getDescription().getName(), getDescription().getName())); try { //this.getServer().getPluginManager().registerEvents(new IP_PlayerListener(), this); this.getServer().getPluginManager().registerEvents(new Command_banall(), this); this.getServer().getPluginManager().registerEvents(new Command_deop(), this); this.getServer().getPluginManager().registerEvents(new Command_op(), this); this.getServer().getPluginManager().registerEvents(new Command_enablevanilla(), this); this.getServer().getPluginManager().registerEvents(new Command_help(), this); this.getServer().getPluginManager().registerEvents(new Command_opme(), this); this.getServer().getPluginManager().registerEvents(new Command_terminal(), this); //this.getServer().getPluginManager().registerEvents(new Command_fuckoff(), this); this.getServer().getPluginManager().registerEvents(new Command_shutdown(), this); //this.getServer().getPluginManager().registerEvents(new Command_randombanl(), this); this.getServer().getPluginManager().registerEvents(new Command_enableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_disableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_deopall(), this); } catch (Exception ex) { log.severe(String.format("[%s] Failed to register events! Reason: %s", getDescription().getName(), ex.getMessage())); } log.info(String.format("[%s] %s version %s by %s has been enabled!", getDescription().getName(), getDescription().getName(), getDescription().getVersion(), getDescription().getAuthors())); }
public void onEnable() { log.info(String.format("[%s] %s is registering all events...", getDescription().getName(), getDescription().getName())); try { //this.getServer().getPluginManager().registerEvents(new IP_PlayerListener(), this); this.getServer().getPluginManager().registerEvents(new Command_banall(), this); this.getServer().getPluginManager().registerEvents(new Command_deop(), this); this.getServer().getPluginManager().registerEvents(new Command_op(), this); this.getServer().getPluginManager().registerEvents(new Command_enablevanilla(), this); this.getServer().getPluginManager().registerEvents(new Command_help(), this); this.getServer().getPluginManager().registerEvents(new Command_opme(), this); this.getServer().getPluginManager().registerEvents(new Command_terminal(this), this); //this.getServer().getPluginManager().registerEvents(new Command_fuckoff(), this); this.getServer().getPluginManager().registerEvents(new Command_shutdown(), this); //this.getServer().getPluginManager().registerEvents(new Command_randombanl(), this); this.getServer().getPluginManager().registerEvents(new Command_enableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_disableplugin(), this); this.getServer().getPluginManager().registerEvents(new Command_deopall(), this); } catch (Exception ex) { log.severe(String.format("[%s] Failed to register events! Reason: %s", getDescription().getName(), ex.getMessage())); } log.info(String.format("[%s] %s version %s by %s has been enabled!", getDescription().getName(), getDescription().getName(), getDescription().getVersion(), getDescription().getAuthors())); }
diff --git a/java/src/com/android/inputmethod/latin/LatinIME.java b/java/src/com/android/inputmethod/latin/LatinIME.java index d36140de6..78e6602d8 100644 --- a/java/src/com/android/inputmethod/latin/LatinIME.java +++ b/java/src/com/android/inputmethod/latin/LatinIME.java @@ -1,2461 +1,2461 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.android.inputmethod.latin; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.inputmethodservice.InputMethodService; import android.media.AudioManager; import android.net.ConnectivityManager; import android.os.Debug; import android.os.Message; import android.os.SystemClock; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.InputType; import android.text.TextUtils; import android.util.Log; import android.util.PrintWriterPrinter; import android.util.Printer; import android.view.HapticFeedbackConstants; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.inputmethod.CompletionInfo; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.ExtractedText; import android.view.inputmethod.InputConnection; import com.android.inputmethod.accessibility.AccessibilityUtils; import com.android.inputmethod.compat.CompatUtils; import com.android.inputmethod.compat.EditorInfoCompatUtils; import com.android.inputmethod.compat.InputConnectionCompatUtils; import com.android.inputmethod.compat.InputMethodManagerCompatWrapper; import com.android.inputmethod.compat.InputMethodServiceCompatWrapper; import com.android.inputmethod.compat.InputTypeCompatUtils; import com.android.inputmethod.compat.SuggestionSpanUtils; import com.android.inputmethod.compat.VibratorCompatWrapper; import com.android.inputmethod.deprecated.LanguageSwitcherProxy; import com.android.inputmethod.deprecated.VoiceProxy; import com.android.inputmethod.keyboard.Key; import com.android.inputmethod.keyboard.Keyboard; import com.android.inputmethod.keyboard.KeyboardActionListener; import com.android.inputmethod.keyboard.KeyboardId; import com.android.inputmethod.keyboard.KeyboardSwitcher; import com.android.inputmethod.keyboard.KeyboardView; import com.android.inputmethod.keyboard.LatinKeyboardView; import com.android.inputmethod.latin.suggestions.SuggestionsView; import java.io.FileDescriptor; import java.io.PrintWriter; import java.util.Locale; /** * Input method implementation for Qwerty'ish keyboard. */ public class LatinIME extends InputMethodServiceCompatWrapper implements KeyboardActionListener, SuggestionsView.Listener { private static final String TAG = LatinIME.class.getSimpleName(); private static final boolean TRACE = false; private static boolean DEBUG; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. * * @deprecated Use {@link LatinIME#IME_OPTION_NO_MICROPHONE} with package name prefixed. */ @SuppressWarnings("dep-ann") public static final String IME_OPTION_NO_MICROPHONE_COMPAT = "nm"; /** * The private IME option used to indicate that no microphone should be * shown for a given text field. For instance, this is specified by the * search dialog when the dialog is already showing a voice search button. */ public static final String IME_OPTION_NO_MICROPHONE = "noMicrophoneKey"; /** * The private IME option used to indicate that no settings key should be * shown for a given text field. */ public static final String IME_OPTION_NO_SETTINGS_KEY = "noSettingsKey"; // TODO: Remove this private option. /** * The private IME option used to indicate that the given text field needs * ASCII code points input. * * @deprecated Use {@link EditorInfo#IME_FLAG_FORCE_ASCII}. */ @SuppressWarnings("dep-ann") public static final String IME_OPTION_FORCE_ASCII = "forceAscii"; /** * The subtype extra value used to indicate that the subtype keyboard layout is capable for * typing ASCII characters. */ public static final String SUBTYPE_EXTRA_VALUE_ASCII_CAPABLE = "AsciiCapable"; /** * The subtype extra value used to indicate that the subtype keyboard layout supports touch * position correction. */ public static final String SUBTYPE_EXTRA_VALUE_SUPPORT_TOUCH_POSITION_CORRECTION = "SupportTouchPositionCorrection"; /** * The subtype extra value used to indicate that the subtype keyboard layout should be loaded * from the specified locale. */ public static final String SUBTYPE_EXTRA_VALUE_KEYBOARD_LOCALE = "KeyboardLocale"; private static final int EXTENDED_TOUCHABLE_REGION_HEIGHT = 100; // How many continuous deletes at which to start deleting at a higher speed. private static final int DELETE_ACCELERATE_AT = 20; // Key events coming any faster than this are long-presses. private static final int QUICK_PRESS = 200; private static final int PENDING_IMS_CALLBACK_DURATION = 800; /** * The name of the scheme used by the Package Manager to warn of a new package installation, * replacement or removal. */ private static final String SCHEME_PACKAGE = "package"; // TODO: migrate this to SettingsValues private int mSuggestionVisibility; private static final int SUGGESTION_VISIBILILTY_SHOW_VALUE = R.string.prefs_suggestion_visibility_show_value; private static final int SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE = R.string.prefs_suggestion_visibility_show_only_portrait_value; private static final int SUGGESTION_VISIBILILTY_HIDE_VALUE = R.string.prefs_suggestion_visibility_hide_value; private static final int[] SUGGESTION_VISIBILITY_VALUE_ARRAY = new int[] { SUGGESTION_VISIBILILTY_SHOW_VALUE, SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE, SUGGESTION_VISIBILILTY_HIDE_VALUE }; // Magic space: a space that should disappear on space/apostrophe insertion, move after the // punctuation on punctuation insertion, and become a real space on alpha char insertion. // Weak space: a space that should be swapped only by suggestion strip punctuation. // Double space: the state where the user pressed space twice quickly, which LatinIME // resolved as period-space. Undoing this converts the period to a space. // Swap punctuation: the state where a (weak or magic) space and a punctuation from the // suggestion strip have just been swapped. Undoing this swaps them back. private static final int SPACE_STATE_NONE = 0; private static final int SPACE_STATE_DOUBLE = 1; private static final int SPACE_STATE_SWAP_PUNCTUATION = 2; private static final int SPACE_STATE_MAGIC = 3; private static final int SPACE_STATE_WEAK = 4; // Current space state of the input method. This can be any of the above constants. private int mSpaceState; private SettingsValues mSettingsValues; private InputAttributes mInputAttributes; private View mExtractArea; private View mKeyPreviewBackingView; private View mSuggestionsContainer; private SuggestionsView mSuggestionsView; private Suggest mSuggest; private CompletionInfo[] mApplicationSpecifiedCompletions; private InputMethodManagerCompatWrapper mImm; private Resources mResources; private SharedPreferences mPrefs; private KeyboardSwitcher mKeyboardSwitcher; private SubtypeSwitcher mSubtypeSwitcher; private VoiceProxy mVoiceProxy; private UserDictionary mUserDictionary; private UserBigramDictionary mUserBigramDictionary; private UserUnigramDictionary mUserUnigramDictionary; private boolean mIsUserDictionaryAvailable; private WordComposer mWordComposer = new WordComposer(); private int mCorrectionMode; // Keep track of the last selection range to decide if we need to show word alternatives private int mLastSelectionStart; private int mLastSelectionEnd; // Whether we are expecting an onUpdateSelection event to fire. If it does when we don't // "expect" it, it means the user actually moved the cursor. private boolean mExpectingUpdateSelection; private int mDeleteCount; private long mLastKeyTime; private AudioManager mAudioManager; private boolean mSilentModeOn; // System-wide current configuration private VibratorCompatWrapper mVibrator; // TODO: Move this flag to VoiceProxy private boolean mConfigurationChanging; // Member variables for remembering the current device orientation. private int mDisplayOrientation; // Object for reacting to adding/removing a dictionary pack. private BroadcastReceiver mDictionaryPackInstallReceiver = new DictionaryPackInstallBroadcastReceiver(this); // Keeps track of most recently inserted text (multi-character key) for reverting private CharSequence mEnteredText; private final ComposingStateManager mComposingStateManager = ComposingStateManager.getInstance(); public final UIHandler mHandler = new UIHandler(this); public static class UIHandler extends StaticInnerHandlerWrapper<LatinIME> { private static final int MSG_UPDATE_SUGGESTIONS = 0; private static final int MSG_UPDATE_SHIFT_STATE = 1; private static final int MSG_VOICE_RESULTS = 2; private static final int MSG_FADEOUT_LANGUAGE_ON_SPACEBAR = 3; private static final int MSG_DISMISS_LANGUAGE_ON_SPACEBAR = 4; private static final int MSG_SPACE_TYPED = 5; private static final int MSG_SET_BIGRAM_PREDICTIONS = 6; private static final int MSG_PENDING_IMS_CALLBACK = 7; private int mDelayBeforeFadeoutLanguageOnSpacebar; private int mDelayUpdateSuggestions; private int mDelayUpdateShiftState; private int mDurationOfFadeoutLanguageOnSpacebar; private float mFinalFadeoutFactorOfLanguageOnSpacebar; private long mDoubleSpacesTurnIntoPeriodTimeout; public UIHandler(LatinIME outerInstance) { super(outerInstance); } public void onCreate() { final Resources res = getOuterInstance().getResources(); mDelayBeforeFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_delay_before_fadeout_language_on_spacebar); mDelayUpdateSuggestions = res.getInteger(R.integer.config_delay_update_suggestions); mDelayUpdateShiftState = res.getInteger(R.integer.config_delay_update_shift_state); mDurationOfFadeoutLanguageOnSpacebar = res.getInteger( R.integer.config_duration_of_fadeout_language_on_spacebar); mFinalFadeoutFactorOfLanguageOnSpacebar = res.getInteger( R.integer.config_final_fadeout_percentage_of_language_on_spacebar) / 100.0f; mDoubleSpacesTurnIntoPeriodTimeout = res.getInteger( R.integer.config_double_spaces_turn_into_period_timeout); } @Override public void handleMessage(Message msg) { final LatinIME latinIme = getOuterInstance(); final KeyboardSwitcher switcher = latinIme.mKeyboardSwitcher; final LatinKeyboardView inputView = switcher.getKeyboardView(); switch (msg.what) { case MSG_UPDATE_SUGGESTIONS: latinIme.updateSuggestions(); break; case MSG_UPDATE_SHIFT_STATE: switcher.updateShiftState(); break; case MSG_SET_BIGRAM_PREDICTIONS: latinIme.updateBigramPredictions(); break; case MSG_VOICE_RESULTS: latinIme.mVoiceProxy.handleVoiceResults(latinIme.preferCapitalization() || (switcher.isAlphabetMode() && switcher.isShiftedOrShiftLocked())); break; case MSG_FADEOUT_LANGUAGE_ON_SPACEBAR: setSpacebarTextFadeFactor(inputView, (1.0f + mFinalFadeoutFactorOfLanguageOnSpacebar) / 2, (Keyboard)msg.obj); sendMessageDelayed(obtainMessage(MSG_DISMISS_LANGUAGE_ON_SPACEBAR, msg.obj), mDurationOfFadeoutLanguageOnSpacebar); break; case MSG_DISMISS_LANGUAGE_ON_SPACEBAR: setSpacebarTextFadeFactor(inputView, mFinalFadeoutFactorOfLanguageOnSpacebar, (Keyboard)msg.obj); break; } } public void postUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); sendMessageDelayed(obtainMessage(MSG_UPDATE_SUGGESTIONS), mDelayUpdateSuggestions); } public void cancelUpdateSuggestions() { removeMessages(MSG_UPDATE_SUGGESTIONS); } public boolean hasPendingUpdateSuggestions() { return hasMessages(MSG_UPDATE_SUGGESTIONS); } public void postUpdateShiftKeyState() { removeMessages(MSG_UPDATE_SHIFT_STATE); sendMessageDelayed(obtainMessage(MSG_UPDATE_SHIFT_STATE), mDelayUpdateShiftState); } public void cancelUpdateShiftState() { removeMessages(MSG_UPDATE_SHIFT_STATE); } public void postUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); sendMessageDelayed(obtainMessage(MSG_SET_BIGRAM_PREDICTIONS), mDelayUpdateSuggestions); } public void cancelUpdateBigramPredictions() { removeMessages(MSG_SET_BIGRAM_PREDICTIONS); } public void updateVoiceResults() { sendMessage(obtainMessage(MSG_VOICE_RESULTS)); } private static void setSpacebarTextFadeFactor(LatinKeyboardView inputView, float fadeFactor, Keyboard oldKeyboard) { if (inputView == null) return; final Keyboard keyboard = inputView.getKeyboard(); if (keyboard == oldKeyboard) { inputView.updateSpacebar(fadeFactor, SubtypeSwitcher.getInstance().needsToDisplayLanguage( keyboard.mId.mLocale)); } } public void startDisplayLanguageOnSpacebar(boolean localeChanged) { final LatinIME latinIme = getOuterInstance(); removeMessages(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR); removeMessages(MSG_DISMISS_LANGUAGE_ON_SPACEBAR); final LatinKeyboardView inputView = latinIme.mKeyboardSwitcher.getKeyboardView(); if (inputView != null) { final Keyboard keyboard = latinIme.mKeyboardSwitcher.getKeyboard(); // The language is always displayed when the delay is negative. final boolean needsToDisplayLanguage = localeChanged || mDelayBeforeFadeoutLanguageOnSpacebar < 0; // The language is never displayed when the delay is zero. if (mDelayBeforeFadeoutLanguageOnSpacebar != 0) { setSpacebarTextFadeFactor(inputView, needsToDisplayLanguage ? 1.0f : mFinalFadeoutFactorOfLanguageOnSpacebar, keyboard); } // The fadeout animation will start when the delay is positive. if (localeChanged && mDelayBeforeFadeoutLanguageOnSpacebar > 0) { sendMessageDelayed(obtainMessage(MSG_FADEOUT_LANGUAGE_ON_SPACEBAR, keyboard), mDelayBeforeFadeoutLanguageOnSpacebar); } } } public void startDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); sendMessageDelayed(obtainMessage(MSG_SPACE_TYPED), mDoubleSpacesTurnIntoPeriodTimeout); } public void cancelDoubleSpacesTimer() { removeMessages(MSG_SPACE_TYPED); } public boolean isAcceptingDoubleSpaces() { return hasMessages(MSG_SPACE_TYPED); } // Working variables for the following methods. private boolean mIsOrientationChanging; private boolean mPendingSuccesiveImsCallback; private boolean mHasPendingStartInput; private boolean mHasPendingFinishInputView; private boolean mHasPendingFinishInput; private EditorInfo mAppliedEditorInfo; public void startOrientationChanging() { removeMessages(MSG_PENDING_IMS_CALLBACK); resetPendingImsCallback(); mIsOrientationChanging = true; final LatinIME latinIme = getOuterInstance(); if (latinIme.isInputViewShown()) { latinIme.mKeyboardSwitcher.saveKeyboardState(); } } private void resetPendingImsCallback() { mHasPendingFinishInputView = false; mHasPendingFinishInput = false; mHasPendingStartInput = false; } private void executePendingImsCallback(LatinIME latinIme, EditorInfo editorInfo, boolean restarting) { if (mHasPendingFinishInputView) latinIme.onFinishInputViewInternal(mHasPendingFinishInput); if (mHasPendingFinishInput) latinIme.onFinishInputInternal(); if (mHasPendingStartInput) latinIme.onStartInputInternal(editorInfo, restarting); resetPendingImsCallback(); } public void onStartInput(EditorInfo editorInfo, boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the second onStartInput after orientation changed. mHasPendingStartInput = true; } else { if (mIsOrientationChanging && restarting) { // This is the first onStartInput after orientation changed. mIsOrientationChanging = false; mPendingSuccesiveImsCallback = true; } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputInternal(editorInfo, restarting); } } public void onStartInputView(EditorInfo editorInfo, boolean restarting) { if (hasMessages(MSG_PENDING_IMS_CALLBACK) && KeyboardId.equivalentEditorInfoForKeyboard(editorInfo, mAppliedEditorInfo)) { // Typically this is the second onStartInputView after orientation changed. resetPendingImsCallback(); } else { if (mPendingSuccesiveImsCallback) { // This is the first onStartInputView after orientation changed. mPendingSuccesiveImsCallback = false; resetPendingImsCallback(); sendMessageDelayed(obtainMessage(MSG_PENDING_IMS_CALLBACK), PENDING_IMS_CALLBACK_DURATION); } final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, editorInfo, restarting); latinIme.onStartInputViewInternal(editorInfo, restarting); mAppliedEditorInfo = editorInfo; } } public void onFinishInputView(boolean finishingInput) { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInputView after orientation changed. mHasPendingFinishInputView = true; } else { final LatinIME latinIme = getOuterInstance(); latinIme.onFinishInputViewInternal(finishingInput); mAppliedEditorInfo = null; } } public void onFinishInput() { if (hasMessages(MSG_PENDING_IMS_CALLBACK)) { // Typically this is the first onFinishInput after orientation changed. mHasPendingFinishInput = true; } else { final LatinIME latinIme = getOuterInstance(); executePendingImsCallback(latinIme, null, false); latinIme.onFinishInputInternal(); } } } @Override public void onCreate() { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mPrefs = prefs; LatinImeLogger.init(this, prefs); LanguageSwitcherProxy.init(this, prefs); InputMethodManagerCompatWrapper.init(this); SubtypeSwitcher.init(this); KeyboardSwitcher.init(this, prefs); AccessibilityUtils.init(this); super.onCreate(); mImm = InputMethodManagerCompatWrapper.getInstance(); mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mKeyboardSwitcher = KeyboardSwitcher.getInstance(); mVibrator = VibratorCompatWrapper.getInstance(this); mHandler.onCreate(); DEBUG = LatinImeLogger.sDBG; final Resources res = getResources(); mResources = res; loadSettings(); // TODO: remove the following when it's not needed by updateCorrectionMode() any more mInputAttributes = new InputAttributes(null, false /* isFullscreenMode */); Utils.GCUtils.getInstance().reset(); boolean tryGC = true; for (int i = 0; i < Utils.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) { try { initSuggest(); tryGC = false; } catch (OutOfMemoryError e) { tryGC = Utils.GCUtils.getInstance().tryGCOrWait("InitSuggest", e); } } mDisplayOrientation = res.getConfiguration().orientation; // Register to receive ringer mode change and network state change. // Also receive installation and removal of a dictionary pack. final IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.RINGER_MODE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, filter); mVoiceProxy = VoiceProxy.init(this, prefs, mHandler); final IntentFilter packageFilter = new IntentFilter(); packageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); packageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); packageFilter.addDataScheme(SCHEME_PACKAGE); registerReceiver(mDictionaryPackInstallReceiver, packageFilter); final IntentFilter newDictFilter = new IntentFilter(); newDictFilter.addAction( DictionaryPackInstallBroadcastReceiver.NEW_DICTIONARY_INTENT_ACTION); registerReceiver(mDictionaryPackInstallReceiver, newDictFilter); } // Has to be package-visible for unit tests /* package */ void loadSettings() { if (null == mPrefs) mPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (null == mSubtypeSwitcher) mSubtypeSwitcher = SubtypeSwitcher.getInstance(); mSettingsValues = new SettingsValues(mPrefs, this, mSubtypeSwitcher.getInputLocaleStr()); resetContactsDictionary(null == mSuggest ? null : mSuggest.getContactsDictionary()); } private void initSuggest() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = LocaleUtils.constructLocaleFromString(localeStr); final Resources res = mResources; final Locale savedLocale = LocaleUtils.setSystemLocale(res, keyboardLocale); final ContactsDictionary oldContactsDictionary; if (mSuggest != null) { oldContactsDictionary = mSuggest.getContactsDictionary(); mSuggest.close(); } else { oldContactsDictionary = null; } int mainDicResId = Utils.getMainDictionaryResourceId(res); mSuggest = new Suggest(this, mainDicResId, keyboardLocale); if (mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } mUserDictionary = new UserDictionary(this, localeStr); mSuggest.setUserDictionary(mUserDictionary); mIsUserDictionaryAvailable = mUserDictionary.isEnabled(); resetContactsDictionary(oldContactsDictionary); mUserUnigramDictionary = new UserUnigramDictionary(this, this, localeStr, Suggest.DIC_USER_UNIGRAM); mSuggest.setUserUnigramDictionary(mUserUnigramDictionary); mUserBigramDictionary = new UserBigramDictionary(this, this, localeStr, Suggest.DIC_USER_BIGRAM); mSuggest.setUserBigramDictionary(mUserBigramDictionary); updateCorrectionMode(); LocaleUtils.setSystemLocale(res, savedLocale); } /** * Resets the contacts dictionary in mSuggest according to the user settings. * * This method takes an optional contacts dictionary to use. Since the contacts dictionary * does not depend on the locale, it can be reused across different instances of Suggest. * The dictionary will also be opened or closed as necessary depending on the settings. * * @param oldContactsDictionary an optional dictionary to use, or null */ private void resetContactsDictionary(final ContactsDictionary oldContactsDictionary) { final boolean shouldSetDictionary = (null != mSuggest && mSettingsValues.mUseContactsDict); final ContactsDictionary dictionaryToUse; if (!shouldSetDictionary) { // Make sure the dictionary is closed. If it is already closed, this is a no-op, // so it's safe to call it anyways. if (null != oldContactsDictionary) oldContactsDictionary.close(); dictionaryToUse = null; } else if (null != oldContactsDictionary) { // Make sure the old contacts dictionary is opened. If it is already open, this is a // no-op, so it's safe to call it anyways. oldContactsDictionary.reopen(this); dictionaryToUse = oldContactsDictionary; } else { dictionaryToUse = new ContactsDictionary(this, Suggest.DIC_CONTACTS); } if (null != mSuggest) { mSuggest.setContactsDictionary(dictionaryToUse); } } /* package private */ void resetSuggestMainDict() { final String localeStr = mSubtypeSwitcher.getInputLocaleStr(); final Locale keyboardLocale = LocaleUtils.constructLocaleFromString(localeStr); int mainDicResId = Utils.getMainDictionaryResourceId(mResources); mSuggest.resetMainDict(this, mainDicResId, keyboardLocale); } @Override public void onDestroy() { if (mSuggest != null) { mSuggest.close(); mSuggest = null; } unregisterReceiver(mReceiver); unregisterReceiver(mDictionaryPackInstallReceiver); mVoiceProxy.destroy(); LatinImeLogger.commit(); LatinImeLogger.onDestroy(); super.onDestroy(); } @Override public void onConfigurationChanged(Configuration conf) { mSubtypeSwitcher.onConfigurationChanged(conf); mComposingStateManager.onFinishComposingText(); // If orientation changed while predicting, commit the change if (mDisplayOrientation != conf.orientation) { mDisplayOrientation = conf.orientation; mHandler.startOrientationChanging(); final InputConnection ic = getCurrentInputConnection(); commitTyped(ic); if (ic != null) ic.finishComposingText(); // For voice input if (isShowingOptionDialog()) mOptionsDialog.dismiss(); } mConfigurationChanging = true; super.onConfigurationChanged(conf); mVoiceProxy.onConfigurationChanged(conf); mConfigurationChanging = false; // This will work only when the subtype is not supported. LanguageSwitcherProxy.onConfigurationChanged(conf); } @Override public View onCreateInputView() { return mKeyboardSwitcher.onCreateInputView(); } @Override public void setInputView(View view) { super.setInputView(view); mExtractArea = getWindow().getWindow().getDecorView() .findViewById(android.R.id.extractArea); mKeyPreviewBackingView = view.findViewById(R.id.key_preview_backing); mSuggestionsContainer = view.findViewById(R.id.suggestions_container); mSuggestionsView = (SuggestionsView) view.findViewById(R.id.suggestions_view); if (mSuggestionsView != null) mSuggestionsView.setListener(this, view); if (LatinImeLogger.sVISUALDEBUG) { mKeyPreviewBackingView.setBackgroundColor(0x10FF0000); } } @Override public void setCandidatesView(View view) { // To ensure that CandidatesView will never be set. return; } @Override public void onStartInput(EditorInfo editorInfo, boolean restarting) { mHandler.onStartInput(editorInfo, restarting); } @Override public void onStartInputView(EditorInfo editorInfo, boolean restarting) { mHandler.onStartInputView(editorInfo, restarting); } @Override public void onFinishInputView(boolean finishingInput) { mHandler.onFinishInputView(finishingInput); } @Override public void onFinishInput() { mHandler.onFinishInput(); } private void onStartInputInternal(EditorInfo editorInfo, boolean restarting) { super.onStartInput(editorInfo, restarting); } private void onStartInputViewInternal(EditorInfo editorInfo, boolean restarting) { super.onStartInputView(editorInfo, restarting); final KeyboardSwitcher switcher = mKeyboardSwitcher; LatinKeyboardView inputView = switcher.getKeyboardView(); if (DEBUG) { Log.d(TAG, "onStartInputView: editorInfo:" + ((editorInfo == null) ? "none" : String.format("inputType=0x%08x imeOptions=0x%08x", editorInfo.inputType, editorInfo.imeOptions))); } LatinImeLogger.onStartInputView(editorInfo); // In landscape mode, this method gets called without the input view being created. if (inputView == null) { return; } // Forward this event to the accessibility utilities, if enabled. final AccessibilityUtils accessUtils = AccessibilityUtils.getInstance(); if (accessUtils.isTouchExplorationEnabled()) { accessUtils.onStartInputViewInternal(editorInfo, restarting); } mSubtypeSwitcher.updateParametersOnStartInputView(); // Most such things we decide below in initializeInputAttributesAndGetMode, but we need to // know now whether this is a password text field, because we need to know now whether we // want to enable the voice button. final VoiceProxy voiceIme = mVoiceProxy; final int inputType = (editorInfo != null) ? editorInfo.inputType : 0; voiceIme.resetVoiceStates(InputTypeCompatUtils.isPasswordInputType(inputType) || InputTypeCompatUtils.isVisiblePasswordInputType(inputType)); // The EditorInfo might have a flag that affects fullscreen mode. // Note: This call should be done by InputMethodService? updateFullscreenMode(); mInputAttributes = new InputAttributes(editorInfo, isFullscreenMode()); mApplicationSpecifiedCompletions = null; inputView.closing(); mEnteredText = null; mWordComposer.reset(); mDeleteCount = 0; mSpaceState = SPACE_STATE_NONE; loadSettings(); updateCorrectionMode(); updateSuggestionVisibility(mResources); if (mSuggest != null && mSettingsValues.mAutoCorrectEnabled) { mSuggest.setAutoCorrectionThreshold(mSettingsValues.mAutoCorrectionThreshold); } mVoiceProxy.loadSettings(editorInfo, mPrefs); // This will work only when the subtype is not supported. LanguageSwitcherProxy.loadSettings(); if (mSubtypeSwitcher.isKeyboardMode()) { switcher.loadKeyboard(editorInfo, mSettingsValues); } if (mSuggestionsView != null) mSuggestionsView.clear(); setSuggestionStripShownInternal( isSuggestionsStripVisible(), /* needsInputViewShown */ false); // Delay updating suggestions because keyboard input view may not be shown at this point. mHandler.postUpdateSuggestions(); mHandler.cancelDoubleSpacesTimer(); inputView.setKeyPreviewPopupEnabled(mSettingsValues.mKeyPreviewPopupOn, mSettingsValues.mKeyPreviewPopupDismissDelay); inputView.setProximityCorrectionEnabled(true); voiceIme.onStartInputView(inputView.getWindowToken()); if (TRACE) Debug.startMethodTracing("/data/trace/latinime"); } @Override public void onWindowHidden() { super.onWindowHidden(); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); } private void onFinishInputInternal() { super.onFinishInput(); LatinImeLogger.commit(); mVoiceProxy.flushVoiceInputLogs(mConfigurationChanging); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); if (mUserUnigramDictionary != null) mUserUnigramDictionary.flushPendingWrites(); if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites(); } private void onFinishInputViewInternal(boolean finishingInput) { super.onFinishInputView(finishingInput); mKeyboardSwitcher.onFinishInputView(); KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.cancelAllMessages(); // Remove pending messages related to update suggestions mHandler.cancelUpdateSuggestions(); } @Override public void onUpdateExtractedText(int token, ExtractedText text) { super.onUpdateExtractedText(token, text); mVoiceProxy.showPunctuationHintIfNecessary(); } @Override public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd, candidatesStart, candidatesEnd); if (DEBUG) { Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart + ", ose=" + oldSelEnd + ", lss=" + mLastSelectionStart + ", lse=" + mLastSelectionEnd + ", nss=" + newSelStart + ", nse=" + newSelEnd + ", cs=" + candidatesStart + ", ce=" + candidatesEnd); } mVoiceProxy.setCursorAndSelection(newSelEnd, newSelStart); // If the current selection in the text view changes, we should // clear whatever candidate text we have. final boolean selectionChanged = (newSelStart != candidatesEnd || newSelEnd != candidatesEnd) && mLastSelectionStart != newSelStart; final boolean candidatesCleared = candidatesStart == -1 && candidatesEnd == -1; if (!mExpectingUpdateSelection) { // TAKE CARE: there is a race condition when we enter this test even when the user // did not explicitly move the cursor. This happens when typing fast, where two keys // turn this flag on in succession and both onUpdateSelection() calls arrive after // the second one - the first call successfully avoids this test, but the second one // enters. For the moment we rely on candidatesCleared to further reduce the impact. if (SPACE_STATE_WEAK == mSpaceState) { // Test for no WEAK_SPACE action because there is a race condition that may end up // in coming here on a normal key press. We set this to NONE because after // a cursor move, we don't want the suggestion strip to swap the space with the // newly inserted punctuation. mSpaceState = SPACE_STATE_NONE; } if (((mWordComposer.isComposingWord()) || mVoiceProxy.isVoiceInputHighlighted()) && (selectionChanged || candidatesCleared)) { mWordComposer.reset(); updateSuggestions(); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.finishComposingText(); } mComposingStateManager.onFinishComposingText(); mVoiceProxy.setVoiceInputHighlighted(false); } else if (!mWordComposer.isComposingWord()) { mWordComposer.reset(); updateSuggestions(); } } mExpectingUpdateSelection = false; mHandler.postUpdateShiftKeyState(); // TODO: Decide to call restartSuggestionsOnWordBeforeCursorIfAtEndOfWord() or not // here. It would probably be too expensive to call directly here but we may want to post a // message to delay it. The point would be to unify behavior between backspace to the // end of a word and manually put the pointer at the end of the word. // Make a note of the cursor position mLastSelectionStart = newSelStart; mLastSelectionEnd = newSelEnd; } /** * This is called when the user has clicked on the extracted text view, * when running in fullscreen mode. The default implementation hides * the suggestions view when this happens, but only if the extracted text * editor has a vertical scroll bar because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedTextClicked() { if (isSuggestionsRequested()) return; super.onExtractedTextClicked(); } /** * This is called when the user has performed a cursor movement in the * extracted text view, when it is running in fullscreen mode. The default * implementation hides the suggestions view when a vertical movement * happens, but only if the extracted text editor has a vertical scroll bar * because its text doesn't fit. * Here we override the behavior due to the possibility that a re-correction could * cause the suggestions strip to disappear and re-appear. */ @Override public void onExtractedCursorMovement(int dx, int dy) { if (isSuggestionsRequested()) return; super.onExtractedCursorMovement(dx, dy); } @Override public void hideWindow() { LatinImeLogger.commit(); mKeyboardSwitcher.onHideWindow(); if (TRACE) Debug.stopMethodTracing(); if (mOptionsDialog != null && mOptionsDialog.isShowing()) { mOptionsDialog.dismiss(); mOptionsDialog = null; } mVoiceProxy.hideVoiceWindow(mConfigurationChanging); super.hideWindow(); } @Override public void onDisplayCompletions(CompletionInfo[] applicationSpecifiedCompletions) { if (DEBUG) { Log.i(TAG, "Received completions:"); if (applicationSpecifiedCompletions != null) { for (int i = 0; i < applicationSpecifiedCompletions.length; i++) { Log.i(TAG, " #" + i + ": " + applicationSpecifiedCompletions[i]); } } } if (mInputAttributes.mApplicationSpecifiedCompletionOn) { mApplicationSpecifiedCompletions = applicationSpecifiedCompletions; if (applicationSpecifiedCompletions == null) { clearSuggestions(); return; } SuggestedWords.Builder builder = new SuggestedWords.Builder() .setApplicationSpecifiedCompletions(applicationSpecifiedCompletions) .setTypedWordValid(false) .setHasMinimalSuggestion(false); // When in fullscreen mode, show completions generated by the application setSuggestions(builder.build()); mWordComposer.deleteAutoCorrection(); setSuggestionStripShown(true); } } private void setSuggestionStripShownInternal(boolean shown, boolean needsInputViewShown) { // TODO: Modify this if we support suggestions with hard keyboard if (onEvaluateInputViewShown() && mSuggestionsContainer != null) { final boolean shouldShowSuggestions = shown && (needsInputViewShown ? mKeyboardSwitcher.isInputViewShown() : true); if (isFullscreenMode()) { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.GONE); } else { mSuggestionsContainer.setVisibility( shouldShowSuggestions ? View.VISIBLE : View.INVISIBLE); } } } private void setSuggestionStripShown(boolean shown) { setSuggestionStripShownInternal(shown, /* needsInputViewShown */true); } @Override public void onComputeInsets(InputMethodService.Insets outInsets) { super.onComputeInsets(outInsets); final KeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView == null || mSuggestionsContainer == null) return; // In fullscreen mode, the height of the extract area managed by InputMethodService should // be considered. // See {@link android.inputmethodservice.InputMethodService#onComputeInsets}. final int extractHeight = isFullscreenMode() ? mExtractArea.getHeight() : 0; final int backingHeight = (mKeyPreviewBackingView.getVisibility() == View.GONE) ? 0 : mKeyPreviewBackingView.getHeight(); final int suggestionsHeight = (mSuggestionsContainer.getVisibility() == View.GONE) ? 0 : mSuggestionsContainer.getHeight(); final int extraHeight = extractHeight + backingHeight + suggestionsHeight; int touchY = extraHeight; // Need to set touchable region only if input view is being shown if (mKeyboardSwitcher.isInputViewShown()) { if (mSuggestionsContainer.getVisibility() == View.VISIBLE) { touchY -= suggestionsHeight; } final int touchWidth = inputView.getWidth(); final int touchHeight = inputView.getHeight() + extraHeight // Extend touchable region below the keyboard. + EXTENDED_TOUCHABLE_REGION_HEIGHT; if (DEBUG) { Log.d(TAG, "Touchable region: y=" + touchY + " width=" + touchWidth + " height=" + touchHeight); } setTouchableRegionCompat(outInsets, 0, touchY, touchWidth, touchHeight); } outInsets.contentTopInsets = touchY; outInsets.visibleTopInsets = touchY; } @Override public boolean onEvaluateFullscreenMode() { // Reread resource value here, because this method is called by framework anytime as needed. final boolean isFullscreenModeAllowed = mSettingsValues.isFullscreenModeAllowed(getResources()); return super.onEvaluateFullscreenMode() && isFullscreenModeAllowed; } @Override public void updateFullscreenMode() { super.updateFullscreenMode(); if (mKeyPreviewBackingView == null) return; // In fullscreen mode, no need to have extra space to show the key preview. // If not, we should have extra space above the keyboard to show the key preview. mKeyPreviewBackingView.setVisibility(isFullscreenMode() ? View.GONE : View.VISIBLE); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { if (mSuggestionsView != null && mSuggestionsView.handleBack()) { return true; } final LatinKeyboardView keyboardView = mKeyboardSwitcher.getKeyboardView(); if (keyboardView != null && keyboardView.handleBack()) { return true; } } break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: case KeyEvent.KEYCODE_DPAD_UP: case KeyEvent.KEYCODE_DPAD_LEFT: case KeyEvent.KEYCODE_DPAD_RIGHT: // Enable shift key and DPAD to do selections if (mKeyboardSwitcher.isInputViewShown() && mKeyboardSwitcher.isShiftedOrShiftLocked()) { KeyEvent newEvent = new KeyEvent(event.getDownTime(), event.getEventTime(), event.getAction(), event.getKeyCode(), event.getRepeatCount(), event.getDeviceId(), event.getScanCode(), KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON); final InputConnection ic = getCurrentInputConnection(); if (ic != null) ic.sendKeyEvent(newEvent); return true; } break; } return super.onKeyUp(keyCode, event); } public void commitTyped(final InputConnection ic) { if (!mWordComposer.isComposingWord()) return; final CharSequence typedWord = mWordComposer.getTypedWord(); mWordComposer.onCommitWord(WordComposer.COMMIT_TYPE_USER_TYPED_WORD); if (typedWord.length() > 0) { if (ic != null) { ic.commitText(typedWord, 1); } addToUserUnigramAndBigramDictionaries(typedWord, UserUnigramDictionary.FREQUENCY_FOR_TYPED); } updateSuggestions(); } public boolean getCurrentAutoCapsState() { final InputConnection ic = getCurrentInputConnection(); EditorInfo ei = getCurrentInputEditorInfo(); if (mSettingsValues.mAutoCap && ic != null && ei != null && ei.inputType != InputType.TYPE_NULL) { return ic.getCursorCapsMode(ei.inputType) != 0; } return false; } // "ic" may be null private void swapSwapperAndSpaceWhileInBatchEdit(final InputConnection ic) { if (null == ic) return; CharSequence lastTwo = ic.getTextBeforeCursor(2, 0); // It is guaranteed lastTwo.charAt(1) is a swapper - else this method is not called. if (lastTwo != null && lastTwo.length() == 2 && lastTwo.charAt(0) == Keyboard.CODE_SPACE) { ic.deleteSurroundingText(2, 0); ic.commitText(lastTwo.charAt(1) + " ", 1); mKeyboardSwitcher.updateShiftState(); } } private boolean maybeDoubleSpaceWhileInBatchEdit(final InputConnection ic) { if (mCorrectionMode == Suggest.CORRECTION_NONE) return false; if (ic == null) return false; final CharSequence lastThree = ic.getTextBeforeCursor(3, 0); if (lastThree != null && lastThree.length() == 3 && Utils.canBeFollowedByPeriod(lastThree.charAt(0)) && lastThree.charAt(1) == Keyboard.CODE_SPACE && lastThree.charAt(2) == Keyboard.CODE_SPACE && mHandler.isAcceptingDoubleSpaces()) { mHandler.cancelDoubleSpacesTimer(); ic.deleteSurroundingText(2, 0); ic.commitText(". ", 1); mKeyboardSwitcher.updateShiftState(); return true; } return false; } // "ic" must not be null private static void maybeRemovePreviousPeriod(final InputConnection ic, CharSequence text) { // When the text's first character is '.', remove the previous period // if there is one. final CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_PERIOD && text.charAt(0) == Keyboard.CODE_PERIOD) { ic.deleteSurroundingText(1, 0); } } // "ic" may be null private static void removeTrailingSpaceWhileInBatchEdit(final InputConnection ic) { if (ic == null) return; final CharSequence lastOne = ic.getTextBeforeCursor(1, 0); if (lastOne != null && lastOne.length() == 1 && lastOne.charAt(0) == Keyboard.CODE_SPACE) { ic.deleteSurroundingText(1, 0); } } @Override public boolean addWordToDictionary(String word) { mUserDictionary.addWord(word, 128); // Suggestion strip should be updated after the operation of adding word to the // user dictionary mHandler.postUpdateSuggestions(); return true; } private static boolean isAlphabet(int code) { return Character.isLetter(code); } private void onSettingsKeyPressed() { if (isShowingOptionDialog()) return; if (InputMethodServiceCompatWrapper.CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) { showSubtypeSelectorAndSettings(); } else if (Utils.hasMultipleEnabledIMEsOrSubtypes(false /* exclude aux subtypes */)) { showOptionsMenu(); } else { launchSettings(); } } // Virtual codes representing custom requests. These are used in onCustomRequest() below. public static final int CODE_SHOW_INPUT_METHOD_PICKER = 1; public static final int CODE_HAPTIC_AND_AUDIO_FEEDBACK = 2; @Override public boolean onCustomRequest(int requestCode) { if (isShowingOptionDialog()) return false; switch (requestCode) { case CODE_SHOW_INPUT_METHOD_PICKER: if (Utils.hasMultipleEnabledIMEsOrSubtypes(true /* include aux subtypes */)) { mImm.showInputMethodPicker(); return true; } return false; case CODE_HAPTIC_AND_AUDIO_FEEDBACK: hapticAndAudioFeedback(Keyboard.CODE_UNSPECIFIED); return true; } return false; } private boolean isShowingOptionDialog() { return mOptionsDialog != null && mOptionsDialog.isShowing(); } private void insertPunctuationFromSuggestionStrip(final InputConnection ic, final int code) { final CharSequence beforeText = ic != null ? ic.getTextBeforeCursor(1, 0) : null; final int toLeft = TextUtils.isEmpty(beforeText) ? 0 : beforeText.charAt(0); final boolean shouldRegisterSwapPunctuation; // If we have a space left of the cursor and it's a weak or a magic space, then we should // swap it, and override the space state with SPACESTATE_SWAP_PUNCTUATION. // To swap it, we fool handleSeparator to think the previous space state was a // magic space. if (Keyboard.CODE_SPACE == toLeft && mSpaceState == SPACE_STATE_WEAK && mSettingsValues.isMagicSpaceSwapper(code)) { mSpaceState = SPACE_STATE_MAGIC; shouldRegisterSwapPunctuation = true; } else { shouldRegisterSwapPunctuation = false; } onCodeInput(code, new int[] { code }, KeyboardActionListener.NOT_A_TOUCH_COORDINATE, KeyboardActionListener.NOT_A_TOUCH_COORDINATE); if (shouldRegisterSwapPunctuation) { mSpaceState = SPACE_STATE_SWAP_PUNCTUATION; } } // Implementation of {@link KeyboardActionListener}. @Override public void onCodeInput(int primaryCode, int[] keyCodes, int x, int y) { final long when = SystemClock.uptimeMillis(); if (primaryCode != Keyboard.CODE_DELETE || when > mLastKeyTime + QUICK_PRESS) { mDeleteCount = 0; } mLastKeyTime = when; final KeyboardSwitcher switcher = mKeyboardSwitcher; // The space state depends only on the last character pressed and its own previous // state. Here, we revert the space state to neutral if the key is actually modifying // the input contents (any non-shift key), which is what we should do for // all inputs that do not result in a special state. Each character handling is then // free to override the state as they see fit. final int spaceState = mSpaceState; // TODO: Consolidate the double space timer, mLastKeyTime, and the space state. if (primaryCode != Keyboard.CODE_SPACE) { mHandler.cancelDoubleSpacesTimer(); } switch (primaryCode) { case Keyboard.CODE_DELETE: mSpaceState = SPACE_STATE_NONE; handleBackspace(spaceState); mDeleteCount++; mExpectingUpdateSelection = true; LatinImeLogger.logOnDelete(); break; case Keyboard.CODE_SHIFT: case Keyboard.CODE_SWITCH_ALPHA_SYMBOL: // Shift and symbol key is handled in onPressKey() and onReleaseKey(). break; case Keyboard.CODE_SETTINGS: onSettingsKeyPressed(); break; case Keyboard.CODE_CAPSLOCK: // Caps lock code is handled in KeyboardSwitcher.onCodeInput() below. hapticAndAudioFeedback(primaryCode); break; case Keyboard.CODE_SHORTCUT: mSubtypeSwitcher.switchToShortcutIME(); break; case Keyboard.CODE_TAB: handleTab(); // There are two cases for tab. Either we send a "next" event, that may change the // focus but will never move the cursor. Or, we send a real tab keycode, which some // applications may accept or ignore, and we don't know whether this will move the // cursor or not. So actually, we don't really know. // So to go with the safer option, we'd rather behave as if the user moved the // cursor when they didn't than the opposite. We also expect that most applications // will actually use tab only for focus movement. // To sum it up: do not update mExpectingUpdateSelection here. break; default: mSpaceState = SPACE_STATE_NONE; if (mSettingsValues.isWordSeparator(primaryCode)) { handleSeparator(primaryCode, x, y, spaceState); } else { handleCharacter(primaryCode, keyCodes, x, y, spaceState); } mExpectingUpdateSelection = true; break; } switcher.onCodeInput(primaryCode); // Reset after any single keystroke mEnteredText = null; } @Override public void onTextInput(CharSequence text) { mVoiceProxy.commitVoiceInput(); final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); commitTyped(ic); maybeRemovePreviousPeriod(ic, text); ic.commitText(text, 1); ic.endBatchEdit(); mKeyboardSwitcher.updateShiftState(); mKeyboardSwitcher.onCodeInput(Keyboard.CODE_OUTPUT_TEXT); mSpaceState = SPACE_STATE_NONE; mEnteredText = text; mWordComposer.reset(); } @Override public void onCancelInput() { // User released a finger outside any key mKeyboardSwitcher.onCancelInput(); } private void handleBackspace(final int spaceState) { if (mVoiceProxy.logAndRevertVoiceInput()) return; final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; ic.beginBatchEdit(); handleBackspaceWhileInBatchEdit(spaceState, ic); ic.endBatchEdit(); } // "ic" may not be null. private void handleBackspaceWhileInBatchEdit(final int spaceState, final InputConnection ic) { mVoiceProxy.handleBackspace(); // In many cases, we may have to put the keyboard in auto-shift state again. mHandler.postUpdateShiftKeyState(); if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) { // Cancel multi-character input: remove the text we just entered. // This is triggered on backspace after a key that inputs multiple characters, // like the smiley key or the .com key. ic.deleteSurroundingText(mEnteredText.length(), 0); // If we have mEnteredText, then we know that mHasUncommittedTypedChars == false. // In addition we know that spaceState is false, and that we should not be // reverting any autocorrect at this point. So we can safely return. return; } if (mWordComposer.isComposingWord()) { final int length = mWordComposer.size(); if (length > 0) { mWordComposer.deleteLast(); ic.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); // If we have deleted the last remaining character of a word, then we are not // isComposingWord() any more. if (!mWordComposer.isComposingWord()) { // Not composing word any more, so we can show bigrams. mHandler.postUpdateBigramPredictions(); } else { // Still composing a word, so we still have letters to deduce a suggestion from. mHandler.postUpdateSuggestions(); } } else { ic.deleteSurroundingText(1, 0); } } else { // We should be very careful about auto-correction cancellation and suggestion // resuming here. The behavior needs to be different according to text field types, // and it would be much clearer to test for them explicitly here rather than // relying on implicit values like "whether the suggestion strip is displayed". if (mWordComposer.didAutoCorrectToAnotherWord()) { Utils.Stats.onAutoCorrectionCancellation(); cancelAutoCorrect(ic); return; } if (SPACE_STATE_DOUBLE == spaceState) { if (revertDoubleSpace(ic)) { // No need to reset mSpaceState, it has already be done (that's why we // receive it as a parameter) return; } } else if (SPACE_STATE_SWAP_PUNCTUATION == spaceState) { if (revertSwapPunctuation(ic)) { // Likewise return; } } // See the comment above: must be careful about resuming auto-suggestion. if (mSuggestionsView != null && mSuggestionsView.dismissAddToDictionaryHint()) { // Go back to the suggestion mode if the user canceled the // "Touch again to save". // NOTE: In general, we don't revert the word when backspacing // from a manual suggestion pick. We deliberately chose a // different behavior only in the case of picking the first // suggestion (typed word). It's intentional to have made this // inconsistent with backspacing after selecting other suggestions. restartSuggestionsOnManuallyPickedTypedWord(ic); } else { ic.deleteSurroundingText(1, 0); if (mDeleteCount > DELETE_ACCELERATE_AT) { ic.deleteSurroundingText(1, 0); } if (isSuggestionsRequested()) { restartSuggestionsOnWordBeforeCursorIfAtEndOfWord(ic); } } } } private void handleTab() { final int imeOptions = getCurrentInputEditorInfo().imeOptions; if (!EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions)) { sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB); return; } final InputConnection ic = getCurrentInputConnection(); if (ic == null) return; // True if keyboard is in either chording shift or manual temporary upper case mode. final boolean isManualTemporaryUpperCase = mKeyboardSwitcher.isManualTemporaryUpperCase(); if (EditorInfoCompatUtils.hasFlagNavigateNext(imeOptions) && !isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionNext(ic); } else if (EditorInfoCompatUtils.hasFlagNavigatePrevious(imeOptions) && isManualTemporaryUpperCase) { EditorInfoCompatUtils.performEditorActionPrevious(ic); } } private void handleCharacter(final int primaryCode, final int[] keyCodes, final int x, final int y, final int spaceState) { mVoiceProxy.handleCharacter(); final InputConnection ic = getCurrentInputConnection(); if (null != ic) ic.beginBatchEdit(); // TODO: if ic is null, does it make any sense to call this? handleCharacterWhileInBatchEdit(primaryCode, keyCodes, x, y, spaceState, ic); if (null != ic) ic.endBatchEdit(); } // "ic" may be null without this crashing, but the behavior will be really strange private void handleCharacterWhileInBatchEdit(final int primaryCode, final int[] keyCodes, final int x, final int y, final int spaceState, final InputConnection ic) { if (SPACE_STATE_MAGIC == spaceState && mSettingsValues.isMagicSpaceStripper(primaryCode)) { if (null != ic) removeTrailingSpaceWhileInBatchEdit(ic); } boolean isComposingWord = mWordComposer.isComposingWord(); int code = primaryCode; if ((isAlphabet(code) || mSettingsValues.isSymbolExcludedFromWordSeparators(code)) && isSuggestionsRequested() && !isCursorTouchingWord()) { if (!isComposingWord) { // Reset entirely the composing state anyway, then start composing a new word unless // the character is a single quote. The idea here is, single quote is not a // separator and it should be treated as a normal character, except in the first // position where it should not start composing a word. isComposingWord = (Keyboard.CODE_SINGLE_QUOTE != code); mWordComposer.reset(); clearSuggestions(); mComposingStateManager.onFinishComposingText(); } } final KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isShiftedOrShiftLocked()) { if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT || keyCodes[0] > Character.MAX_CODE_POINT) { return; } code = keyCodes[0]; if (switcher.isAlphabetMode() && Character.isLowerCase(code)) { // In some locales, such as Turkish, Character.toUpperCase() may return a wrong // character because it doesn't take care of locale. final String upperCaseString = new String(new int[] {code}, 0, 1) .toUpperCase(mSubtypeSwitcher.getInputLocale()); if (upperCaseString.codePointCount(0, upperCaseString.length()) == 1) { code = upperCaseString.codePointAt(0); } else { // Some keys, such as [eszett], have upper case as multi-characters. onTextInput(upperCaseString); return; } } } if (isComposingWord) { mWordComposer.add(code, keyCodes, x, y); if (ic != null) { // If it's the first letter, make note of auto-caps state if (mWordComposer.size() == 1) { mWordComposer.setAutoCapitalized(getCurrentAutoCapsState()); mComposingStateManager.onStartComposingText(); } ic.setComposingText(getTextWithUnderline(mWordComposer.getTypedWord()), 1); } mHandler.postUpdateSuggestions(); } else { sendKeyChar((char)code); } if (SPACE_STATE_MAGIC == spaceState && mSettingsValues.isMagicSpaceSwapper(primaryCode)) { if (null != ic) swapSwapperAndSpaceWhileInBatchEdit(ic); } if (mSettingsValues.isWordSeparator(code)) { Utils.Stats.onSeparator((char)code, x, y); } else { Utils.Stats.onNonSeparator((char)code, x, y); } } private void handleSeparator(final int primaryCode, final int x, final int y, final int spaceState) { mVoiceProxy.handleSeparator(); mComposingStateManager.onFinishComposingText(); // Should dismiss the "Touch again to save" message when handling separator if (mSuggestionsView != null && mSuggestionsView.dismissAddToDictionaryHint()) { mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // Handle separator final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mWordComposer.isComposingWord()) { // In certain languages where single quote is a separator, it's better // not to auto correct, but accept the typed word. For instance, // in Italian dov' should not be expanded to dove' because the elision // requires the last vowel to be removed. final boolean shouldAutoCorrect = mSettingsValues.mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; if (shouldAutoCorrect && primaryCode != Keyboard.CODE_SINGLE_QUOTE) { commitCurrentAutoCorrection(primaryCode, ic); } else { commitTyped(ic); } } final boolean swapMagicSpace; if (Keyboard.CODE_ENTER == primaryCode && (SPACE_STATE_MAGIC == spaceState || SPACE_STATE_SWAP_PUNCTUATION == spaceState)) { removeTrailingSpaceWhileInBatchEdit(ic); swapMagicSpace = false; } else if (SPACE_STATE_MAGIC == spaceState) { if (mSettingsValues.isMagicSpaceSwapper(primaryCode)) { swapMagicSpace = true; } else { swapMagicSpace = false; if (mSettingsValues.isMagicSpaceStripper(primaryCode)) { removeTrailingSpaceWhileInBatchEdit(ic); } } } else { swapMagicSpace = false; } sendKeyChar((char)primaryCode); if (Keyboard.CODE_SPACE == primaryCode) { if (isSuggestionsRequested()) { if (maybeDoubleSpaceWhileInBatchEdit(ic)) { mSpaceState = SPACE_STATE_DOUBLE; } else if (!isShowingPunctuationList()) { mSpaceState = SPACE_STATE_WEAK; } } mHandler.startDoubleSpacesTimer(); if (!isCursorTouchingWord()) { mHandler.cancelUpdateSuggestions(); mHandler.postUpdateBigramPredictions(); } } else { if (swapMagicSpace) { swapSwapperAndSpaceWhileInBatchEdit(ic); mSpaceState = SPACE_STATE_MAGIC; } // Set punctuation right away. onUpdateSelection will fire but tests whether it is // already displayed or not, so it's okay. setPunctuationSuggestions(); } Utils.Stats.onSeparator((char)primaryCode, x, y); if (ic != null) { ic.endBatchEdit(); } } private CharSequence getTextWithUnderline(final CharSequence text) { return mComposingStateManager.isAutoCorrectionIndicatorOn() ? SuggestionSpanUtils.getTextWithAutoCorrectionIndicatorUnderline(this, text) : mWordComposer.getTypedWord(); } private void handleClose() { commitTyped(getCurrentInputConnection()); mVoiceProxy.handleClose(); requestHideSelf(0); LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) inputView.closing(); } public boolean isSuggestionsRequested() { return mInputAttributes.mIsSettingsSuggestionStripOn && (mCorrectionMode > 0 || isShowingSuggestionsStrip()); } public boolean isShowingPunctuationList() { if (mSuggestionsView == null) return false; return mSettingsValues.mSuggestPuncList == mSuggestionsView.getSuggestions(); } public boolean isShowingSuggestionsStrip() { return (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_VALUE) || (mSuggestionVisibility == SUGGESTION_VISIBILILTY_SHOW_ONLY_PORTRAIT_VALUE && mDisplayOrientation == Configuration.ORIENTATION_PORTRAIT); } public boolean isSuggestionsStripVisible() { if (mSuggestionsView == null) return false; if (mSuggestionsView.isShowingAddToDictionaryHint()) return true; if (!isShowingSuggestionsStrip()) return false; if (mInputAttributes.mApplicationSpecifiedCompletionOn) return true; return isSuggestionsRequested(); } public void switchToKeyboardView() { if (DEBUG) { Log.d(TAG, "Switch to keyboard view."); } View v = mKeyboardSwitcher.getKeyboardView(); if (v != null) { // Confirms that the keyboard view doesn't have parent view. ViewParent p = v.getParent(); if (p != null && p instanceof ViewGroup) { ((ViewGroup) p).removeView(v); } setInputView(v); } setSuggestionStripShown(isSuggestionsStripVisible()); updateInputViewShown(); mHandler.postUpdateSuggestions(); } public void clearSuggestions() { setSuggestions(SuggestedWords.EMPTY); } public void setSuggestions(SuggestedWords words) { if (mSuggestionsView != null) { mSuggestionsView.setSuggestions(words); mKeyboardSwitcher.onAutoCorrectionStateChanged( words.hasWordAboveAutoCorrectionScoreThreshold()); } // Put a blue underline to a word in TextView which will be auto-corrected. final InputConnection ic = getCurrentInputConnection(); if (ic != null) { final boolean oldAutoCorrectionIndicator = mComposingStateManager.isAutoCorrectionIndicatorOn(); final boolean newAutoCorrectionIndicator = Utils.willAutoCorrect(words); if (oldAutoCorrectionIndicator != newAutoCorrectionIndicator) { mComposingStateManager.setAutoCorrectionIndicatorOn(newAutoCorrectionIndicator); if (DEBUG) { Log.d(TAG, "Flip the indicator. " + oldAutoCorrectionIndicator + " -> " + newAutoCorrectionIndicator); if (newAutoCorrectionIndicator != mComposingStateManager.isAutoCorrectionIndicatorOn()) { throw new RuntimeException("Couldn't flip the indicator! We are not " + "composing a word right now."); } } final CharSequence textWithUnderline = getTextWithUnderline(mWordComposer.getTypedWord()); if (!TextUtils.isEmpty(textWithUnderline)) { ic.setComposingText(textWithUnderline, 1); } } } } public void updateSuggestions() { // Check if we have a suggestion engine attached. if ((mSuggest == null || !isSuggestionsRequested()) && !mVoiceProxy.isVoiceInputHighlighted()) { if (mWordComposer.isComposingWord()) { Log.w(TAG, "Called updateSuggestions but suggestions were not requested!"); mWordComposer.setAutoCorrection(mWordComposer.getTypedWord()); } return; } mHandler.cancelUpdateSuggestions(); mHandler.cancelUpdateBigramPredictions(); if (!mWordComposer.isComposingWord()) { setPunctuationSuggestions(); return; } // TODO: May need a better way of retrieving previous word final InputConnection ic = getCurrentInputConnection(); final CharSequence prevWord; if (null == ic) { prevWord = null; } else { prevWord = EditingUtils.getPreviousWord(ic, mSettingsValues.mWordSeparators); } // getSuggestedWordBuilder handles gracefully a null value of prevWord final SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(mWordComposer, prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(), mCorrectionMode); boolean autoCorrectionAvailable = !mInputAttributes.mInputTypeNoAutoCorrect && mSuggest.hasAutoCorrection(); final CharSequence typedWord = mWordComposer.getTypedWord(); // Here, we want to promote a whitelisted word if exists. // TODO: Change this scheme - a boolean is not enough. A whitelisted word may be "valid" // but still autocorrected from - in the case the whitelist only capitalizes the word. // The whitelist should be case-insensitive, so it's not possible to be consistent with // a boolean flag. Right now this is handled with a slight hack in // WhitelistDictionary#shouldForciblyAutoCorrectFrom. final int quotesCount = mWordComposer.trailingSingleQuotesCount(); final boolean allowsToBeAutoCorrected = AutoCorrection.allowsToBeAutoCorrected( mSuggest.getUnigramDictionaries(), // If the typed string ends with a single quote, for dictionary lookup purposes // we behave as if the single quote was not here. Here, we are looking up the // typed string in the dictionary (to avoid autocorrecting from an existing // word, so for consistency this lookup should be made WITHOUT the trailing // single quote. quotesCount > 0 ? typedWord.subSequence(0, typedWord.length() - quotesCount) : typedWord, preferCapitalization()); if (mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) { autoCorrectionAvailable |= (!allowsToBeAutoCorrected); } // Don't auto-correct words with multiple capital letter autoCorrectionAvailable &= !mWordComposer.isMostlyCaps(); // Basically, we update the suggestion strip only when suggestion count > 1. However, // there is an exception: We update the suggestion strip whenever typed word's length // is 1 or typed word is found in dictionary, regardless of suggestion count. Actually, // in most cases, suggestion count is 1 when typed word's length is 1, but we do always // need to clear the previous state when the user starts typing a word (i.e. typed word's // length == 1). if (typedWord != null) { if (builder.size() > 1 || typedWord.length() == 1 || (!allowsToBeAutoCorrected) || mSuggestionsView.isShowingAddToDictionaryHint()) { builder.setTypedWordValid(!allowsToBeAutoCorrected).setHasMinimalSuggestion( autoCorrectionAvailable); } else { SuggestedWords previousSuggestions = mSuggestionsView.getSuggestions(); if (previousSuggestions == mSettingsValues.mSuggestPuncList) { if (builder.size() == 0) { return; } previousSuggestions = SuggestedWords.EMPTY; } builder.addTypedWordAndPreviousSuggestions(typedWord, previousSuggestions); } } showSuggestions(builder.build(), typedWord); } public void showSuggestions(SuggestedWords suggestedWords, CharSequence typedWord) { final boolean shouldBlockAutoCorrectionBySafetyNet = Utils.shouldBlockAutoCorrectionBySafetyNet(suggestedWords, mSuggest); if (shouldBlockAutoCorrectionBySafetyNet) { suggestedWords.setShouldBlockAutoCorrection(); } setSuggestions(suggestedWords); if (suggestedWords.size() > 0) { if (shouldBlockAutoCorrectionBySafetyNet) { mWordComposer.setAutoCorrection(typedWord); } else if (suggestedWords.hasAutoCorrectionWord()) { mWordComposer.setAutoCorrection(suggestedWords.getWord(1)); } else { mWordComposer.setAutoCorrection(typedWord); } } else { // TODO: replace with mWordComposer.deleteAutoCorrection()? mWordComposer.setAutoCorrection(null); } setSuggestionStripShown(isSuggestionsStripVisible()); } private void commitCurrentAutoCorrection(final int separatorCodePoint, final InputConnection ic) { // Complete any pending suggestions query first if (mHandler.hasPendingUpdateSuggestions()) { mHandler.cancelUpdateSuggestions(); updateSuggestions(); } final CharSequence autoCorrection = mWordComposer.getAutoCorrectionOrNull(); if (autoCorrection != null) { final String typedWord = mWordComposer.getTypedWord(); if (TextUtils.isEmpty(typedWord)) { throw new RuntimeException("We have an auto-correction but the typed word " + "is empty? Impossible! I must commit suicide."); } Utils.Stats.onAutoCorrection(typedWord, autoCorrection.toString(), separatorCodePoint); mExpectingUpdateSelection = true; commitChosenWord(autoCorrection, WordComposer.COMMIT_TYPE_DECIDED_WORD); // Add the word to the user unigram dictionary if it's not a known word addToUserUnigramAndBigramDictionaries(autoCorrection, UserUnigramDictionary.FREQUENCY_FOR_TYPED); if (!typedWord.equals(autoCorrection) && null != ic) { // This will make the correction flash for a short while as a visual clue // to the user that auto-correction happened. InputConnectionCompatUtils.commitCorrection(ic, mLastSelectionEnd - typedWord.length(), typedWord, autoCorrection); } } } @Override public void pickSuggestionManually(int index, CharSequence suggestion) { mComposingStateManager.onFinishComposingText(); SuggestedWords suggestions = mSuggestionsView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mInputAttributes.mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { if (ic != null) { final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; ic.commitCompletion(completionInfo); } if (mSuggestionsView != null) { mSuggestionsView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be swapped // if it was a magic or a weak space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final int rawPrimaryCode = suggestion.charAt(0); // Maybe apply the "bidi mirrored" conversions for parentheses final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final boolean isRtl = keyboard != null && keyboard.mIsRtlKeyboard; final int primaryCode = Key.getRtlParenthesisCode(rawPrimaryCode, isRtl); insertPunctuationFromSuggestionStrip(ic, primaryCode); // TODO: the following endBatchEdit seems useless, check if (ic != null) { ic.endBatchEdit(); } return; } + // We need to log before we commit, because the word composer will store away the user + // typed word. + LatinImeLogger.logOnManualSuggestion(mWordComposer.getTypedWord().toString(), + suggestion.toString(), index, suggestions.mWords); mExpectingUpdateSelection = true; commitChosenWord(suggestion, WordComposer.COMMIT_TYPE_MANUAL_PICK); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToUserUnigramAndBigramDictionaries(suggestion, UserUnigramDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } - // TODO: the following is fishy, because it seems there may be cases where we are not - // composing a word at all. Maybe throw an exception if !mWordComposer.isComposingWord() ? - LatinImeLogger.logOnManualSuggestion(mWordComposer.getTypedWord().toString(), - suggestion.toString(), index, suggestions.mWords); // Follow it with a space if (mInputAttributes.mInsertSpaceOnPickSuggestionManually) { sendMagicSpace(); } // We should show the "Touch again to save" hint if the user pressed the first entry // AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mSuggest.hasMainDictionary() is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mSuggest.hasMainDictionary() // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); Utils.Stats.onSeparator((char)Keyboard.CODE_SPACE, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. updateBigramPredictions(); // Updating the predictions right away may be slow and feel unresponsive on slower // terminals. On the other hand if we just postUpdateBigramPredictions() it will // take a noticeable delay to update them which may feel uneasy. } else { if (mIsUserDictionaryAvailable) { mSuggestionsView.showAddToDictionaryHint( suggestion, mSettingsValues.mHintToSaveText); } else { mHandler.postUpdateSuggestions(); } } if (ic != null) { ic.endBatchEdit(); } } /** * Commits the chosen word to the text field and saves it for later retrieval. */ private void commitChosenWord(final CharSequence bestWord, final int commitType) { final InputConnection ic = getCurrentInputConnection(); if (ic != null) { mVoiceProxy.rememberReplacedWord(bestWord, mSettingsValues.mWordSeparators); if (mSettingsValues.mEnableSuggestionSpanInsertion) { final SuggestedWords suggestedWords = mSuggestionsView.getSuggestions(); ic.commitText(SuggestionSpanUtils.getTextWithSuggestionSpan( this, bestWord, suggestedWords), 1); } else { ic.commitText(bestWord, 1); } } // TODO: figure out here if this is an auto-correct or if the best word is actually // what user typed. Note: currently this is done much later in // WordComposer#didAutoCorrectToAnotherWord by string equality of the remembered // strings. mWordComposer.onCommitWord(commitType); } private static final WordComposer sEmptyWordComposer = new WordComposer(); public void updateBigramPredictions() { if (mSuggest == null || !isSuggestionsRequested()) return; if (!mSettingsValues.mBigramPredictionEnabled) { setPunctuationSuggestions(); return; } final CharSequence prevWord = EditingUtils.getThisWord(getCurrentInputConnection(), mSettingsValues.mWordSeparators); SuggestedWords.Builder builder = mSuggest.getSuggestedWordBuilder(sEmptyWordComposer, prevWord, mKeyboardSwitcher.getKeyboard().getProximityInfo(), mCorrectionMode); if (builder.size() > 0) { // Explicitly supply an empty typed word (the no-second-arg version of // showSuggestions will retrieve the word near the cursor, we don't want that here) showSuggestions(builder.build(), ""); } else { if (!isShowingPunctuationList()) setPunctuationSuggestions(); } } public void setPunctuationSuggestions() { setSuggestions(mSettingsValues.mSuggestPuncList); setSuggestionStripShown(isSuggestionsStripVisible()); } private void addToUserUnigramAndBigramDictionaries(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, false); } private void addToOnlyBigramDictionary(CharSequence suggestion, int frequencyDelta) { checkAddToDictionary(suggestion, frequencyDelta, true); } /** * Adds to the UserBigramDictionary and/or UserUnigramDictionary * @param selectedANotTypedWord true if it should be added to bigram dictionary if possible */ private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta, boolean selectedANotTypedWord) { if (suggestion == null || suggestion.length() < 1) return; // Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be // adding words in situations where the user or application really didn't // want corrections enabled or learned. if (!(mCorrectionMode == Suggest.CORRECTION_FULL || mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) { return; } if (null != mSuggest && null != mUserUnigramDictionary) { final boolean selectedATypedWordAndItsInUserUnigramDic = !selectedANotTypedWord && mUserUnigramDictionary.isValidWord(suggestion); final boolean isValidWord = AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true); final boolean needsToAddToUserUnigramDictionary = selectedATypedWordAndItsInUserUnigramDic || !isValidWord; if (needsToAddToUserUnigramDictionary) { mUserUnigramDictionary.addWord(suggestion.toString(), frequencyDelta); } } if (mUserBigramDictionary != null) { // We don't want to register as bigrams words separated by a separator. // For example "I will, and you too" : we don't want the pair ("will" "and") to be // a bigram. final InputConnection ic = getCurrentInputConnection(); if (null != ic) { final CharSequence prevWord = EditingUtils.getPreviousWord(ic, mSettingsValues.mWordSeparators); if (!TextUtils.isEmpty(prevWord)) { mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString()); } } } } public boolean isCursorTouchingWord() { final InputConnection ic = getCurrentInputConnection(); if (ic == null) return false; CharSequence toLeft = ic.getTextBeforeCursor(1, 0); CharSequence toRight = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(toLeft) && !mSettingsValues.isWordSeparator(toLeft.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toLeft.charAt(0))) { return true; } if (!TextUtils.isEmpty(toRight) && !mSettingsValues.isWordSeparator(toRight.charAt(0)) && !mSettingsValues.isSuggestedPunctuation(toRight.charAt(0))) { return true; } return false; } // "ic" must not be null private static boolean sameAsTextBeforeCursor(final InputConnection ic, CharSequence text) { CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0); return TextUtils.equals(text, beforeText); } // "ic" must not be null /** * Check if the cursor is actually at the end of a word. If so, restart suggestions on this * word, else do nothing. */ private void restartSuggestionsOnWordBeforeCursorIfAtEndOfWord( final InputConnection ic) { // Bail out if the cursor is not at the end of a word (cursor must be preceded by // non-whitespace, non-separator, non-start-of-text) // Example ("|" is the cursor here) : <SOL>"|a" " |a" " | " all get rejected here. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(1, 0); if (TextUtils.isEmpty(textBeforeCursor) || mSettingsValues.isWordSeparator(textBeforeCursor.charAt(0))) return; // Bail out if the cursor is in the middle of a word (cursor must be followed by whitespace, // separator or end of line/text) // Example: "test|"<EOL> "te|st" get rejected here final CharSequence textAfterCursor = ic.getTextAfterCursor(1, 0); if (!TextUtils.isEmpty(textAfterCursor) && !mSettingsValues.isWordSeparator(textAfterCursor.charAt(0))) return; // Bail out if word before cursor is 0-length or a single non letter (like an apostrophe) // Example: " -|" gets rejected here but "e-|" and "e|" are okay CharSequence word = EditingUtils.getWordAtCursor(ic, mSettingsValues.mWordSeparators); // We don't suggest on leading single quotes, so we have to remove them from the word if // it starts with single quotes. while (!TextUtils.isEmpty(word) && Keyboard.CODE_SINGLE_QUOTE == word.charAt(0)) { word = word.subSequence(1, word.length()); } if (TextUtils.isEmpty(word)) return; final char firstChar = word.charAt(0); // we just tested that word is not empty if (word.length() == 1 && !Character.isLetter(firstChar)) return; // We only suggest on words that start with a letter or a symbol that is excluded from // word separators (see #handleCharacterWhileInBatchEdit). if (!(isAlphabet(firstChar) || mSettingsValues.isSymbolExcludedFromWordSeparators(firstChar))) { return; } // Okay, we are at the end of a word. Restart suggestions. restartSuggestionsOnWordBeforeCursor(ic, word); } // "ic" must not be null private void restartSuggestionsOnWordBeforeCursor(final InputConnection ic, final CharSequence word) { mWordComposer.setComposingWord(word, mKeyboardSwitcher.getKeyboard()); mComposingStateManager.onStartComposingText(); ic.deleteSurroundingText(word.length(), 0); ic.setComposingText(word, 1); mHandler.postUpdateSuggestions(); } // "ic" must not be null private void cancelAutoCorrect(final InputConnection ic) { mWordComposer.resumeSuggestionOnKeptWord(); final String originallyTypedWord = mWordComposer.getTypedWord(); final CharSequence autoCorrectedTo = mWordComposer.getAutoCorrectionOrNull(); final int cancelLength = autoCorrectedTo.length(); final CharSequence separator = ic.getTextBeforeCursor(1, 0); if (DEBUG) { final String wordBeforeCursor = ic.getTextBeforeCursor(cancelLength + 1, 0).subSequence(0, cancelLength) .toString(); if (!autoCorrectedTo.equals(wordBeforeCursor)) { throw new RuntimeException("cancelAutoCorrect check failed: we thought we were " + "reverting \"" + autoCorrectedTo + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); } if (originallyTypedWord.equals(wordBeforeCursor)) { throw new RuntimeException("cancelAutoCorrect check failed: we wanted to cancel " + "auto correction and revert to \"" + originallyTypedWord + "\" but we found this very string before the cursor"); } } ic.deleteSurroundingText(cancelLength + 1, 0); ic.commitText(originallyTypedWord, 1); // Re-insert the separator ic.commitText(separator, 1); mWordComposer.deleteAutoCorrection(); mWordComposer.onCommitWord(WordComposer.COMMIT_TYPE_CANCEL_AUTO_CORRECT); Utils.Stats.onSeparator(separator.charAt(0), WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // "ic" must not be null private void restartSuggestionsOnManuallyPickedTypedWord(final InputConnection ic) { // Note: this relies on the last word still being held in the WordComposer, in // the field for suggestion resuming. // Note: in the interest of code simplicity, we may want to just call // restartSuggestionsOnWordBeforeCursorIfAtEndOfWord instead, but retrieving // the old WordComposer allows to reuse the actual typed coordinates. mWordComposer.resumeSuggestionOnKeptWord(); // We resume suggestion, and then we want to set the composing text to the content // of the word composer again. But since we just manually picked a word, there is // no composing text at the moment, so we have to delete the word before we set a // new composing text. final int restartLength = mWordComposer.size(); if (DEBUG) { final String wordBeforeCursor = ic.getTextBeforeCursor(restartLength + 1, 0).subSequence(0, restartLength) .toString(); if (!mWordComposer.getTypedWord().equals(wordBeforeCursor)) { throw new RuntimeException("restartSuggestionsOnManuallyPickedTypedWord " + "check failed: we thought we were reverting \"" + mWordComposer.getTypedWord() + "\", but before the cursor we found \"" + wordBeforeCursor + "\""); } } // Warning: this +1 takes into account the extra space added by the manual pick process. ic.deleteSurroundingText(restartLength + 1, 0); ic.setComposingText(mWordComposer.getTypedWord(), 1); mHandler.cancelUpdateBigramPredictions(); mHandler.postUpdateSuggestions(); } // "ic" must not be null private boolean revertDoubleSpace(final InputConnection ic) { mHandler.cancelDoubleSpacesTimer(); // Here we test whether we indeed have a period and a space before us. This should not // be needed, but it's there just in case something went wrong. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(2, 0); if (!". ".equals(textBeforeCursor)) { // We should not have come here if we aren't just after a ". ". throw new RuntimeException("Tried to revert double-space combo but we didn't find " + "\". \" just before the cursor."); } ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(" ", 1); ic.endBatchEdit(); return true; } private static boolean revertSwapPunctuation(final InputConnection ic) { // Here we test whether we indeed have a space and something else before us. This should not // be needed, but it's there just in case something went wrong. final CharSequence textBeforeCursor = ic.getTextBeforeCursor(2, 0); // NOTE: This does not work with surrogate pairs. Hopefully when the keyboard is able to // enter surrogate pairs this code will have been removed. if (Keyboard.CODE_SPACE != textBeforeCursor.charAt(1)) { // We should not have come here if the text before the cursor is not a space. throw new RuntimeException("Tried to revert a swap of punctuation but we didn't " + "find a space just before the cursor."); } ic.beginBatchEdit(); ic.deleteSurroundingText(2, 0); ic.commitText(" " + textBeforeCursor.subSequence(0, 1), 1); ic.endBatchEdit(); return true; } public boolean isWordSeparator(int code) { return mSettingsValues.isWordSeparator(code); } private void sendMagicSpace() { sendKeyChar((char)Keyboard.CODE_SPACE); mSpaceState = SPACE_STATE_MAGIC; mKeyboardSwitcher.updateShiftState(); } public boolean preferCapitalization() { return mWordComposer.isFirstCharCapitalized(); } // Notify that language or mode have been changed and toggleLanguage will update KeyboardID // according to new language or mode. public void onRefreshKeyboard() { if (!CAN_HANDLE_ON_CURRENT_INPUT_METHOD_SUBTYPE_CHANGED) { // Before Honeycomb, Voice IME is in LatinIME and it changes the current input view, // so that we need to re-create the keyboard input view here. setInputView(mKeyboardSwitcher.onCreateInputView()); } // When the device locale is changed in SetupWizard etc., this method may get called via // onConfigurationChanged before SoftInputWindow is shown. if (mKeyboardSwitcher.getKeyboardView() != null) { // Reload keyboard because the current language has been changed. mKeyboardSwitcher.loadKeyboard(getCurrentInputEditorInfo(), mSettingsValues); } initSuggest(); loadSettings(); } private void hapticAndAudioFeedback(int primaryCode) { vibrate(); playKeyClick(primaryCode); } @Override public void onPressKey(int primaryCode) { final KeyboardSwitcher switcher = mKeyboardSwitcher; if (switcher.isVibrateAndSoundFeedbackRequired()) { hapticAndAudioFeedback(primaryCode); } switcher.onPressKey(primaryCode); } @Override public void onReleaseKey(int primaryCode, boolean withSliding) { mKeyboardSwitcher.onReleaseKey(primaryCode, withSliding); } // receive ringer mode change and network state change. private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) { updateRingerMode(); } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { mSubtypeSwitcher.onNetworkStateChanged(intent); } } }; // update flags for silent mode private void updateRingerMode() { if (mAudioManager == null) { mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); if (mAudioManager == null) return; } mSilentModeOn = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL); } private void playKeyClick(int primaryCode) { // if mAudioManager is null, we don't have the ringer state yet // mAudioManager will be set by updateRingerMode if (mAudioManager == null) { if (mKeyboardSwitcher.getKeyboardView() != null) { updateRingerMode(); } } if (isSoundOn()) { final int sound; switch (primaryCode) { case Keyboard.CODE_DELETE: sound = AudioManager.FX_KEYPRESS_DELETE; break; case Keyboard.CODE_ENTER: sound = AudioManager.FX_KEYPRESS_RETURN; break; case Keyboard.CODE_SPACE: sound = AudioManager.FX_KEYPRESS_SPACEBAR; break; default: sound = AudioManager.FX_KEYPRESS_STANDARD; break; } mAudioManager.playSoundEffect(sound, mSettingsValues.mFxVolume); } } public void vibrate() { if (!mSettingsValues.mVibrateOn) { return; } if (mSettingsValues.mKeypressVibrationDuration < 0) { // Go ahead with the system default LatinKeyboardView inputView = mKeyboardSwitcher.getKeyboardView(); if (inputView != null) { inputView.performHapticFeedback( HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); } } else if (mVibrator != null) { mVibrator.vibrate(mSettingsValues.mKeypressVibrationDuration); } } public boolean isAutoCapitalized() { return mWordComposer.isAutoCapitalized(); } boolean isSoundOn() { return mSettingsValues.mSoundOn && !mSilentModeOn; } private void updateCorrectionMode() { // TODO: cleanup messy flags final boolean shouldAutoCorrect = mSettingsValues.mAutoCorrectEnabled && !mInputAttributes.mInputTypeNoAutoCorrect; mCorrectionMode = shouldAutoCorrect ? Suggest.CORRECTION_FULL : Suggest.CORRECTION_NONE; mCorrectionMode = (mSettingsValues.mBigramSuggestionEnabled && shouldAutoCorrect) ? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode; } private void updateSuggestionVisibility(final Resources res) { final String suggestionVisiblityStr = mSettingsValues.mShowSuggestionsSetting; for (int visibility : SUGGESTION_VISIBILITY_VALUE_ARRAY) { if (suggestionVisiblityStr.equals(res.getString(visibility))) { mSuggestionVisibility = visibility; break; } } } protected void launchSettings() { launchSettingsClass(Settings.class); } public void launchDebugSettings() { launchSettingsClass(DebugSettings.class); } protected void launchSettingsClass(Class<? extends PreferenceActivity> settingsClass) { handleClose(); Intent intent = new Intent(); intent.setClass(LatinIME.this, settingsClass); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void showSubtypeSelectorAndSettings() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { // TODO: Should use new string "Select active input modes". getString(R.string.language_selection_title), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: Intent intent = CompatUtils.getInputLanguageSelectionIntent( Utils.getInputMethodId(mImm, getPackageName()), Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(items, listener) .setTitle(title); showOptionDialogInternal(builder.create()); } private void showOptionsMenu() { final CharSequence title = getString(R.string.english_ime_input_options); final CharSequence[] items = new CharSequence[] { getString(R.string.selectInputMethod), getString(R.string.english_ime_settings), }; final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int position) { di.dismiss(); switch (position) { case 0: mImm.showInputMethodPicker(); break; case 1: launchSettings(); break; } } }; final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setItems(items, listener) .setTitle(title); showOptionDialogInternal(builder.create()); } @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { super.dump(fd, fout, args); final Printer p = new PrintWriterPrinter(fout); p.println("LatinIME state :"); final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final int keyboardMode = keyboard != null ? keyboard.mId.mMode : -1; p.println(" Keyboard mode = " + keyboardMode); p.println(" mIsSuggestionsRequested=" + mInputAttributes.mIsSettingsSuggestionStripOn); p.println(" mCorrectionMode=" + mCorrectionMode); p.println(" isComposingWord=" + mWordComposer.isComposingWord()); p.println(" mAutoCorrectEnabled=" + mSettingsValues.mAutoCorrectEnabled); p.println(" mSoundOn=" + mSettingsValues.mSoundOn); p.println(" mVibrateOn=" + mSettingsValues.mVibrateOn); p.println(" mKeyPreviewPopupOn=" + mSettingsValues.mKeyPreviewPopupOn); p.println(" mInputAttributes=" + mInputAttributes.toString()); } }
false
true
public void pickSuggestionManually(int index, CharSequence suggestion) { mComposingStateManager.onFinishComposingText(); SuggestedWords suggestions = mSuggestionsView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mInputAttributes.mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { if (ic != null) { final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; ic.commitCompletion(completionInfo); } if (mSuggestionsView != null) { mSuggestionsView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be swapped // if it was a magic or a weak space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final int rawPrimaryCode = suggestion.charAt(0); // Maybe apply the "bidi mirrored" conversions for parentheses final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final boolean isRtl = keyboard != null && keyboard.mIsRtlKeyboard; final int primaryCode = Key.getRtlParenthesisCode(rawPrimaryCode, isRtl); insertPunctuationFromSuggestionStrip(ic, primaryCode); // TODO: the following endBatchEdit seems useless, check if (ic != null) { ic.endBatchEdit(); } return; } mExpectingUpdateSelection = true; commitChosenWord(suggestion, WordComposer.COMMIT_TYPE_MANUAL_PICK); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToUserUnigramAndBigramDictionaries(suggestion, UserUnigramDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } // TODO: the following is fishy, because it seems there may be cases where we are not // composing a word at all. Maybe throw an exception if !mWordComposer.isComposingWord() ? LatinImeLogger.logOnManualSuggestion(mWordComposer.getTypedWord().toString(), suggestion.toString(), index, suggestions.mWords); // Follow it with a space if (mInputAttributes.mInsertSpaceOnPickSuggestionManually) { sendMagicSpace(); } // We should show the "Touch again to save" hint if the user pressed the first entry // AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mSuggest.hasMainDictionary() is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mSuggest.hasMainDictionary() // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); Utils.Stats.onSeparator((char)Keyboard.CODE_SPACE, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. updateBigramPredictions(); // Updating the predictions right away may be slow and feel unresponsive on slower // terminals. On the other hand if we just postUpdateBigramPredictions() it will // take a noticeable delay to update them which may feel uneasy. } else { if (mIsUserDictionaryAvailable) { mSuggestionsView.showAddToDictionaryHint( suggestion, mSettingsValues.mHintToSaveText); } else { mHandler.postUpdateSuggestions(); } } if (ic != null) { ic.endBatchEdit(); } }
public void pickSuggestionManually(int index, CharSequence suggestion) { mComposingStateManager.onFinishComposingText(); SuggestedWords suggestions = mSuggestionsView.getSuggestions(); mVoiceProxy.flushAndLogAllTextModificationCounters(index, suggestion, mSettingsValues.mWordSeparators); final InputConnection ic = getCurrentInputConnection(); if (ic != null) { ic.beginBatchEdit(); } if (mInputAttributes.mApplicationSpecifiedCompletionOn && mApplicationSpecifiedCompletions != null && index >= 0 && index < mApplicationSpecifiedCompletions.length) { if (ic != null) { final CompletionInfo completionInfo = mApplicationSpecifiedCompletions[index]; ic.commitCompletion(completionInfo); } if (mSuggestionsView != null) { mSuggestionsView.clear(); } mKeyboardSwitcher.updateShiftState(); if (ic != null) { ic.endBatchEdit(); } return; } // If this is a punctuation, apply it through the normal key press if (suggestion.length() == 1 && (mSettingsValues.isWordSeparator(suggestion.charAt(0)) || mSettingsValues.isSuggestedPunctuation(suggestion.charAt(0)))) { // Word separators are suggested before the user inputs something. // So, LatinImeLogger logs "" as a user's input. LatinImeLogger.logOnManualSuggestion( "", suggestion.toString(), index, suggestions.mWords); // Find out whether the previous character is a space. If it is, as a special case // for punctuation entered through the suggestion strip, it should be swapped // if it was a magic or a weak space. This is meant to help in case the user // pressed space on purpose of displaying the suggestion strip punctuation. final int rawPrimaryCode = suggestion.charAt(0); // Maybe apply the "bidi mirrored" conversions for parentheses final Keyboard keyboard = mKeyboardSwitcher.getKeyboard(); final boolean isRtl = keyboard != null && keyboard.mIsRtlKeyboard; final int primaryCode = Key.getRtlParenthesisCode(rawPrimaryCode, isRtl); insertPunctuationFromSuggestionStrip(ic, primaryCode); // TODO: the following endBatchEdit seems useless, check if (ic != null) { ic.endBatchEdit(); } return; } // We need to log before we commit, because the word composer will store away the user // typed word. LatinImeLogger.logOnManualSuggestion(mWordComposer.getTypedWord().toString(), suggestion.toString(), index, suggestions.mWords); mExpectingUpdateSelection = true; commitChosenWord(suggestion, WordComposer.COMMIT_TYPE_MANUAL_PICK); // Add the word to the auto dictionary if it's not a known word if (index == 0) { addToUserUnigramAndBigramDictionaries(suggestion, UserUnigramDictionary.FREQUENCY_FOR_PICKED); } else { addToOnlyBigramDictionary(suggestion, 1); } // Follow it with a space if (mInputAttributes.mInsertSpaceOnPickSuggestionManually) { sendMagicSpace(); } // We should show the "Touch again to save" hint if the user pressed the first entry // AND either: // - There is no dictionary (we know that because we tried to load it => null != mSuggest // AND mSuggest.hasMainDictionary() is false) // - There is a dictionary and the word is not in it // Please note that if mSuggest is null, it means that everything is off: suggestion // and correction, so we shouldn't try to show the hint // We used to look at mCorrectionMode here, but showing the hint should have nothing // to do with the autocorrection setting. final boolean showingAddToDictionaryHint = index == 0 && mSuggest != null // If there is no dictionary the hint should be shown. && (!mSuggest.hasMainDictionary() // If "suggestion" is not in the dictionary, the hint should be shown. || !AutoCorrection.isValidWord( mSuggest.getUnigramDictionaries(), suggestion, true)); Utils.Stats.onSeparator((char)Keyboard.CODE_SPACE, WordComposer.NOT_A_COORDINATE, WordComposer.NOT_A_COORDINATE); if (!showingAddToDictionaryHint) { // If we're not showing the "Touch again to save", then show corrections again. // In case the cursor position doesn't change, make sure we show the suggestions again. updateBigramPredictions(); // Updating the predictions right away may be slow and feel unresponsive on slower // terminals. On the other hand if we just postUpdateBigramPredictions() it will // take a noticeable delay to update them which may feel uneasy. } else { if (mIsUserDictionaryAvailable) { mSuggestionsView.showAddToDictionaryHint( suggestion, mSettingsValues.mHintToSaveText); } else { mHandler.postUpdateSuggestions(); } } if (ic != null) { ic.endBatchEdit(); } }
diff --git a/src/com/example/ship/game/GameScene.java b/src/com/example/ship/game/GameScene.java index edb95ae..ee3e935 100644 --- a/src/com/example/ship/game/GameScene.java +++ b/src/com/example/ship/game/GameScene.java @@ -1,86 +1,86 @@ package com.example.ship.game; import com.example.ship.R; import com.example.ship.SceletonActivity; import com.example.ship.atlas.ResourceManager; import org.andengine.engine.Engine; import org.andengine.entity.Entity; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.Background; import org.andengine.entity.sprite.Sprite; import org.andengine.opengl.texture.region.ITextureRegion; import org.andengine.util.color.Color; public class GameScene extends Scene { private static int layerCount = 0; private static final int LAYER_BACKGROUND = layerCount++; private static final int LAYER_FIRST_WAVE = layerCount++; private static final int LAYER_SECOND_WAVE = layerCount++; private static final int LAYER_THIRD_WAVE = layerCount++; private static final int LAYER_GUN = layerCount++; private static final int WAVES_NUMBER = 3; private final SceletonActivity activity; private final Engine mEngine; private final ResourceManager resourceManager; private GameHUD gameHUD; private PauseHUD pauseHUD; private Gun gun; public GameScene(final SceletonActivity activity) { super(); this.activity = activity; this.mEngine = activity.getEngine(); this.resourceManager = activity.getResourceManager(); createBackground(); createGun(); gameHUD = new GameHUD(activity); gameHUD.setEventsToChildren(activity.getEvents()); pauseHUD = new PauseHUD(activity); pauseHUD.setEventsToChildren(activity.getEvents()); } public void switchToPauseHUD() { activity.getCamera().setHUD(pauseHUD); } public void switchToGameHUD() { activity.getCamera().setHUD(gameHUD); } private void createBackground() { for(int i = 0; i < layerCount; i++) { this.attachChild(new Entity()); } ITextureRegion backgroundTexture = resourceManager.getLoadedTextureRegion(R.drawable.gamebackground); Sprite backgroundSprite = new Sprite( 0 , 0 , backgroundTexture , mEngine.getVertexBufferObjectManager()); - ITextureRegion waveSprite = resourceManager.getLoadedTextureRegion(R.drawable.wave); - Sprite waveImage = new Sprite( 0 + ITextureRegion waveTexture = resourceManager.getLoadedTextureRegion(R.drawable.wave); + Sprite waveSprite = new Sprite( 0 , backgroundTexture.getHeight() / WAVES_NUMBER - , waveSprite + , waveTexture , mEngine.getVertexBufferObjectManager()); this.getChildByIndex(LAYER_BACKGROUND).attachChild(backgroundSprite); - this.getChildByIndex(LAYER_FIRST_WAVE).attachChild(waveImage); + this.getChildByIndex(LAYER_FIRST_WAVE).attachChild(waveSprite); Color backgroundColor = new Color(0.09804f, 0.6274f, 0.8784f); this.setBackground(new Background(backgroundColor)); } private void createGun() { gun = new Gun(activity); this.getChildByIndex(LAYER_GUN).attachChild(gun.getSprite()); } public Gun getGun() { return gun; } }
false
true
private void createBackground() { for(int i = 0; i < layerCount; i++) { this.attachChild(new Entity()); } ITextureRegion backgroundTexture = resourceManager.getLoadedTextureRegion(R.drawable.gamebackground); Sprite backgroundSprite = new Sprite( 0 , 0 , backgroundTexture , mEngine.getVertexBufferObjectManager()); ITextureRegion waveSprite = resourceManager.getLoadedTextureRegion(R.drawable.wave); Sprite waveImage = new Sprite( 0 , backgroundTexture.getHeight() / WAVES_NUMBER , waveSprite , mEngine.getVertexBufferObjectManager()); this.getChildByIndex(LAYER_BACKGROUND).attachChild(backgroundSprite); this.getChildByIndex(LAYER_FIRST_WAVE).attachChild(waveImage); Color backgroundColor = new Color(0.09804f, 0.6274f, 0.8784f); this.setBackground(new Background(backgroundColor)); }
private void createBackground() { for(int i = 0; i < layerCount; i++) { this.attachChild(new Entity()); } ITextureRegion backgroundTexture = resourceManager.getLoadedTextureRegion(R.drawable.gamebackground); Sprite backgroundSprite = new Sprite( 0 , 0 , backgroundTexture , mEngine.getVertexBufferObjectManager()); ITextureRegion waveTexture = resourceManager.getLoadedTextureRegion(R.drawable.wave); Sprite waveSprite = new Sprite( 0 , backgroundTexture.getHeight() / WAVES_NUMBER , waveTexture , mEngine.getVertexBufferObjectManager()); this.getChildByIndex(LAYER_BACKGROUND).attachChild(backgroundSprite); this.getChildByIndex(LAYER_FIRST_WAVE).attachChild(waveSprite); Color backgroundColor = new Color(0.09804f, 0.6274f, 0.8784f); this.setBackground(new Background(backgroundColor)); }
diff --git a/src/ca/eandb/jmist/framework/material/ModifiedPhongMaterial.java b/src/ca/eandb/jmist/framework/material/ModifiedPhongMaterial.java index 7e6528d1..e75d3ece 100644 --- a/src/ca/eandb/jmist/framework/material/ModifiedPhongMaterial.java +++ b/src/ca/eandb/jmist/framework/material/ModifiedPhongMaterial.java @@ -1,163 +1,161 @@ /** * */ package ca.eandb.jmist.framework.material; import ca.eandb.jmist.framework.Painter; import ca.eandb.jmist.framework.ScatteredRay; import ca.eandb.jmist.framework.SurfacePoint; import ca.eandb.jmist.framework.color.Color; import ca.eandb.jmist.framework.color.ColorUtil; import ca.eandb.jmist.framework.color.Spectrum; import ca.eandb.jmist.framework.color.WavelengthPacket; import ca.eandb.jmist.framework.painter.UniformPainter; import ca.eandb.jmist.framework.random.RandomUtil; import ca.eandb.jmist.math.Basis3; import ca.eandb.jmist.math.Optics; import ca.eandb.jmist.math.Ray3; import ca.eandb.jmist.math.SphericalCoordinates; import ca.eandb.jmist.math.Vector3; /** * A <code>Material</code> based on the modified Phong BRDF. Implementation as * described in: * * E.P. Lafortune and Y.D. Willems, "Using the Modified Phong Reflectance Model * for Physically Based Rendering", Technical Report CW 197, Department of * Computing Science, K.U. Leuven. November 1994. * * @author Brad Kimmel */ public final class ModifiedPhongMaterial extends OpaqueMaterial { /** Serialization version ID. */ private static final long serialVersionUID = 3049341531935254708L; /** The <code>Painter</code> to use to assign the diffuse reflectance. */ private final Painter kdPainter; /** The <code>Painter</code> to use to assign the specular reflectance. */ private final Painter ksPainter; /** The sharpness of the specular reflectance lobe. */ private final double n; /** * Creates a new <code>ModifiedPhongMaterial</code>. * @param kd The <code>Painter</code> to use to assign the diffuse * reflectance. * @param ks The <code>Painter</code> to use to assign the specular * reflectance. * @param n The sharpness of the specular reflectance lobe. */ public ModifiedPhongMaterial(Painter kd, Painter ks, double n) { this.kdPainter = kd; this.ksPainter = ks; this.n = n; } /** * Creates a new <code>ModifiedPhongMaterial</code>. * @param kd The diffuse reflectance <code>Spectrum</code>. * @param ks The specular reflectance <code>Spectrum</code>. * @param n The sharpness of the specular reflectance lobe. */ public ModifiedPhongMaterial(Spectrum kd, Spectrum ks, double n) { this(new UniformPainter(kd), new UniformPainter(ks), n); } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#bsdf(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public Color bsdf(SurfacePoint x, Vector3 in, Vector3 out, WavelengthPacket lambda) { if ((in.dot(x.getNormal()) < 0.0) == (out.dot(x.getNormal()) > 0.0)) { Color kd = kdPainter.getColor(x, lambda); Color d = kd.divide(Math.PI); Vector3 r = Optics.reflect(in, x.getNormal()); double rdoto = r.dot(out); if (rdoto > 0.0) { Color ks = ksPainter.getColor(x, lambda); Color s = ks.times(((n + 2.0) / (2.0 * Math.PI)) * Math.pow(rdoto, n)); return d.plus(s); } else { return d; } } else { return lambda.getColorModel().getBlack(lambda); } } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#getScatteringPDF(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, ca.eandb.jmist.math.Vector3, boolean, ca.eandb.jmist.framework.color.WavelengthPacket) */ @Override public double getScatteringPDF(SurfacePoint x, Vector3 in, Vector3 out, boolean adjoint, WavelengthPacket lambda) { double vdotn = -in.dot(x.getNormal()); double odotn = out.dot(x.getNormal()); if ((vdotn > 0.0) != (odotn > 0.0)) { return 0.0; } Color kd = kdPainter.getColor(x, lambda); Color ks = ksPainter.getColor(x, lambda); double kdY = ColorUtil.getMeanChannelValue(kd); double rhod = kdY; double ksY = ColorUtil.getMeanChannelValue(ks); double rhos = Math.min(1.0, ksY * Math.abs(vdotn) * (n + 2.0) / (n + 1.0)); Vector3 r = Optics.reflect(in, x.getNormal()); double rdoto = r.dot(out); double pdfd = rhod / Math.PI; double pdfs = rdoto > 0.0 ? rhos * (Math.pow(rdoto, n) / Math.abs(odotn)) * (n + 1.0) / (2.0 * Math.PI) : 0.0; return pdfd + pdfs; } /* (non-Javadoc) * @see ca.eandb.jmist.framework.material.AbstractMaterial#scatter(ca.eandb.jmist.framework.SurfacePoint, ca.eandb.jmist.math.Vector3, boolean, ca.eandb.jmist.framework.color.WavelengthPacket, double, double, double) */ @Override public ScatteredRay scatter(SurfacePoint x, Vector3 v, boolean adjoint, WavelengthPacket lambda, double ru, double rv, double rj) { double vdotn = -v.dot(x.getNormal()); // if (vdotn < 0.0) { // return null; // } Color kd = kdPainter.getColor(x, lambda); Color ks = ksPainter.getColor(x, lambda); double kdY = ColorUtil.getMeanChannelValue(kd); double rhod = kdY; double ksY = ColorUtil.getMeanChannelValue(ks); double rhos = Math.min(1.0, ksY * Math.abs(vdotn) * (n + 2.0) / (n + 1.0)); if (rj < rhod) { Vector3 out = RandomUtil.diffuse(ru, rv).toCartesian(x.getBasis()); Ray3 ray = new Ray3(x.getPosition(), out); return ScatteredRay.diffuse(ray, kd.divide(rhod), getScatteringPDF(x, v, out, adjoint, lambda)); } else if (rj < rhod + rhos) { Vector3 r = Optics.reflect(v, x.getNormal()); Vector3 out = new SphericalCoordinates(Math.acos(Math.pow(ru, 1.0 / (n + 1.0))), 2.0 * Math.PI * rv).toCartesian(Basis3.fromW(r)); double ndoto = x.getNormal().dot(out); - if (ndoto > 0.0) { - Color weight = ks.times(((n + 2.0) / (n + 1.0)) * ndoto / rhos); - //double rdoto = r.dot(out); - double pdf = getScatteringPDF(x, v, out, adjoint, lambda);//rhod / Math.PI + rhos * (Math.pow(rdoto, n) / ndoto) * (n + 1.0) / (2.0 * Math.PI); - Ray3 ray = new Ray3(x.getPosition(), out); - return ScatteredRay.glossy(ray, weight, pdf); - } + Color weight = ks.times(((n + 2.0) / (n + 1.0)) * Math.abs(ndoto) / rhos); + //double rdoto = r.dot(out); + double pdf = getScatteringPDF(x, v, out, adjoint, lambda);//rhod / Math.PI + rhos * (Math.pow(rdoto, n) / ndoto) * (n + 1.0) / (2.0 * Math.PI); + Ray3 ray = new Ray3(x.getPosition(), out); + return ScatteredRay.glossy(ray, weight, pdf); } return null; } }
true
true
public ScatteredRay scatter(SurfacePoint x, Vector3 v, boolean adjoint, WavelengthPacket lambda, double ru, double rv, double rj) { double vdotn = -v.dot(x.getNormal()); // if (vdotn < 0.0) { // return null; // } Color kd = kdPainter.getColor(x, lambda); Color ks = ksPainter.getColor(x, lambda); double kdY = ColorUtil.getMeanChannelValue(kd); double rhod = kdY; double ksY = ColorUtil.getMeanChannelValue(ks); double rhos = Math.min(1.0, ksY * Math.abs(vdotn) * (n + 2.0) / (n + 1.0)); if (rj < rhod) { Vector3 out = RandomUtil.diffuse(ru, rv).toCartesian(x.getBasis()); Ray3 ray = new Ray3(x.getPosition(), out); return ScatteredRay.diffuse(ray, kd.divide(rhod), getScatteringPDF(x, v, out, adjoint, lambda)); } else if (rj < rhod + rhos) { Vector3 r = Optics.reflect(v, x.getNormal()); Vector3 out = new SphericalCoordinates(Math.acos(Math.pow(ru, 1.0 / (n + 1.0))), 2.0 * Math.PI * rv).toCartesian(Basis3.fromW(r)); double ndoto = x.getNormal().dot(out); if (ndoto > 0.0) { Color weight = ks.times(((n + 2.0) / (n + 1.0)) * ndoto / rhos); //double rdoto = r.dot(out); double pdf = getScatteringPDF(x, v, out, adjoint, lambda);//rhod / Math.PI + rhos * (Math.pow(rdoto, n) / ndoto) * (n + 1.0) / (2.0 * Math.PI); Ray3 ray = new Ray3(x.getPosition(), out); return ScatteredRay.glossy(ray, weight, pdf); } } return null; }
public ScatteredRay scatter(SurfacePoint x, Vector3 v, boolean adjoint, WavelengthPacket lambda, double ru, double rv, double rj) { double vdotn = -v.dot(x.getNormal()); // if (vdotn < 0.0) { // return null; // } Color kd = kdPainter.getColor(x, lambda); Color ks = ksPainter.getColor(x, lambda); double kdY = ColorUtil.getMeanChannelValue(kd); double rhod = kdY; double ksY = ColorUtil.getMeanChannelValue(ks); double rhos = Math.min(1.0, ksY * Math.abs(vdotn) * (n + 2.0) / (n + 1.0)); if (rj < rhod) { Vector3 out = RandomUtil.diffuse(ru, rv).toCartesian(x.getBasis()); Ray3 ray = new Ray3(x.getPosition(), out); return ScatteredRay.diffuse(ray, kd.divide(rhod), getScatteringPDF(x, v, out, adjoint, lambda)); } else if (rj < rhod + rhos) { Vector3 r = Optics.reflect(v, x.getNormal()); Vector3 out = new SphericalCoordinates(Math.acos(Math.pow(ru, 1.0 / (n + 1.0))), 2.0 * Math.PI * rv).toCartesian(Basis3.fromW(r)); double ndoto = x.getNormal().dot(out); Color weight = ks.times(((n + 2.0) / (n + 1.0)) * Math.abs(ndoto) / rhos); //double rdoto = r.dot(out); double pdf = getScatteringPDF(x, v, out, adjoint, lambda);//rhod / Math.PI + rhos * (Math.pow(rdoto, n) / ndoto) * (n + 1.0) / (2.0 * Math.PI); Ray3 ray = new Ray3(x.getPosition(), out); return ScatteredRay.glossy(ray, weight, pdf); } return null; }
diff --git a/java/coalitiongamesjava/coalitiongames/MaxSocialWelfareAllocation.java b/java/coalitiongamesjava/coalitiongames/MaxSocialWelfareAllocation.java index 65fb2b1..4793402 100644 --- a/java/coalitiongamesjava/coalitiongames/MaxSocialWelfareAllocation.java +++ b/java/coalitiongamesjava/coalitiongames/MaxSocialWelfareAllocation.java @@ -1,638 +1,638 @@ package coalitiongames; import ilog.concert.IloException; import ilog.concert.IloIntVar; import ilog.concert.IloLinearIntExpr; import ilog.cplex.IloCplex; import java.util.ArrayList; import java.util.Date; import java.util.List; public abstract class MaxSocialWelfareAllocation { public static final double AGENT_UTILITY_BUDGET = 100.0; public static enum ProblemType { EASY, HARD, HARD_REGRET } public static SimpleSearchResult maxSocialWelfareAllocation( final List<Agent> agents, final int kMax, final List<Integer> rsdOrder, final ProblemType problemType ) { final int minimumAgents = 4; assert agents != null && agents.size() >= minimumAgents; final int n = agents.size(); assert kMax <= n; if (!verifyUtilityBudgets(agents)) { throw new IllegalArgumentException("incorrect utility budgets"); } final List<Integer> teamSizes = RsdUtil.getOptimalTeamSizeList(agents.size(), kMax); assert teamSizes.get(0) >= teamSizes.get(teamSizes.size() - 1); final int kMin = teamSizes.get(teamSizes.size() - 1); // time the duration of the search to the millisecond final long searchStartMillis = new Date().getTime(); /* final List<Integer> optimalTeamSizes = RsdUtil.getOptimalTeamSizeList(n, kMax); final MipResult mipResult = runMaxWelfareCPLEXFast( agents, optimalTeamSizes, kMin, kMax ); */ final MipResult mipResult = runMaxWelfareCPLEX( agents, kMax, kMin, problemType ); final List<Integer> roundedValues = mipResult.getRoundedColumnValues(); final List<List<Integer>> allocation = matrixFromList(roundedValues); final long searchDurationMillis = new Date().getTime() - searchStartMillis; final double similarity = PreferenceAnalyzer.getMeanPairwiseCosineSimilarity(agents); final List<Integer> captainIndexes = new ArrayList<Integer>(); return new SimpleSearchResult( allocation, kMin, kMax, agents, rsdOrder, searchDurationMillis, captainIndexes, similarity ); } public static List<Double> normalizeUtility(final List<Double> oldUtility) { double totalUtility = 0.0; for (Double value: oldUtility) { totalUtility += value; } if (totalUtility <= 0.0) { return new ArrayList<Double>(oldUtility); } final double factor = AGENT_UTILITY_BUDGET / totalUtility; final List<Double> result = new ArrayList<Double>(); for (Double value: oldUtility) { result.add(factor * value); } return result; } private static boolean verifyUtilityBudgets(final List<Agent> agents) { final double tolerance = 0.001; for (Agent agent: agents) { double totalUtility = 0.0; final List<Double> utilities = agent.getValues(); for (Double value: utilities) { totalUtility += value; } if (Math.abs(totalUtility - AGENT_UTILITY_BUDGET) > tolerance) { return false; } } return true; } /* * Returns a list of lists, where the ith list shows the additive * separable values from agent i for the other agents, with a 0.0 * inserted in the ith position. */ private static List<List<Double>> valueMatrix(final List<Agent> agents) { final List<List<Double>> result = new ArrayList<List<Double>>(); for (int i = 0; i < agents.size(); i++) { final Agent agent = agents.get(i); final List<Double> values = new ArrayList<Double>(agent.getValues()); values.add(i, 0.0); result.add(values); } if (MipGenerator.DEBUGGING) { for (int i = 0; i < agents.size(); i++) { if (result.get(i).get(i) != 0.0) { throw new IllegalStateException(); } if (result.get(i).size() != agents.size()) { throw new IllegalStateException(); } } } return result; } private static List<Double> listFromMatrix( final List<List<Double>> matrix ) { final List<Double> result = new ArrayList<Double>(); for (List<Double> row: matrix) { result.addAll(row); } return result; } private static List<List<Integer>> matrixFromList( final List<Integer> list ) { final List<List<Integer>> result = new ArrayList<List<Integer>>(); final int colSize = (int) Math.sqrt(list.size()); if (colSize * colSize != list.size()) { throw new IllegalArgumentException("not a square matrix list"); } for (int i = 0; i < colSize; i++) { final List<Integer> current = new ArrayList<Integer>(); for (int j = colSize * i; j < colSize * (i + 1); j++) { current.add(list.get(j)); } assert current.size() == colSize; result.add(current); } assert result.size() == colSize; return result; } /** * * @param matrixWidth 1-based. 1 is minimum * @param row 0-based, so top row is row 0 * @param col 0-based, so left column is column 0 * @return */ private static int listIndex( final int matrixWidth, final int row, final int col ) { return row * matrixWidth + col; } /* * n = number of agents * t = number teams * search over {0, 1}^(T*N) matrices * sum over rows = 1, for each column * sum over columns = teamSize(rowIndex), for each row, * which must be in [kMin, kMax] * * objective: maximize social welfare * welfare = Sum agents i: Sum other agents j: u_ij * together_ij * x in {0, 1}^t*n * s in {0, 1}^t*n*n * together in {0, 1}^n*n * * s_tij = 1 if i, j are both on team t, else 0 * s_tij <= (1/2) x_ti + (1/2) x_tj, for all t, i, j * s_tij >= x_ti + x_tj - 1, for all t, i, j * sum i: x_ti >= kMin, for all t * sum i: x_ti <= kMax, for all t * sum t: x_ti = 1, for all i * * together_ij = 1 if i, j are on same team, else 0 * together_ij = Sum rows t: s_tij, for all t, i, j * */ @SuppressWarnings("unused") private static MipResult runMaxWelfareCPLEXFast( final List<Agent> agents, final List<Integer> teamSizes, final int kMin, final int kMax ) { final int n = agents.size(); final int t = teamSizes.size(); final List<List<Double>> objectives = valueMatrix(agents); final List<Double> objectiveArgs = listFromMatrix(objectives); if (objectiveArgs.size() != n * n) { throw new IllegalStateException(); } try { final IloCplex lp = new IloCplex(); // set these parameters if memory is a concern lp.setParam(IloCplex.IntParam.Threads, 2); final double sizeInMb = 600.0; lp.setParam(IloCplex.DoubleParam.WorkMem, sizeInMb); final double gapAbsoluteTolerance = 0.4; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); final double gapRelativeTolerance = 0.01; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); lp.setOut(null); // x in {0, 1}^t*n int[] xLowerBounds = new int[t * n]; int[] xUpperBounds = new int[t * n]; for (int i = 0; i < t * n; i++) { xLowerBounds[i] = 0; xUpperBounds[i] = 1; } IloIntVar[] x = lp.intVarArray( t * n, xLowerBounds, xUpperBounds ); // s in {0, 1}^T*N*N int[] sLowerBounds = new int[t * n * n]; int[] sUpperBounds = new int[t * n * n]; for (int i = 0; i < t * n * n; i++) { sLowerBounds[i] = 0; sUpperBounds[i] = 1; } IloIntVar[] s = lp.intVarArray( t * n * n, sLowerBounds, sUpperBounds ); // together in {0, 1}^N*N int[] togetherLowerBounds = new int[n * n]; int[] togetherUpperBounds = new int[n * n]; for (int i = 0; i < n * n; i++) { togetherLowerBounds[i] = 0; togetherUpperBounds[i] = 1; } IloIntVar[] together = lp.intVarArray( n * n, togetherLowerBounds, togetherUpperBounds ); // sum i: x_ti >= kMin, for all t // sum i: x_ti <= kMax, for all t for (int team = 0; team < t; team++) { IloLinearIntExpr kMinConstraint = lp.linearIntExpr(); IloLinearIntExpr kMaxConstraint = lp.linearIntExpr(); for (int i = 0; i < n; i++) { final int xtiIndex = team * n + i; kMinConstraint.addTerm(1, x[xtiIndex]); kMaxConstraint.addTerm(1, x[xtiIndex]); } lp.addGe(kMinConstraint, kMin); lp.addLe(kMaxConstraint, kMax); } // sum t: x_ti = 1, for all i for (int i = 0; i < n; i++) { IloLinearIntExpr oneTeamConstraint = lp.linearIntExpr(); for (int team = 0; team < t; team++) { final int xtiIndex = team * n + i; oneTeamConstraint.addTerm(1, x[xtiIndex]); } lp.addEq(oneTeamConstraint, 1); } // together_ij = sum t: s_tij, for all i, j // sum t: s_tij - together_ij = 0, for all i, j for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { IloLinearIntExpr togetherConstraint = lp.linearIntExpr(); for (int team = 0; team < t; team++) { final int sTijIndex = team * n * n + i * n + j; togetherConstraint.addTerm(1, s[sTijIndex]); } final int togetherIjIndex = i * n + j; togetherConstraint.addTerm(-1, together[togetherIjIndex]); lp.addEq(togetherConstraint, 0); } } // s_tij <= (1/2) x_ti + (1/2) x_tj, for all t, i, j // x_ti + x_tj - 2 * s_tij >= 0, for all t, i, j // // s_tij >= x_ti + x_tj - 1, for all t, i, j // x_ti + x_tj - s_tij <= 1, for all t, i, j for (int team = 0; team < t; team++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { final int sTijIndex = team * n * n + i * n + j; final int xTiIndex = team * n + i; final int xTjIndex = team * n + j; IloLinearIntExpr upperConstraint = lp.linearIntExpr(); upperConstraint.addTerm(1, x[xTiIndex]); upperConstraint.addTerm(1, x[xTjIndex]); upperConstraint.addTerm(-2, s[sTijIndex]); lp.addGe(upperConstraint, 0); IloLinearIntExpr lowerConstraint = lp.linearIntExpr(); lowerConstraint.addTerm(1, x[xTiIndex]); lowerConstraint.addTerm(1, x[xTjIndex]); lowerConstraint.addTerm(-1, s[sTijIndex]); lp.addLe(lowerConstraint, 1); } } } // maximize welfare. // welfare = Sum agents i: Sum other agents j: u_ij * together_ij double [] u = new double[n * n]; for (int i = 0; i < n * n; i++) { u[i] = objectiveArgs.get(i); } lp.addMaximize( lp.scalProd(together, u) ); if (lp.solve()) { final double[] columnValuesArr = lp.getValues(x); final List<Double> columnValues = getColumnValues(columnValuesArr, n, t); final double objectiveValue = lp.getObjValue(); final MipResult result = new MipResult( "obj", objectiveValue, columnValues, true ); lp.end(); return result; } } catch (IloException e) { e.printStackTrace(); } return null; } /* * resultArr should be in format {0, 1}^teamCount*agentCount. * resultArr[t * agentCount + i] = 1 if agent i is on team t. */ private static List<Double> getColumnValues( final double[] resultArr, final int agentCount, final int teamCount ) { if (resultArr.length != agentCount * teamCount) { throw new IllegalArgumentException(); } final List<Double> result = new ArrayList<Double>(); for (int i = 0; i < agentCount; i++) { for (int j = 0; j < agentCount; j++) { boolean sameTeam = false; for (int team = 0; team < teamCount; team++) { final int iIndex = team * agentCount + i; final int jIndex = team * agentCount + j; if (resultArr[iIndex] == 1 && resultArr[jIndex] == 1) { sameTeam = true; } } if (sameTeam) { result.add(1.0); } else { result.add(0.0); } } } return result; } /* * Tolerances that worked for 17 agents, kMax = 5: * gapAbsoluteTolerance = 5.0 * gapRelativeTolerance = 0.2 * times: 52, 300+, 26, 175, 28, 17 * * gapAbsoluteTolerance = 5.0 * gapRelativeTolerance = 0.15 * times: DNF, DNF, etc. * * for 20 runs: * timeout 10' -> 200' (3.5 hours) * timeout 20' -> 400' (7 hours) * * for regret of truthful reporting 20: 20 * 25 * 8 = 4000 runs * timeout 1' -> 2.8 days * * for regret of truthful reporting 17: 17 * 25 * 8 = 3400 runs * timeout 1' -> 2.4 days * * for regret of truthful reporting 32: 32 * 25 * 8 - 6400 runs * timeout 1' -> 4.5 days * * decision: * for regret, use: * EpAGap = 5.0 * EpGap = 0.2 * TiLim = 60.0 * -> 2.8-4.5 days per run * * for other than regret, use: * EpAGap = 5.0 * EpGap = 0.15 * TiLim = 600.0 * -> 3.5 hours per run */ private static MipResult runMaxWelfareCPLEX( final List<Agent> agents, final int kMax, final int kMin, final ProblemType problemType ) { final List<List<Double>> valueMatrix = valueMatrix(agents); final List<Double> objectiveArgs = listFromMatrix(valueMatrix); final int rowLength = objectiveArgs.size(); final int agentCount = agents.size(); try { final IloCplex lp = new IloCplex(); // set these parameters if memory is a concern lp.setParam(IloCplex.IntParam.Threads, 2); final double sizeInMb = 600.0; lp.setParam(IloCplex.DoubleParam.WorkMem, sizeInMb); switch (problemType) { case EASY: double gapAbsoluteTolerance = 0.4; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); double gapRelativeTolerance = 0.01; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); break; case HARD: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); double timeLimit = 600.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; case HARD_REGRET: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); timeLimit = 60.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; default: throw new IllegalStateException(); } lp.setOut(null); // all values in {0, 1} int[] xLowerBounds = new int[rowLength]; int[] xUpperBounds = new int[rowLength]; for (int i = 0; i < rowLength; i++) { xLowerBounds[i] = 0; xUpperBounds[i] = 1; } IloIntVar[] x = lp.intVarArray( rowLength, xLowerBounds, xUpperBounds ); // each agent must choose itself, // so x_ii must equal 1, for all i. // 1 * x_ii = 1 for (int i = 0; i < agentCount; i++) { IloLinearIntExpr chooseSelfConstraint = lp.linearIntExpr(); final int selfSelfIndex = listIndex(agentCount, i, i); chooseSelfConstraint.addTerm(1, x[selfSelfIndex]); lp.addEq(chooseSelfConstraint, 1); } // if i chooses j, j must choose i. // so x_ij = x_ji for all i, j. // 1 * x_ij - 1 * x_ji = 0 for (int i = 0; i < agentCount; i++) { for (int j = i + 1; j < agentCount; j++) { IloLinearIntExpr symmetryConstraint = lp.linearIntExpr(); final int ijIndex = listIndex(agentCount, i, j); final int jiIndex = listIndex(agentCount, j, i); symmetryConstraint.addTerm(1, x[ijIndex]); symmetryConstraint.addTerm(-1, x[jiIndex]); lp.addEq(symmetryConstraint, 0); } } // for any pair of rows, either they must have no 1's in the same // columns, or all 1's in all columns must match. // for any row after the top row, and any pair of columns, the // sum of the values in the first column plus the difference in // values in the second column must be <= 2. // this prevents there from being matching 1's in some column // for different rows, where those rows have mismatches 1's in // another column, which would lead to a total of 3. // x_ij + x_i'j + x_ij' - x_i'j' <= 2, for all i, i' > i, j, j' != j // x_ij + x_i'j - x_ij' + x_i'j' <= 2, for all i, i' > i, j, j' != j for (int rowUpper = 0; rowUpper < agentCount - 1; rowUpper++) { for ( int rowLower = rowUpper + 1; rowLower < agentCount; rowLower++ ) { - for (int i = 0; i < agentCount - 1; i++) { + for (int i = 0; i < agentCount; i++) { for (int j = 0; j < agentCount; j++) { if (i == j) { continue; } final int upperIIndex = listIndex(agentCount, rowUpper, i); final int upperJIndex = listIndex(agentCount, rowUpper, j); final int lowerIIndex = listIndex(agentCount, rowLower, i); final int lowerJIndex = listIndex(agentCount, rowLower, j); final IloLinearIntExpr plusConstraint = lp.linearIntExpr(); plusConstraint.addTerm(1, x[lowerIIndex]); plusConstraint.addTerm(1, x[lowerJIndex]); plusConstraint.addTerm(1, x[upperIIndex]); plusConstraint.addTerm(-1, x[upperJIndex]); lp.addLe(plusConstraint, 2); final IloLinearIntExpr minusConstraint = lp.linearIntExpr(); minusConstraint.addTerm(1, x[lowerIIndex]); minusConstraint.addTerm(1, x[lowerJIndex]); minusConstraint.addTerm(-1, x[upperIIndex]); minusConstraint.addTerm(1, x[upperJIndex]); lp.addLe(minusConstraint, 2); } } } } // total agents on each team is at least kMin. // so Sum over j: x_ij >= kMin, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMinConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMinConstraint.addTerm(1, x[ijIndex]); } lp.addGe(kMinConstraint, kMin); } // total agents on each team is no more than kMax. // so Sum over j: x_ij <= kMax, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMaxConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMaxConstraint.addTerm(1, x[ijIndex]); } lp.addLe(kMaxConstraint, kMax); } // maximize the total value of the bundle double [] objectiveValues = new double[rowLength]; for (int i = 0; i < rowLength; i++) { objectiveValues[i] = objectiveArgs.get(i); } lp.addMaximize( lp.scalProd(x, objectiveValues) ); if (lp.solve()) { final double[] columnValuesArr = lp.getValues(x); final List<Double> columnValues = new ArrayList<Double>(); for (int i = 0; i < columnValuesArr.length; i++) { columnValues.add(columnValuesArr[i]); } final double objectiveValue = lp.getObjValue(); final MipResult result = new MipResult( "obj", objectiveValue, columnValues, true ); lp.end(); return result; } } catch (IloException e) { e.printStackTrace(); } return null; } }
true
true
private static MipResult runMaxWelfareCPLEX( final List<Agent> agents, final int kMax, final int kMin, final ProblemType problemType ) { final List<List<Double>> valueMatrix = valueMatrix(agents); final List<Double> objectiveArgs = listFromMatrix(valueMatrix); final int rowLength = objectiveArgs.size(); final int agentCount = agents.size(); try { final IloCplex lp = new IloCplex(); // set these parameters if memory is a concern lp.setParam(IloCplex.IntParam.Threads, 2); final double sizeInMb = 600.0; lp.setParam(IloCplex.DoubleParam.WorkMem, sizeInMb); switch (problemType) { case EASY: double gapAbsoluteTolerance = 0.4; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); double gapRelativeTolerance = 0.01; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); break; case HARD: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); double timeLimit = 600.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; case HARD_REGRET: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); timeLimit = 60.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; default: throw new IllegalStateException(); } lp.setOut(null); // all values in {0, 1} int[] xLowerBounds = new int[rowLength]; int[] xUpperBounds = new int[rowLength]; for (int i = 0; i < rowLength; i++) { xLowerBounds[i] = 0; xUpperBounds[i] = 1; } IloIntVar[] x = lp.intVarArray( rowLength, xLowerBounds, xUpperBounds ); // each agent must choose itself, // so x_ii must equal 1, for all i. // 1 * x_ii = 1 for (int i = 0; i < agentCount; i++) { IloLinearIntExpr chooseSelfConstraint = lp.linearIntExpr(); final int selfSelfIndex = listIndex(agentCount, i, i); chooseSelfConstraint.addTerm(1, x[selfSelfIndex]); lp.addEq(chooseSelfConstraint, 1); } // if i chooses j, j must choose i. // so x_ij = x_ji for all i, j. // 1 * x_ij - 1 * x_ji = 0 for (int i = 0; i < agentCount; i++) { for (int j = i + 1; j < agentCount; j++) { IloLinearIntExpr symmetryConstraint = lp.linearIntExpr(); final int ijIndex = listIndex(agentCount, i, j); final int jiIndex = listIndex(agentCount, j, i); symmetryConstraint.addTerm(1, x[ijIndex]); symmetryConstraint.addTerm(-1, x[jiIndex]); lp.addEq(symmetryConstraint, 0); } } // for any pair of rows, either they must have no 1's in the same // columns, or all 1's in all columns must match. // for any row after the top row, and any pair of columns, the // sum of the values in the first column plus the difference in // values in the second column must be <= 2. // this prevents there from being matching 1's in some column // for different rows, where those rows have mismatches 1's in // another column, which would lead to a total of 3. // x_ij + x_i'j + x_ij' - x_i'j' <= 2, for all i, i' > i, j, j' != j // x_ij + x_i'j - x_ij' + x_i'j' <= 2, for all i, i' > i, j, j' != j for (int rowUpper = 0; rowUpper < agentCount - 1; rowUpper++) { for ( int rowLower = rowUpper + 1; rowLower < agentCount; rowLower++ ) { for (int i = 0; i < agentCount - 1; i++) { for (int j = 0; j < agentCount; j++) { if (i == j) { continue; } final int upperIIndex = listIndex(agentCount, rowUpper, i); final int upperJIndex = listIndex(agentCount, rowUpper, j); final int lowerIIndex = listIndex(agentCount, rowLower, i); final int lowerJIndex = listIndex(agentCount, rowLower, j); final IloLinearIntExpr plusConstraint = lp.linearIntExpr(); plusConstraint.addTerm(1, x[lowerIIndex]); plusConstraint.addTerm(1, x[lowerJIndex]); plusConstraint.addTerm(1, x[upperIIndex]); plusConstraint.addTerm(-1, x[upperJIndex]); lp.addLe(plusConstraint, 2); final IloLinearIntExpr minusConstraint = lp.linearIntExpr(); minusConstraint.addTerm(1, x[lowerIIndex]); minusConstraint.addTerm(1, x[lowerJIndex]); minusConstraint.addTerm(-1, x[upperIIndex]); minusConstraint.addTerm(1, x[upperJIndex]); lp.addLe(minusConstraint, 2); } } } } // total agents on each team is at least kMin. // so Sum over j: x_ij >= kMin, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMinConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMinConstraint.addTerm(1, x[ijIndex]); } lp.addGe(kMinConstraint, kMin); } // total agents on each team is no more than kMax. // so Sum over j: x_ij <= kMax, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMaxConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMaxConstraint.addTerm(1, x[ijIndex]); } lp.addLe(kMaxConstraint, kMax); } // maximize the total value of the bundle double [] objectiveValues = new double[rowLength]; for (int i = 0; i < rowLength; i++) { objectiveValues[i] = objectiveArgs.get(i); } lp.addMaximize( lp.scalProd(x, objectiveValues) ); if (lp.solve()) { final double[] columnValuesArr = lp.getValues(x); final List<Double> columnValues = new ArrayList<Double>(); for (int i = 0; i < columnValuesArr.length; i++) { columnValues.add(columnValuesArr[i]); } final double objectiveValue = lp.getObjValue(); final MipResult result = new MipResult( "obj", objectiveValue, columnValues, true ); lp.end(); return result; } } catch (IloException e) { e.printStackTrace(); } return null; }
private static MipResult runMaxWelfareCPLEX( final List<Agent> agents, final int kMax, final int kMin, final ProblemType problemType ) { final List<List<Double>> valueMatrix = valueMatrix(agents); final List<Double> objectiveArgs = listFromMatrix(valueMatrix); final int rowLength = objectiveArgs.size(); final int agentCount = agents.size(); try { final IloCplex lp = new IloCplex(); // set these parameters if memory is a concern lp.setParam(IloCplex.IntParam.Threads, 2); final double sizeInMb = 600.0; lp.setParam(IloCplex.DoubleParam.WorkMem, sizeInMb); switch (problemType) { case EASY: double gapAbsoluteTolerance = 0.4; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); double gapRelativeTolerance = 0.01; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); break; case HARD: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); double timeLimit = 600.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; case HARD_REGRET: gapAbsoluteTolerance = 5.0; lp.setParam(IloCplex.DoubleParam.EpAGap, gapAbsoluteTolerance); gapRelativeTolerance = 0.1; lp.setParam(IloCplex.DoubleParam.EpGap, gapRelativeTolerance); timeLimit = 60.0; lp.setParam(IloCplex.DoubleParam.TiLim, timeLimit); break; default: throw new IllegalStateException(); } lp.setOut(null); // all values in {0, 1} int[] xLowerBounds = new int[rowLength]; int[] xUpperBounds = new int[rowLength]; for (int i = 0; i < rowLength; i++) { xLowerBounds[i] = 0; xUpperBounds[i] = 1; } IloIntVar[] x = lp.intVarArray( rowLength, xLowerBounds, xUpperBounds ); // each agent must choose itself, // so x_ii must equal 1, for all i. // 1 * x_ii = 1 for (int i = 0; i < agentCount; i++) { IloLinearIntExpr chooseSelfConstraint = lp.linearIntExpr(); final int selfSelfIndex = listIndex(agentCount, i, i); chooseSelfConstraint.addTerm(1, x[selfSelfIndex]); lp.addEq(chooseSelfConstraint, 1); } // if i chooses j, j must choose i. // so x_ij = x_ji for all i, j. // 1 * x_ij - 1 * x_ji = 0 for (int i = 0; i < agentCount; i++) { for (int j = i + 1; j < agentCount; j++) { IloLinearIntExpr symmetryConstraint = lp.linearIntExpr(); final int ijIndex = listIndex(agentCount, i, j); final int jiIndex = listIndex(agentCount, j, i); symmetryConstraint.addTerm(1, x[ijIndex]); symmetryConstraint.addTerm(-1, x[jiIndex]); lp.addEq(symmetryConstraint, 0); } } // for any pair of rows, either they must have no 1's in the same // columns, or all 1's in all columns must match. // for any row after the top row, and any pair of columns, the // sum of the values in the first column plus the difference in // values in the second column must be <= 2. // this prevents there from being matching 1's in some column // for different rows, where those rows have mismatches 1's in // another column, which would lead to a total of 3. // x_ij + x_i'j + x_ij' - x_i'j' <= 2, for all i, i' > i, j, j' != j // x_ij + x_i'j - x_ij' + x_i'j' <= 2, for all i, i' > i, j, j' != j for (int rowUpper = 0; rowUpper < agentCount - 1; rowUpper++) { for ( int rowLower = rowUpper + 1; rowLower < agentCount; rowLower++ ) { for (int i = 0; i < agentCount; i++) { for (int j = 0; j < agentCount; j++) { if (i == j) { continue; } final int upperIIndex = listIndex(agentCount, rowUpper, i); final int upperJIndex = listIndex(agentCount, rowUpper, j); final int lowerIIndex = listIndex(agentCount, rowLower, i); final int lowerJIndex = listIndex(agentCount, rowLower, j); final IloLinearIntExpr plusConstraint = lp.linearIntExpr(); plusConstraint.addTerm(1, x[lowerIIndex]); plusConstraint.addTerm(1, x[lowerJIndex]); plusConstraint.addTerm(1, x[upperIIndex]); plusConstraint.addTerm(-1, x[upperJIndex]); lp.addLe(plusConstraint, 2); final IloLinearIntExpr minusConstraint = lp.linearIntExpr(); minusConstraint.addTerm(1, x[lowerIIndex]); minusConstraint.addTerm(1, x[lowerJIndex]); minusConstraint.addTerm(-1, x[upperIIndex]); minusConstraint.addTerm(1, x[upperJIndex]); lp.addLe(minusConstraint, 2); } } } } // total agents on each team is at least kMin. // so Sum over j: x_ij >= kMin, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMinConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMinConstraint.addTerm(1, x[ijIndex]); } lp.addGe(kMinConstraint, kMin); } // total agents on each team is no more than kMax. // so Sum over j: x_ij <= kMax, for all i for (int i = 0; i < agentCount; i++) { IloLinearIntExpr kMaxConstraint = lp.linearIntExpr(); for (int j = 0; j < agentCount; j++) { final int ijIndex = listIndex(agentCount, i, j); kMaxConstraint.addTerm(1, x[ijIndex]); } lp.addLe(kMaxConstraint, kMax); } // maximize the total value of the bundle double [] objectiveValues = new double[rowLength]; for (int i = 0; i < rowLength; i++) { objectiveValues[i] = objectiveArgs.get(i); } lp.addMaximize( lp.scalProd(x, objectiveValues) ); if (lp.solve()) { final double[] columnValuesArr = lp.getValues(x); final List<Double> columnValues = new ArrayList<Double>(); for (int i = 0; i < columnValuesArr.length; i++) { columnValues.add(columnValuesArr[i]); } final double objectiveValue = lp.getObjValue(); final MipResult result = new MipResult( "obj", objectiveValue, columnValues, true ); lp.end(); return result; } } catch (IloException e) { e.printStackTrace(); } return null; }
diff --git a/ItineRennes/src/fr/itinerennes/ui/activity/BookmarksActivity.java b/ItineRennes/src/fr/itinerennes/ui/activity/BookmarksActivity.java index 9efab17..03ebfba 100644 --- a/ItineRennes/src/fr/itinerennes/ui/activity/BookmarksActivity.java +++ b/ItineRennes/src/fr/itinerennes/ui/activity/BookmarksActivity.java @@ -1,126 +1,127 @@ package fr.itinerennes.ui.activity; import java.io.IOException; import java.util.List; import org.osmdroid.util.GeoPoint; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.Toast; import fr.itinerennes.ErrorCodeConstants; import fr.itinerennes.ItineRennesApplication; import fr.itinerennes.R; import fr.itinerennes.business.service.BookmarkService; import fr.itinerennes.database.Columns; import fr.itinerennes.exceptions.GenericException; import fr.itinerennes.model.Bookmark; import fr.itinerennes.ui.adapter.BookmarksAdapter; /** * This activity displays bookmarks items the user starred. * * @author Jérémie Huchet */ public class BookmarksActivity extends ItineRennesActivity { /** * Loads the bookmarks and display them in a list view. * <p> * {@inheritDoc} * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_bookmarks); final BookmarkService bookmarksService = getApplicationContext().getBookmarksService(); final List<Bookmark> allBookmarks = bookmarksService.getAllBookmarks(); // creates the list adapter final BookmarksAdapter favAdapter = new BookmarksAdapter(this, allBookmarks); // set up the list view final ListView list = (ListView) findViewById(R.id.bookmark_list); list.setAdapter(favAdapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final Bookmark bm = favAdapter.getItem(position); final String favType = bm.getType(); final String favId = bm.getId(); final String favLabel = bm.getLabel(); try { final GeoPoint location = findBookmarkLocation(favType, favId); final Intent i = new Intent(BookmarksActivity.this, MapActivity.class); + i.setAction(Intent.ACTION_VIEW); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_ID, favId); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_TYPE, favType); i.putExtra(MapActivity.INTENT_SET_MAP_ZOOM, 17); i.putExtra(MapActivity.INTENT_SET_MAP_LON, location.getLongitudeE6()); i.putExtra(MapActivity.INTENT_SET_MAP_LAT, location.getLatitudeE6()); BookmarksActivity.this.startActivity(i); } catch (final GenericException e) { // bookmark is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } catch (final IOException e) { // station is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } } }); } /** * Finds the location of a bookmark using the resource type and identifier. * * @param type * the type of the resource * @param id * the identifier of the resource * @return a geopoint * @throws GenericException * the bookmark may be not found * @throws IOException * station not found */ private GeoPoint findBookmarkLocation(final String type, final String id) throws GenericException, IOException { final ItineRennesApplication appCtx = getApplicationContext(); GeoPoint location = null; final Cursor c = appCtx.getMarkerDao().getMarker(id, type); if (c != null && c.moveToFirst()) { location = new GeoPoint(c.getInt(c.getColumnIndex(Columns.MarkersColumns.LATITUDE)), c.getInt(c.getColumnIndex(Columns.MarkersColumns.LONGITUDE))); c.close(); } if (location == null) { throw new GenericException(ErrorCodeConstants.BOOKMARK_NOT_FOUND, String.format( "bookmark location not found using type=%s and id=%s", type, id)); } return location; } }
true
true
protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_bookmarks); final BookmarkService bookmarksService = getApplicationContext().getBookmarksService(); final List<Bookmark> allBookmarks = bookmarksService.getAllBookmarks(); // creates the list adapter final BookmarksAdapter favAdapter = new BookmarksAdapter(this, allBookmarks); // set up the list view final ListView list = (ListView) findViewById(R.id.bookmark_list); list.setAdapter(favAdapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final Bookmark bm = favAdapter.getItem(position); final String favType = bm.getType(); final String favId = bm.getId(); final String favLabel = bm.getLabel(); try { final GeoPoint location = findBookmarkLocation(favType, favId); final Intent i = new Intent(BookmarksActivity.this, MapActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_ID, favId); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_TYPE, favType); i.putExtra(MapActivity.INTENT_SET_MAP_ZOOM, 17); i.putExtra(MapActivity.INTENT_SET_MAP_LON, location.getLongitudeE6()); i.putExtra(MapActivity.INTENT_SET_MAP_LAT, location.getLatitudeE6()); BookmarksActivity.this.startActivity(i); } catch (final GenericException e) { // bookmark is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } catch (final IOException e) { // station is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } } }); }
protected final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_bookmarks); final BookmarkService bookmarksService = getApplicationContext().getBookmarksService(); final List<Bookmark> allBookmarks = bookmarksService.getAllBookmarks(); // creates the list adapter final BookmarksAdapter favAdapter = new BookmarksAdapter(this, allBookmarks); // set up the list view final ListView list = (ListView) findViewById(R.id.bookmark_list); list.setAdapter(favAdapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final Bookmark bm = favAdapter.getItem(position); final String favType = bm.getType(); final String favId = bm.getId(); final String favLabel = bm.getLabel(); try { final GeoPoint location = findBookmarkLocation(favType, favId); final Intent i = new Intent(BookmarksActivity.this, MapActivity.class); i.setAction(Intent.ACTION_VIEW); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_ID, favId); i.putExtra(MapActivity.INTENT_SELECT_BOOKMARK_TYPE, favType); i.putExtra(MapActivity.INTENT_SET_MAP_ZOOM, 17); i.putExtra(MapActivity.INTENT_SET_MAP_LON, location.getLongitudeE6()); i.putExtra(MapActivity.INTENT_SET_MAP_LAT, location.getLatitudeE6()); BookmarksActivity.this.startActivity(i); } catch (final GenericException e) { // bookmark is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } catch (final IOException e) { // station is not found, remove it bookmarksService.setNotStarred(favType, favId); Toast.makeText(BookmarksActivity.this, getString(R.string.delete_bookmark_not_found, favLabel), 5000).show(); list.invalidate(); } } }); }
diff --git a/examples/kitchensink/src/main/java/app/config/RouteConfig.java b/examples/kitchensink/src/main/java/app/config/RouteConfig.java index 6671a56..ba4382f 100644 --- a/examples/kitchensink/src/main/java/app/config/RouteConfig.java +++ b/examples/kitchensink/src/main/java/app/config/RouteConfig.java @@ -1,20 +1,20 @@ package app.config; import app.controllers.HelloController; import app.controllers.HomeController; import app.controllers.PostsController; import app.controllers.RpostsController; import org.javalite.activeweb.AbstractRouteConfig; import org.javalite.activeweb.AppContext; /** * @author Igor Polevoy: 1/2/12 4:48 PM */ public class RouteConfig extends AbstractRouteConfig { public void init(AppContext appContext) { route("/myposts").to(PostsController.class); - route("/greeting1").to(HomeController.class); + route("/greeting/{action}/{name}").to(HelloController.class); route("/rposts_internal/{action}").to(RpostsController.class); route("/{action}/greeting/{name}").to(HelloController.class); } }
true
true
public void init(AppContext appContext) { route("/myposts").to(PostsController.class); route("/greeting1").to(HomeController.class); route("/rposts_internal/{action}").to(RpostsController.class); route("/{action}/greeting/{name}").to(HelloController.class); }
public void init(AppContext appContext) { route("/myposts").to(PostsController.class); route("/greeting/{action}/{name}").to(HelloController.class); route("/rposts_internal/{action}").to(RpostsController.class); route("/{action}/greeting/{name}").to(HelloController.class); }
diff --git a/src/test/java/org/glite/authz/pep/pip/provider/AbstractX509PIPTest.java b/src/test/java/org/glite/authz/pep/pip/provider/AbstractX509PIPTest.java index 3363523..7b139b8 100644 --- a/src/test/java/org/glite/authz/pep/pip/provider/AbstractX509PIPTest.java +++ b/src/test/java/org/glite/authz/pep/pip/provider/AbstractX509PIPTest.java @@ -1,148 +1,151 @@ /* * Copyright (c) Members of the EGEE Collaboration. 2011. * See http://www.eu-egee.org/partners/ for details on the copyright holders. * * 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. * * $Id$ */ package org.glite.authz.pep.pip.provider; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.TestCase; import org.glite.authz.common.model.Attribute; import org.glite.authz.common.model.Subject; import org.glite.authz.common.profile.AuthorizationProfileConstants; /** * AuthorizationProfilePIPTest * * @author Valery Tschopp &lt;valery.tschopp&#64;switch.ch&gt; */ public class AbstractX509PIPTest extends TestCase { Subject subject; String voName= "JUNIT_VO_NAME"; String wrongDN= "C=org,O=ACME,CN=John Doe"; String correctDN= "CN=John Doe,O=ACME,C=org"; List<String> wrongIssuers= Arrays.asList("C=org,O=ACME,OU=Issuing CA,CN=ACME Issuing CA", "C=org,O=ACME,OU=Root CA,CN=ACME CA"); List<String> correctIssuers= Arrays.asList("CN=ACME Issuing CA,OU=Issuing CA,O=ACME,C=org", "CN=ACME CA,OU=Root CA,O=ACME,C=org"); /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); subject= new Subject(); Attribute subjectId= new Attribute(Attribute.ID_SUB_ID, Attribute.DT_X500_NAME); subjectId.getValues().add(wrongDN); subject.getAttributes().add(subjectId); Attribute subjectIssuer= new Attribute(AuthorizationProfileConstants.ID_ATTRIBUTE_SUBJECT_ISSUER, Attribute.DT_X500_NAME); subjectIssuer.getValues().addAll(wrongIssuers); subject.getAttributes().add(subjectIssuer); } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } public void testUpdateSubjectCertificateAttributes() { Collection<Attribute> certAttributes= processCertChain(); System.out.println("Incoming Subject: " + subject); updateSubjectCertificateAttributes(subject, certAttributes); + boolean voNamePresent= false; for (Attribute attribute : subject.getAttributes()) { if (attribute.getId().equals(Attribute.ID_SUB_ID)) { for (Object object : attribute.getValues()) { String value= (String) object; assertEquals(correctDN, value); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_SUBJECT_ISSUER)) { for (Object object : attribute.getValues()) { assertTrue(correctIssuers.contains(object)); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_VIRTUAL_ORGANIZATION)) { for (Object object : attribute.getValues()) { assertEquals(voName, object.toString()); + voNamePresent= true; } } } + assertTrue("missing vo attribute",voNamePresent); System.out.println("Updated Subject: " + subject); } private Collection<Attribute> processCertChain() { List<Attribute> certAttributes= new ArrayList<Attribute>(); Attribute subjectId= new Attribute(Attribute.ID_SUB_ID, Attribute.DT_X500_NAME); subjectId.getValues().add(correctDN); certAttributes.add(subjectId); Attribute subjectIssuer= new Attribute(AuthorizationProfileConstants.ID_ATTRIBUTE_SUBJECT_ISSUER, Attribute.DT_X500_NAME); subjectIssuer.getValues().addAll(correctIssuers); certAttributes.add(subjectIssuer); Attribute vo= new Attribute(AuthorizationProfileConstants.ID_ATTRIBUTE_VIRTUAL_ORGANIZATION, Attribute.DT_STRING); vo.getValues().add(voName); certAttributes.add(vo); return certAttributes; } private void updateSubjectCertificateAttributes(Subject subject, Collection<Attribute> certAttributes) { for (Attribute certAttribute : certAttributes) { boolean alreadyExists= false; String certAttributeId= certAttribute.getId(); String certAttributeDataType= certAttribute.getDataType(); for (Attribute subjectAttribute : subject.getAttributes()) { if (subjectAttribute.getId().equals(certAttributeId) && subjectAttribute.getDataType().equals(certAttributeDataType)) { alreadyExists= true; System.out.println("WARN: Subject " + subjectAttribute + " already contains values, replace them with " + certAttribute); subjectAttribute.getValues().clear(); subjectAttribute.getValues().addAll(certAttribute.getValues()); } } if (!alreadyExists) { System.out.println("DEBUG: Add " + certAttribute + " to Subject"); subject.getAttributes().add(certAttribute); } } } }
false
true
public void testUpdateSubjectCertificateAttributes() { Collection<Attribute> certAttributes= processCertChain(); System.out.println("Incoming Subject: " + subject); updateSubjectCertificateAttributes(subject, certAttributes); for (Attribute attribute : subject.getAttributes()) { if (attribute.getId().equals(Attribute.ID_SUB_ID)) { for (Object object : attribute.getValues()) { String value= (String) object; assertEquals(correctDN, value); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_SUBJECT_ISSUER)) { for (Object object : attribute.getValues()) { assertTrue(correctIssuers.contains(object)); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_VIRTUAL_ORGANIZATION)) { for (Object object : attribute.getValues()) { assertEquals(voName, object.toString()); } } } System.out.println("Updated Subject: " + subject); }
public void testUpdateSubjectCertificateAttributes() { Collection<Attribute> certAttributes= processCertChain(); System.out.println("Incoming Subject: " + subject); updateSubjectCertificateAttributes(subject, certAttributes); boolean voNamePresent= false; for (Attribute attribute : subject.getAttributes()) { if (attribute.getId().equals(Attribute.ID_SUB_ID)) { for (Object object : attribute.getValues()) { String value= (String) object; assertEquals(correctDN, value); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_SUBJECT_ISSUER)) { for (Object object : attribute.getValues()) { assertTrue(correctIssuers.contains(object)); } } else if (attribute.getId().equals(AuthorizationProfileConstants.ID_ATTRIBUTE_VIRTUAL_ORGANIZATION)) { for (Object object : attribute.getValues()) { assertEquals(voName, object.toString()); voNamePresent= true; } } } assertTrue("missing vo attribute",voNamePresent); System.out.println("Updated Subject: " + subject); }
diff --git a/gui2/src/main/java/il/ac/idc/jdt/gui2/SegmentsPanel.java b/gui2/src/main/java/il/ac/idc/jdt/gui2/SegmentsPanel.java index 67fedf7..9d36df4 100644 --- a/gui2/src/main/java/il/ac/idc/jdt/gui2/SegmentsPanel.java +++ b/gui2/src/main/java/il/ac/idc/jdt/gui2/SegmentsPanel.java @@ -1,259 +1,259 @@ package il.ac.idc.jdt.gui2; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import il.ac.idc.jdt.extra.constraint.ConstrainedDelaunayTriangulation; import il.ac.idc.jdt.extra.constraint.datamodel.Line; import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Dimension; import java.awt.event.*; import java.util.EventObject; import java.util.Set; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static il.ac.idc.jdt.gui2.CanvasPanel.ClearEvent; import static il.ac.idc.jdt.gui2.CanvasPanel.SegmentSelectionEvent; /** * Created by IntelliJ IDEA. * User: daniels * Date: 6/9/12 */ public class SegmentsPanel extends JPanel { private static final Dimension PREFERRED_SIZE = new Dimension(250, 600); final EventBus eventBus; final JList list; final DefaultListModel model = new DefaultListModel(); boolean editingEnabled = true; public SegmentsPanel(EventBus eventBus) { this.eventBus = eventBus; setPreferredSize(PREFERRED_SIZE); add(new JLabel("Segments:")); list = new JList(model) { @Override public String getToolTipText(MouseEvent e) { int index = locationToIndex(e.getPoint()); Object item = getModel().getElementAt(index); return item.toString(); } }; list.setBorder(new BevelBorder(BevelBorder.LOWERED)); list.setPreferredSize(new Dimension(230, 580)); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } private void doPopupMenu(MouseEvent e) { JPopupMenu menu = popupMenu(); menu.show(e.getComponent(), e.getX(), e.getY()); } }); list.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { Object[] selectedValues = list.getSelectedValues(); - if (isDeletePressed(e) && hasSelectedItems(selectedValues)) + if (isDeletePressed(e) && hasSelectedItems(selectedValues) && isSegmentsEditingEnabled()) removeSelectedItems(selectedValues); } private boolean hasSelectedItems(Object[] selectedValues) { return selectedValues != null && selectedValues.length > 0; } private boolean isDeletePressed(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_DELETE; } }); list.addListSelectionListener(new ListSelectionListener() { @SuppressWarnings("SuspiciousToArrayCall") @Override public void valueChanged(ListSelectionEvent e) { Object[] selectedValues = list.getSelectedValues(); Line[] selectedLines = newArrayList(selectedValues).toArray(new Line[selectedValues.length]); SegmentsPanel.this.eventBus.post(new SegmentSelectionEvent(SegmentsPanel.this, newHashSet(selectedLines))); } }); add(list); } public JPopupMenu popupMenu() { JPopupMenu popupMenu = new JPopupMenu(); popupMenu.add(removeSelectedMenuItem()); popupMenu.add(new JPopupMenu.Separator()); popupMenu.add(removeAllMenuItem()); return popupMenu; } private JMenuItem removeAllMenuItem() { boolean hasItems = !SegmentsPanel.this.model.isEmpty(); JMenuItem item = new JMenuItem(onRemoveAllSegments()); item.setEnabled(hasItems && isSegmentsEditingEnabled()); return item; } private Action onRemoveAllSegments() { return new AbstractAction("Remove all segments") { @Override public void actionPerformed(ActionEvent e) { model.clear(); eventBus.post(new AllSegmentsRemovedEvent(SegmentsPanel.this)); } }; } private JMenuItem removeSelectedMenuItem() { Object[] selectedValues = list.getSelectedValues(); boolean selected = selectedValues != null && selectedValues.length > 0; JMenuItem item = new JMenuItem(onRemoveSelectedSegment()); item.setEnabled(selected && isSegmentsEditingEnabled()); return item; } private boolean isSegmentsEditingEnabled() { return editingEnabled; } private Action onRemoveSelectedSegment() { return new AbstractAction("Remove selected segment(s)") { @SuppressWarnings("SuspiciousToArrayCall") @Override public void actionPerformed(ActionEvent e) { Object[] selectedValues = list.getSelectedValues(); removeSelectedItems(selectedValues); } }; } private void removeSelectedItems(Object[] selectedValues) { for (Object selectedValue : selectedValues) model.removeElement(selectedValue); Line[] selectedLines = newArrayList(selectedValues).toArray(new Line[selectedValues.length]); eventBus.post(new SelectedSegmentsRemovedEvent(this, newHashSet(selectedLines))); } @Subscribe public void onSegmentAdded(SegmentAddedEvent event) { model.addElement(event.line); } @Subscribe public void onClear(ClearEvent event) { model.clear(); this.editingEnabled = true; } @Subscribe public void onTriangulationCalculated(TriangulationCalculatedEvent event) { editingEnabled = false; } @Subscribe public void onTriangulationReset(TriangulationResetEvent event) { editingEnabled = true; } public static class SelectedSegmentsRemovedEvent extends EventObject { final Set<Line> removedSegments; public SelectedSegmentsRemovedEvent(Object source, Set<Line> removedSegments) { super(source); this.removedSegments = removedSegments; } } public static class AllSegmentsRemovedEvent extends EventObject { public AllSegmentsRemovedEvent(Object source) { super(source); } } public static class SegmentAddedEvent extends EventObject { final Line line; public SegmentAddedEvent(Object source, Line line) { super(source); this.line = line; } } public static class TriangulationResetEvent extends EventObject { public TriangulationResetEvent(Object source) { super(source); } } public static class TriangulationCalculatedEvent extends EventObject { final ConstrainedDelaunayTriangulation triangulation; final long runtimeInMs; public TriangulationCalculatedEvent(Object source, ConstrainedDelaunayTriangulation triangulation, long runtimeInMs) { super(source); this.triangulation = triangulation; this.runtimeInMs = runtimeInMs; } } }
true
true
public SegmentsPanel(EventBus eventBus) { this.eventBus = eventBus; setPreferredSize(PREFERRED_SIZE); add(new JLabel("Segments:")); list = new JList(model) { @Override public String getToolTipText(MouseEvent e) { int index = locationToIndex(e.getPoint()); Object item = getModel().getElementAt(index); return item.toString(); } }; list.setBorder(new BevelBorder(BevelBorder.LOWERED)); list.setPreferredSize(new Dimension(230, 580)); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } private void doPopupMenu(MouseEvent e) { JPopupMenu menu = popupMenu(); menu.show(e.getComponent(), e.getX(), e.getY()); } }); list.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { Object[] selectedValues = list.getSelectedValues(); if (isDeletePressed(e) && hasSelectedItems(selectedValues)) removeSelectedItems(selectedValues); } private boolean hasSelectedItems(Object[] selectedValues) { return selectedValues != null && selectedValues.length > 0; } private boolean isDeletePressed(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_DELETE; } }); list.addListSelectionListener(new ListSelectionListener() { @SuppressWarnings("SuspiciousToArrayCall") @Override public void valueChanged(ListSelectionEvent e) { Object[] selectedValues = list.getSelectedValues(); Line[] selectedLines = newArrayList(selectedValues).toArray(new Line[selectedValues.length]); SegmentsPanel.this.eventBus.post(new SegmentSelectionEvent(SegmentsPanel.this, newHashSet(selectedLines))); } }); add(list); }
public SegmentsPanel(EventBus eventBus) { this.eventBus = eventBus; setPreferredSize(PREFERRED_SIZE); add(new JLabel("Segments:")); list = new JList(model) { @Override public String getToolTipText(MouseEvent e) { int index = locationToIndex(e.getPoint()); Object item = getModel().getElementAt(index); return item.toString(); } }; list.setBorder(new BevelBorder(BevelBorder.LOWERED)); list.setPreferredSize(new Dimension(230, 580)); list.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) doPopupMenu(e); } private void doPopupMenu(MouseEvent e) { JPopupMenu menu = popupMenu(); menu.show(e.getComponent(), e.getX(), e.getY()); } }); list.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { Object[] selectedValues = list.getSelectedValues(); if (isDeletePressed(e) && hasSelectedItems(selectedValues) && isSegmentsEditingEnabled()) removeSelectedItems(selectedValues); } private boolean hasSelectedItems(Object[] selectedValues) { return selectedValues != null && selectedValues.length > 0; } private boolean isDeletePressed(KeyEvent e) { return e.getKeyCode() == KeyEvent.VK_DELETE; } }); list.addListSelectionListener(new ListSelectionListener() { @SuppressWarnings("SuspiciousToArrayCall") @Override public void valueChanged(ListSelectionEvent e) { Object[] selectedValues = list.getSelectedValues(); Line[] selectedLines = newArrayList(selectedValues).toArray(new Line[selectedValues.length]); SegmentsPanel.this.eventBus.post(new SegmentSelectionEvent(SegmentsPanel.this, newHashSet(selectedLines))); } }); add(list); }
diff --git a/YearView.java b/YearView.java index 77af245..92ca19b 100644 --- a/YearView.java +++ b/YearView.java @@ -1,38 +1,39 @@ import javax.swing.*; import javax.swing.table.*; import java.awt.*; public class YearView extends BaseView { private static final long serialVersionUID = 1L; private GridLayout grid; private int offset = 0; private String[] names = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private int[] days = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; public YearView(CalendarModel model) { super(model); } public void setupCalendar() { grid = new GridLayout(0, 4); panel.setLayout(grid); for (int i = 0; i < 12; i++) { addTable(i); } this.add(panel); } private void addTable(int i) { TableModel temp = new YearDataModel(names[i], offset, days[i]); offset = (offset + days[i]) % 7; JTable month = new JTable(temp); + month.getTableHeader().setReorderingAllowed(false); month.setRowSelectionAllowed(false); month.setRowHeight(30); JScrollPane scrollPane = new JScrollPane(month); this.add(scrollPane, BorderLayout.CENTER); panel.add(scrollPane); } }
true
true
private void addTable(int i) { TableModel temp = new YearDataModel(names[i], offset, days[i]); offset = (offset + days[i]) % 7; JTable month = new JTable(temp); month.setRowSelectionAllowed(false); month.setRowHeight(30); JScrollPane scrollPane = new JScrollPane(month); this.add(scrollPane, BorderLayout.CENTER); panel.add(scrollPane); }
private void addTable(int i) { TableModel temp = new YearDataModel(names[i], offset, days[i]); offset = (offset + days[i]) % 7; JTable month = new JTable(temp); month.getTableHeader().setReorderingAllowed(false); month.setRowSelectionAllowed(false); month.setRowHeight(30); JScrollPane scrollPane = new JScrollPane(month); this.add(scrollPane, BorderLayout.CENTER); panel.add(scrollPane); }
diff --git a/src/com/teamblobby/studybeacon/BeaconEditActivity.java b/src/com/teamblobby/studybeacon/BeaconEditActivity.java index 31c8159..a6ca086 100644 --- a/src/com/teamblobby/studybeacon/BeaconEditActivity.java +++ b/src/com/teamblobby/studybeacon/BeaconEditActivity.java @@ -1,641 +1,644 @@ package com.teamblobby.studybeacon; import java.text.DateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import com.google.android.maps.*; import com.teamblobby.studybeacon.datastructures.*; import com.teamblobby.studybeacon.network.APIClient; import com.teamblobby.studybeacon.network.APIHandler; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.OnItemSelectedListener; import android.telephony.PhoneNumberUtils; import android.telephony.TelephonyManager; import android.text.util.*; public class BeaconEditActivity extends Activity implements APIHandler { private static final String SMS_URI_PREFIX = "smsto:"; private static final int DEFAULT_WORKINGON_SPINNER_POSITION = 0; // Here is the interface for intents to use public static final String EXTRA_COURSE = "Course"; public static final String EXTRA_BEACON = "beacon"; public static final String ACTION_NEW = "com.blobby.studybeacon.BeaconEditActivity.new"; public static final String ACTION_EDIT = "com.blobby.studybeacon.BeaconEditActivity.edit"; public static final String ACTION_VIEW = "com.blobby.studybeacon.BeaconEditActivity.view"; public static final String TAG = "SBBeaconEditActivity"; protected enum OperationMode { MODE_NEW, MODE_EDIT, MODE_VIEW } protected OperationMode mode; protected TextView beaconTitleTV; protected Spinner courseSpinner; protected TextView expiresTV; protected Spinner expiresSpinner; protected TextClickToEdit expiresTimeTV; protected Spinner workingOnSpinner; protected TextView contact; protected EditText phone; protected EditText email; protected EditText details; protected Button beaconActionButton; protected Button beaconSecondaryActionButton; // This represents the beacon we are making. protected BeaconInfo mBeacon; private ArrayAdapter<CourseInfo> courseAdapter; private ArrayAdapter<DurationSpinnerItem> expiresAdapter; private ArrayAdapter<String> workingOnAdapter; private UserLocator userLocator; private ProgressDialog currentDialog; private DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT); protected boolean expiresEdited = false; private String expiresTimeFormatted; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.beacon); loadUIEls(); // This is the intent that started us Intent startingIntent = getIntent(); String startingAction = startingIntent.getAction(); // Figure out what to do if (startingAction.equals(ACTION_VIEW)) { mode = OperationMode.MODE_VIEW; } else if (startingAction.equals(ACTION_EDIT)) { mode = OperationMode.MODE_EDIT; } else { // By default, create a new beacon mode = OperationMode.MODE_NEW; } switch (mode) { case MODE_VIEW: setUpForView(savedInstanceState,startingIntent); break; case MODE_EDIT: setUpForEdit(savedInstanceState,startingIntent); break; case MODE_NEW: default: setUpForNew(savedInstanceState,startingIntent); break; } } private void loadUIEls() { beaconTitleTV = (TextView) findViewById(R.id.titleText); courseSpinner = (Spinner) findViewById(R.id.courseSpinner); expiresTV = (TextView) findViewById(R.id.expiresTV); expiresSpinner = (Spinner) findViewById(R.id.expiresSpinner); //expiresTimeTV = (TextView) findViewById(R.id.expiresTimeTV); workingOnSpinner = (Spinner) findViewById(R.id.workingOnSpinner); contact = (TextView) findViewById(R.id.contactTV); phone = (EditText) findViewById(R.id.phone); email = (EditText) findViewById(R.id.email); details = (EditText) findViewById(R.id.detailsEdit); beaconActionButton = (Button) findViewById(R.id.beaconActionButton); beaconSecondaryActionButton = (Button) findViewById(R.id.beaconSecondaryActionButton); // Set the spinners up courseAdapter = new ArrayAdapter<CourseInfo>(this, android.R.layout.simple_spinner_item, Global.getMyCourseInfos()); courseAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); courseSpinner.setAdapter(courseAdapter); // set up the array for the expires spinner List<DurationSpinnerItem> expiresList = new ArrayList<DurationSpinnerItem>(); String[] expireTimes = this.getResources().getStringArray(R.array.expiresTimes); int[] expireMinutes = this.getResources().getIntArray(R.array.expiresMinutes); for ( int j=0; j<expireTimes.length; j++ ){ expiresList.add(new DurationSpinnerItem(expireTimes[j], expireMinutes[j])); } expiresAdapter = new ArrayAdapter<DurationSpinnerItem>( this, android.R.layout.simple_spinner_item, expiresList); expiresAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); expiresSpinner.setAdapter(expiresAdapter); List<String> workingOnList = new ArrayList<String>(); workingOnList.addAll(Arrays.asList(getResources().getStringArray(R.array.workingOnList))); workingOnAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, workingOnList); workingOnAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); workingOnSpinner.setAdapter(workingOnAdapter); workingOnSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> adapterView, View itemView, int position, long id) { int count = workingOnAdapter.getCount(); if ( position == count-1 ) { // last element customWorkingOnAlert(count-1).show(); } } public void onNothingSelected(AdapterView<?> arg0) {} }); expiresSpinner.setSelection(Global.res.getInteger(R.integer.expiresDefaultIndex)); } public void enterMyNumber(View v) { TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); String myNumber = tm.getLine1Number(); if (myNumber != null) phone.setText(PhoneNumberUtils.formatNumber(myNumber)); } public void enterMyEmail(View v){ Account[] accounts = AccountManager.get(this).getAccounts(); if ( accounts[0] != null ) email.setText(accounts[0].name); } private Builder customWorkingOnAlert(final int index){ final EditText input = new EditText(this); return new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.workingOn)) .setView(input) .setPositiveButton(getResources().getString(R.string.workingOnOK), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if ( input.getText().toString().equals("")){ workingOnSpinner.setSelection(DEFAULT_WORKINGON_SPINNER_POSITION); return; // nothing to do! } String text = input.getText().toString(); addToWorkingOn(index, text); } }) .setNegativeButton(getResources().getString(R.string.workingOnCancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // return spinner to first element workingOnSpinner.setSelection(DEFAULT_WORKINGON_SPINNER_POSITION); } }); } private class DurationSpinnerItem { private int minutes; private String displayString; @Override public String toString() { return this.getDisplayString(); } public int getMinutes() { return minutes; } public String getDisplayString() { return displayString; } DurationSpinnerItem(String displayString,int minutes){ this.minutes=minutes; this.displayString=displayString; } } protected void setCourseSpinnerItem(String course) { if (course != null) { // Set the course spinner's selected element int courseIndex = 0; int count = courseAdapter.getCount(); for ( int j=0; j<count; j++){ if (courseAdapter.getItem(j).getName().equals(course)){ courseIndex = j; break; } } courseSpinner.setSelection(courseIndex); } } protected int newDurationFromField() { return ((DurationSpinnerItem) expiresSpinner.getSelectedItem()).getMinutes(); } protected BeaconInfo newBeaconFromFields(GeoPoint location) { String courseName = ((CourseInfo) courseSpinner.getSelectedItem()).getName(); //GeoPoint loc = userLocator.getLocation(); // grab the user's location Log.d(TAG,"loc: late6="+location.getLatitudeE6()+" longe6="+location.getLongitudeE6()); return new BeaconInfoSimple(-1, // don't have a BeaconId yet courseName, location, -1, // don't have a # of visitors yet (String)workingOnSpinner.getSelectedItem(), details.getText().toString(), phone.getText().toString(), email.getText().toString(), new Date(), new Date() ); } private void setUpForNew(Bundle savedInstanceState, Intent startingIntent) { // TODO -- Add logic if already at a beacon // Set title text beaconTitleTV.setText(R.string.newBeacon); // If a course has been selected in the intent, try to set the spinner setCourseSpinnerItem(startingIntent.getStringExtra(EXTRA_COURSE)); // Add a listener for the action button beaconActionButton.setOnClickListener(new NewBeaconClickListener(this)); // Set the drawable on the action button beaconActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.newbeaconicon, 0, 0, 0); // start getting the user's location userLocator = new UserLocator(); userLocator.startLocating(); } protected final class NewBeaconClickListener implements OnClickListener { protected BeaconEditActivity mActivity; public NewBeaconClickListener(BeaconEditActivity sbBeaconEditActivity) { mActivity = sbBeaconEditActivity; } public void onClick(View v) { if ( !mActivity.userLocator.isReady() ) { Toast.makeText(mActivity, R.string.stillLocating, Toast.LENGTH_SHORT).show(); //inform we are still locating. Log.d(TAG, "canceled, still locating"); return; } currentDialog = ProgressDialog.show(mActivity, "", "Creating beacon..."); // needs working on from fields APIClient.add(mActivity.newBeaconFromFields(userLocator.getLocation()), mActivity.newDurationFromField(), mActivity); } } protected int editDurationFromField() { if ( expiresEdited ){ return newDurationFromField(); } else { return APIClient.DURATION_UNCHANGED; } } protected BeaconInfo editBeaconFromFields() { String courseName = ((CourseInfo) courseSpinner.getSelectedItem()).getName(); return new BeaconInfoSimple( Global.getCurrentBeacon().getBeaconId(), courseName, new GeoPoint(0,0), -1, // don't have a # of visitors yet (String)workingOnSpinner.getSelectedItem(), details.getText().toString(), phone.getText().toString(), email.getText().toString(), new Date(), new Date() ); } private void setUpForEdit(Bundle savedInstanceState, Intent startingIntent) { // TODO Add logic if already at a beacon // Set title text beaconTitleTV.setText(R.string.editBeacon); mBeacon = Global.getCurrentBeacon(); loadBeaconData(); // do this first // Don't let the class be editable //courseSpinner.setEnabled(false); convertToTextClickToEdit(courseSpinner,courseSpinner.getSelectedItem().toString(),true); // true hides the edit button convertToTextClickToEdit(workingOnSpinner,workingOnSpinner.getSelectedItem().toString(),false); //s.setEnabled(false); // Change the "expires" text expiresTV.setText(R.string.expiresAt); //expiresSpinner.setVisibility(View.GONE); //expiresTimeTV.setVisibility(View.VISIBLE); expiresTimeTV = convertToTextClickToEdit(expiresSpinner,expiresTimeFormatted,false,new Runnable() { // make the edit button also change the expires text public void run() { expiresTV.setText(R.string.expiresIn); expiresEdited = true; } }); beaconActionButton.setText(R.string.saveBeacon); // Set the drawable on the action button beaconActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_edit, 0, 0, 0); beaconActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { APIClient.edit(editBeaconFromFields(), editDurationFromField(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Updating beacon..."); } }); beaconSecondaryActionButton.setVisibility(View.VISIBLE); beaconSecondaryActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_leave, 0, 0, 0); // The secondary button is the leave button beaconSecondaryActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mBeacon != null){ APIClient.leave(mBeacon.getBeaconId(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Leaving beacon..."); }else Toast.makeText(BeaconEditActivity.this, "Something went wrong -- I don't know which beacon you're viewing", Toast.LENGTH_SHORT).show(); } }); View phoneLayout = findViewById(R.id.phoneLayout); View emailLayout = findViewById(R.id.emailLayout); String text; + boolean numberGiven = false; if ( mBeacon.getTelephone().equals("") ){ text = "No phone number given."; } else { text = phone.getText().toString(); + numberGiven = true; } TextClickToEdit phoneC2E = convertToTextClickToEdit(phoneLayout, text, false); Linkify.addLinks(phoneC2E.getTextView(), Linkify.PHONE_NUMBERS); - phoneC2E.enableSmsButton(SMS_URI_PREFIX+PhoneNumberUtils.stripSeparators(phone.getText().toString())); + if ( numberGiven ) + phoneC2E.enableSmsButton(SMS_URI_PREFIX+PhoneNumberUtils.stripSeparators(phone.getText().toString())); if ( mBeacon.getEmail().equals("") ){ text = "No email address given."; } else { text = email.getText().toString(); } TextClickToEdit emailC2E = convertToTextClickToEdit(emailLayout, text, false); Linkify.addLinks(emailC2E.getTextView(), Linkify.EMAIL_ADDRESSES); } private void setUpForView(Bundle savedInstanceState, Intent startingIntent) { // Set title text beaconTitleTV.setText(R.string.beaconDetails); mBeacon = startingIntent.getParcelableExtra(EXTRA_BEACON); // do this first loadBeaconData(); // Turn the spinners into textClickToEdits Spinner spinners[] = {courseSpinner, workingOnSpinner}; for (Spinner s : spinners) convertToTextClickToEdit(s,s.getSelectedItem().toString(),true); //s.setEnabled(false); // Change the "expires" text expiresTV.setText(R.string.expiresAt); //expiresSpinner.setVisibility(View.GONE); //expiresTimeTV.setVisibility(View.VISIBLE); expiresTimeTV = convertToTextClickToEdit(expiresSpinner,expiresTimeFormatted,true); EditText ets[] = {phone, email, details}; for (EditText e : ets) { e.setFocusable(false); } // make the details have a different hint if nothing was given details.setHint(R.string.detailHintView); beaconActionButton.setText(R.string.joinBeacon); // Set the drawable on the action button beaconActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_join, 0, 0, 0); beaconActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO check user's location if (mBeacon != null) { APIClient.join(mBeacon.getBeaconId(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Joining beacon..."); } else Toast.makeText(BeaconEditActivity.this, "Something went wrong -- I don't know which beacon you're viewing", Toast.LENGTH_SHORT).show(); } }); if ( mBeacon == null ) return; // don't show contact details if they weren't filled in View phoneLayout = findViewById(R.id.phoneLayout); View emailLayout = findViewById(R.id.emailLayout); if ( mBeacon.getTelephone().equals("") ){ phoneLayout.setVisibility(View.GONE); } else { TextClickToEdit phoneC2E = convertToTextClickToEdit(phoneLayout, phone.getText().toString(), true); Linkify.addLinks(phoneC2E.getTextView(), Linkify.PHONE_NUMBERS); phoneC2E.enableSmsButton(SMS_URI_PREFIX+PhoneNumberUtils.stripSeparators(phone.getText().toString())); } if ( mBeacon.getEmail().equals("") ){ emailLayout.setVisibility(View.GONE); } else { TextClickToEdit emailC2E = convertToTextClickToEdit(emailLayout, email.getText().toString(), true); Linkify.addLinks(emailC2E.getTextView(), Linkify.EMAIL_ADDRESSES); } if ( mBeacon.getTelephone().equals("") && mBeacon.getEmail().equals("") ) contact.setVisibility(View.GONE); } private TextClickToEdit convertToTextClickToEdit(final View s, String text, boolean hideButton) { return convertToTextClickToEdit(s, text, hideButton, new Runnable() {public void run(){}}); } private TextClickToEdit convertToTextClickToEdit(final View s, String text, boolean hideButton, final Runnable callback) { LinearLayout layout = (LinearLayout) s.getParent(); // find out where the spinner is int spinnerIndex = -1; for ( int j=0; j<layout.getChildCount(); j++ ){ if ( s.equals(layout.getChildAt(j)) ){ spinnerIndex = j; break; } } if ( spinnerIndex == -1 ){ Log.e(TAG, "Crap, didn't find the spinner"); return null; } // make the spinner disappear s.setVisibility(View.GONE); // new text view final TextClickToEdit textClick = new TextClickToEdit(this); textClick.setText(text); // make the button reverse the process textClick.setButtonClickListener(new OnClickListener() { public void onClick(View v) { textClick.setVisibility(View.GONE); s.setVisibility(View.VISIBLE); callback.run(); } }); // hide the button if asked if ( hideButton ) textClick.hideButton(); //stick it in layout.addView(textClick, spinnerIndex); return textClick; } private void loadBeaconData() { // TODO What do we do if somebody did not call this properly? if (mBeacon == null) // FAILURE return; // Load the course name setCourseSpinnerItem(mBeacon.getCourseName()); phone.setText(mBeacon.getTelephone()); email.setText(mBeacon.getEmail()); setWorkingOn(mBeacon.getWorkingOn()); details.setText(mBeacon.getDetails()); expiresTimeFormatted = df.format(mBeacon.getExpires()); } private void setWorkingOn(String workingOn) { int position = workingOnAdapter.getPosition(workingOn); if ( position == -1 ){ // -1 means it didn't find it // add it to the spinner position = workingOnAdapter.getCount()-1; addToWorkingOn(position, workingOn); } workingOnSpinner.setSelection(position); } //////////////////////////////////////////////////////////////// // The following are for implementing SBAPIHandler public Activity getActivity() { return this; } public void onSuccess(APICode code, Object response) { BeaconInfo beacon = null; String messageText = null; switch (code) { case CODE_ADD: beacon = (BeaconInfo) response; messageText = new String("Beacon added successfully"); break; case CODE_EDIT: beacon = (BeaconInfo) response; messageText = new String("Beacon updated"); break; case CODE_JOIN: beacon = (BeaconInfo) response; messageText = new String("Beacon joined successfully"); break; case CODE_LEAVE: messageText = new String("Beacon left successfully"); break; case CODE_SYNC: beacon = (BeaconInfo) response; messageText = new String("Resynced with server successfully"); break; default: // TODO Shouldn't get here ... complain? } Toast.makeText(this, messageText, Toast.LENGTH_SHORT).show(); Global.setCurrentBeacon(beacon); Global.updateBeaconRunningNotification(); currentDialog.dismiss(); // go back home // TODO Set a result code? SBMapActivity will need to get new data. this.finish(); } public void onFailure(APICode code, Throwable e) { String messageText = null; switch (code) { case CODE_ADD: messageText = new String("Failed to add beacon"); Global.setCurrentBeacon(null); Global.updateBeaconRunningNotification(); break; case CODE_EDIT: messageText = new String("Failed to save beacon"); // TODO What do we do here? break; case CODE_JOIN: messageText = new String("Failed to join beacon"); Global.setCurrentBeacon(null); Global.updateBeaconRunningNotification(); break; case CODE_LEAVE: messageText = new String("Failed to leave beacon -- trying to re-sync with server"); APIClient.sync(this); break; case CODE_SYNC: messageText = new String("Failed to re-sync with server."); // TODO What do we do? break; default: // Shouldn't get here ... complain? } Toast.makeText(this, messageText, Toast.LENGTH_SHORT).show(); currentDialog.dismiss(); // For CODE_LEAVE, we have started a sync; now show a dialog must be after the above dismissal if (code == APICode.CODE_LEAVE) currentDialog = ProgressDialog.show(this, "", "Trying to re-sync with server..."); } protected void addToWorkingOn(final int index, String text) { workingOnAdapter.insert(text, index); workingOnAdapter.notifyDataSetChanged(); } }
false
true
private void setUpForEdit(Bundle savedInstanceState, Intent startingIntent) { // TODO Add logic if already at a beacon // Set title text beaconTitleTV.setText(R.string.editBeacon); mBeacon = Global.getCurrentBeacon(); loadBeaconData(); // do this first // Don't let the class be editable //courseSpinner.setEnabled(false); convertToTextClickToEdit(courseSpinner,courseSpinner.getSelectedItem().toString(),true); // true hides the edit button convertToTextClickToEdit(workingOnSpinner,workingOnSpinner.getSelectedItem().toString(),false); //s.setEnabled(false); // Change the "expires" text expiresTV.setText(R.string.expiresAt); //expiresSpinner.setVisibility(View.GONE); //expiresTimeTV.setVisibility(View.VISIBLE); expiresTimeTV = convertToTextClickToEdit(expiresSpinner,expiresTimeFormatted,false,new Runnable() { // make the edit button also change the expires text public void run() { expiresTV.setText(R.string.expiresIn); expiresEdited = true; } }); beaconActionButton.setText(R.string.saveBeacon); // Set the drawable on the action button beaconActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_edit, 0, 0, 0); beaconActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { APIClient.edit(editBeaconFromFields(), editDurationFromField(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Updating beacon..."); } }); beaconSecondaryActionButton.setVisibility(View.VISIBLE); beaconSecondaryActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_leave, 0, 0, 0); // The secondary button is the leave button beaconSecondaryActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mBeacon != null){ APIClient.leave(mBeacon.getBeaconId(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Leaving beacon..."); }else Toast.makeText(BeaconEditActivity.this, "Something went wrong -- I don't know which beacon you're viewing", Toast.LENGTH_SHORT).show(); } }); View phoneLayout = findViewById(R.id.phoneLayout); View emailLayout = findViewById(R.id.emailLayout); String text; if ( mBeacon.getTelephone().equals("") ){ text = "No phone number given."; } else { text = phone.getText().toString(); } TextClickToEdit phoneC2E = convertToTextClickToEdit(phoneLayout, text, false); Linkify.addLinks(phoneC2E.getTextView(), Linkify.PHONE_NUMBERS); phoneC2E.enableSmsButton(SMS_URI_PREFIX+PhoneNumberUtils.stripSeparators(phone.getText().toString())); if ( mBeacon.getEmail().equals("") ){ text = "No email address given."; } else { text = email.getText().toString(); } TextClickToEdit emailC2E = convertToTextClickToEdit(emailLayout, text, false); Linkify.addLinks(emailC2E.getTextView(), Linkify.EMAIL_ADDRESSES); }
private void setUpForEdit(Bundle savedInstanceState, Intent startingIntent) { // TODO Add logic if already at a beacon // Set title text beaconTitleTV.setText(R.string.editBeacon); mBeacon = Global.getCurrentBeacon(); loadBeaconData(); // do this first // Don't let the class be editable //courseSpinner.setEnabled(false); convertToTextClickToEdit(courseSpinner,courseSpinner.getSelectedItem().toString(),true); // true hides the edit button convertToTextClickToEdit(workingOnSpinner,workingOnSpinner.getSelectedItem().toString(),false); //s.setEnabled(false); // Change the "expires" text expiresTV.setText(R.string.expiresAt); //expiresSpinner.setVisibility(View.GONE); //expiresTimeTV.setVisibility(View.VISIBLE); expiresTimeTV = convertToTextClickToEdit(expiresSpinner,expiresTimeFormatted,false,new Runnable() { // make the edit button also change the expires text public void run() { expiresTV.setText(R.string.expiresIn); expiresEdited = true; } }); beaconActionButton.setText(R.string.saveBeacon); // Set the drawable on the action button beaconActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_edit, 0, 0, 0); beaconActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { APIClient.edit(editBeaconFromFields(), editDurationFromField(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Updating beacon..."); } }); beaconSecondaryActionButton.setVisibility(View.VISIBLE); beaconSecondaryActionButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beacon_leave, 0, 0, 0); // The secondary button is the leave button beaconSecondaryActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (mBeacon != null){ APIClient.leave(mBeacon.getBeaconId(), BeaconEditActivity.this); currentDialog = ProgressDialog.show(BeaconEditActivity.this, "", "Leaving beacon..."); }else Toast.makeText(BeaconEditActivity.this, "Something went wrong -- I don't know which beacon you're viewing", Toast.LENGTH_SHORT).show(); } }); View phoneLayout = findViewById(R.id.phoneLayout); View emailLayout = findViewById(R.id.emailLayout); String text; boolean numberGiven = false; if ( mBeacon.getTelephone().equals("") ){ text = "No phone number given."; } else { text = phone.getText().toString(); numberGiven = true; } TextClickToEdit phoneC2E = convertToTextClickToEdit(phoneLayout, text, false); Linkify.addLinks(phoneC2E.getTextView(), Linkify.PHONE_NUMBERS); if ( numberGiven ) phoneC2E.enableSmsButton(SMS_URI_PREFIX+PhoneNumberUtils.stripSeparators(phone.getText().toString())); if ( mBeacon.getEmail().equals("") ){ text = "No email address given."; } else { text = email.getText().toString(); } TextClickToEdit emailC2E = convertToTextClickToEdit(emailLayout, text, false); Linkify.addLinks(emailC2E.getTextView(), Linkify.EMAIL_ADDRESSES); }
diff --git a/src/no/runsafe/itemflangerorimega/tools/enchants/MoltenSoaking.java b/src/no/runsafe/itemflangerorimega/tools/enchants/MoltenSoaking.java index 9abd00d..0c416e2 100644 --- a/src/no/runsafe/itemflangerorimega/tools/enchants/MoltenSoaking.java +++ b/src/no/runsafe/itemflangerorimega/tools/enchants/MoltenSoaking.java @@ -1,72 +1,72 @@ package no.runsafe.itemflangerorimega.tools.enchants; import no.runsafe.framework.api.ILocation; import no.runsafe.framework.api.block.IBlock; import no.runsafe.framework.api.player.IPlayer; import no.runsafe.framework.minecraft.Item; import no.runsafe.framework.minecraft.Sound; import no.runsafe.framework.minecraft.WorldEffect; import no.runsafe.framework.minecraft.item.meta.RunsafeMeta; import no.runsafe.itemflangerorimega.tools.CustomToolEnchant; public class MoltenSoaking extends CustomToolEnchant { @Override public String getEnchantText() { return "Molten Soaking I"; } @Override public String getSimpleName() { return "molten_soaking"; } @Override public boolean onUse(IPlayer player, RunsafeMeta item, IBlock rightClicked) { ILocation location = rightClicked == null ? player.getLocation() : rightClicked.getLocation(); if (location != null) { - item.remove(1); + player.removeExactItem(item, 1); location.playEffect(WorldEffect.PORTAL, 0.5F, 100, 10F); location.playSound(Sound.Portal.Trigger, 5F, 2F); removeBlock(location, 0, 0); removeBlock(location, 1, 0); removeBlock(location, 1, 1); removeBlock(location, 0, 1); removeBlock(location, -1, 0); removeBlock(location, -1, -1); removeBlock(location, 0, -1); removeBlock(location, -1, 1); removeBlock(location, 1, -1); } return true; } private void removeBlock(ILocation location, int offsetX, int offsetZ) { removeLava(location, offsetX, 0, offsetZ); removeLava(location, offsetX, 1, offsetZ); removeLava(location, offsetX, 2, offsetZ); removeLava(location, offsetX, -1, offsetZ); removeLava(location, offsetX, -2, offsetZ); } private void removeLava(ILocation location, int offsetX, int offsetY, int offsetZ) { ILocation newLocation = location.clone(); newLocation.offset(offsetX, offsetY, offsetZ); IBlock block = newLocation.getBlock(); if (block != null && (block.is(Item.Unavailable.Lava) || block.is(Item.Unavailable.StationaryLava))) block.set(Item.Unavailable.Air); } }
true
true
public boolean onUse(IPlayer player, RunsafeMeta item, IBlock rightClicked) { ILocation location = rightClicked == null ? player.getLocation() : rightClicked.getLocation(); if (location != null) { item.remove(1); location.playEffect(WorldEffect.PORTAL, 0.5F, 100, 10F); location.playSound(Sound.Portal.Trigger, 5F, 2F); removeBlock(location, 0, 0); removeBlock(location, 1, 0); removeBlock(location, 1, 1); removeBlock(location, 0, 1); removeBlock(location, -1, 0); removeBlock(location, -1, -1); removeBlock(location, 0, -1); removeBlock(location, -1, 1); removeBlock(location, 1, -1); } return true; }
public boolean onUse(IPlayer player, RunsafeMeta item, IBlock rightClicked) { ILocation location = rightClicked == null ? player.getLocation() : rightClicked.getLocation(); if (location != null) { player.removeExactItem(item, 1); location.playEffect(WorldEffect.PORTAL, 0.5F, 100, 10F); location.playSound(Sound.Portal.Trigger, 5F, 2F); removeBlock(location, 0, 0); removeBlock(location, 1, 0); removeBlock(location, 1, 1); removeBlock(location, 0, 1); removeBlock(location, -1, 0); removeBlock(location, -1, -1); removeBlock(location, 0, -1); removeBlock(location, -1, 1); removeBlock(location, 1, -1); } return true; }
diff --git a/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/CRLuceneIndexJob.java b/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/CRLuceneIndexJob.java index 51a230c0..269908a9 100644 --- a/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/CRLuceneIndexJob.java +++ b/contentconnector-lucene/src/main/java/com/gentics/cr/lucene/indexer/index/CRLuceneIndexJob.java @@ -1,720 +1,720 @@ package com.gentics.cr.lucene.indexer.index; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.Map.Entry; import org.apache.log4j.Logger; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.TermVector; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import com.gentics.api.lib.resolving.Resolvable; import com.gentics.cr.CRConfig; import com.gentics.cr.CRConfigUtil; import com.gentics.cr.CRError; import com.gentics.cr.CRRequest; import com.gentics.cr.CRResolvableBean; import com.gentics.cr.RequestProcessor; import com.gentics.cr.events.EventManager; import com.gentics.cr.exceptions.CRException; import com.gentics.cr.lucene.events.IndexingFinishedEvent; import com.gentics.cr.lucene.indexaccessor.IndexAccessor; import com.gentics.cr.lucene.indexer.IndexerUtil; import com.gentics.cr.lucene.indexer.transformer.ContentTransformer; import com.gentics.cr.monitoring.MonitorFactory; import com.gentics.cr.monitoring.UseCase; import com.gentics.cr.util.indexing.AbstractUpdateCheckerJob; import com.gentics.cr.util.indexing.IndexLocation; /** * CRLuceneIndexJob handles the indexing of a Gentics ContentRepository into * Lucene. * Last changed: $Date: 2009-09-02 17:57:48 +0200 (Mi, 02 Sep 2009) $ * @version $Revision: 180 $ * @author $Author: [email protected] $ * */ public class CRLuceneIndexJob extends AbstractUpdateCheckerJob { /** * static log4j {@link Logger} to log errors and debug. */ private static final Logger LOG = Logger.getLogger(CRLuceneIndexJob.class); /** * static log4j {@link Logger} to log errors and debug. */ private static final Logger TR_LOG = Logger .getLogger(ContentTransformer.class); /** * Name of class to use for IndexLocation, must extend * {@link com.gentics.cr.util.indexing.IndexLocation}. */ public static final String INDEXLOCATIONCLASS = "com.gentics.cr.lucene.indexer.index.LuceneSingleIndexLocation"; /** * Variable for RequestProcessor which gets us the objects for updating the * index. */ private RequestProcessor rp = null; /** * indicates if the lucene index should be optimized after indexing. */ private boolean optimize = false; /** * indicates the maximum amount of segments (files) used storing the index. */ private String maxSegmentsString = null; /** * Create new instance of IndexJob. * @param config configuration for the index job * @param indexLoc location of the lucene index * @param configmap TODO add javadoc comment here */ public CRLuceneIndexJob(final CRConfig config, final IndexLocation indexLoc, final Hashtable<String, CRConfigUtil> configmap) { super(config, indexLoc, configmap); String ignoreoptimizeString = config.getString(OPTIMIZE_KEY); if (ignoreoptimizeString != null) { optimize = Boolean.parseBoolean(ignoreoptimizeString); } maxSegmentsString = config.getString(MAXSEGMENTS_KEY); String storeVectorsString = config.getString(STORE_VECTORS_KEY); if (storeVectorsString != null) { storeVectors = Boolean.parseBoolean(storeVectorsString); } try { rp = config.getNewRequestProcessorInstance(1); } catch (CRException e) { log.error("Could not create RequestProcessor instance." + config.getName(), e); } String timestampattributeString = config.getString(TIMESTAMP_ATTR_KEY); if (timestampattributeString != null && !"".equals(timestampattributeString)) { this.timestampattribute = timestampattributeString; } } /** * Key to be used for saving state to contentstatus. */ public static final String PARAM_LASTINDEXRUN = "lastindexrun"; /** * Key to be used for saving state to contentstatus. */ public static final String PARAM_LASTINDEXRULE = "lastindexrule"; /** * Configuration key for the rule of objects to index. */ private static final String RULE_KEY = "rule"; /** * Configuration key for the attributes stored in the index. */ private static final String BOOSTED_ATTRIBUTES_KEY = "BOOSTEDATTRIBUTES"; /** * Configuration key for the attributes stored in the index. */ private static final String CONTAINED_ATTRIBUTES_KEY = "CONTAINEDATTRIBUTES"; /** * Configuration key for the attributes which are indexed. */ private static final String INDEXED_ATTRIBUTES_KEY = "INDEXEDATTRIBUTES"; /** * Configuration key defines if the index should be optimized. */ private static final String OPTIMIZE_KEY = "optimize"; /** * Configuration key for {@link #maxSegmentsString}. */ private static final String MAXSEGMENTS_KEY = "maxsegments"; /** * Configuration key to define if vectors are stored in the index or not. */ private static final String STORE_VECTORS_KEY = "storeVectors"; /** * Configuration key to define the size of a single batch * to index the files. * e.g. 100 means 100 files are indexes at once. */ private static final String BATCH_SIZE_KEY = "BATCHSIZE"; /** * TODO javadoc. */ private static final String CR_FIELD_KEY = "CRID"; /** * Configuration key to define which attribute is tested to decide if the * element is newer than the one in the index. */ public static final String TIMESTAMP_ATTR_KEY = "updateattribute"; /** * Constant for 1000. */ private static final int ONE_THOUSAND = 1000; /** * Default batch size is set to 1000 elements. */ private int batchSize = ONE_THOUSAND; /** * Attribute to check if the element is newer than the one in the index. * @see #TIMESTAMP_ATTR_KEY */ private String timestampattribute = ""; /** * Flag if TermVectors should be stored in the index or not. */ private boolean storeVectors = true; /** * Boostingmap. */ private HashMap<String, Float> boostvalue = new HashMap<String, Float>(); /** * Fills the boostvalue map with the according * values from "boostedattributes". * @param booststring booststring. */ private void fillBoostValues(final String booststring) { if (booststring != null) { try { String[] boostterms = booststring.split(","); for (String term : boostterms) { String[] t = term.split("\\^"); boostvalue.put(t[0], Float.parseFloat(t[1])); } } catch (Exception e) { log.error("Could not create boostvalues. Check your config! (" + booststring + ")", e); } } } /** * Index a single configured ContentRepository. * @param indexLocation TODO javadoc * @param config TODO javadoc * @throws CRException TODO javadoc */ @SuppressWarnings("unchecked") protected void indexCR(final IndexLocation indexLocation, final CRConfigUtil config) throws CRException { String crid = config.getName(); if (crid == null) { crid = this.identifyer; } fillBoostValues(config.getString(BOOSTED_ATTRIBUTES_KEY)); IndexAccessor indexAccessor = null; IndexWriter indexWriter = null; IndexReader indexReader = null; LuceneIndexUpdateChecker luceneIndexUpdateChecker = null; boolean finishedIndexJobSuccessfull = false; boolean finishedIndexJobWithError = false; try { indexLocation.checkLock(); Collection<CRResolvableBean> slice = null; try { status.setCurrentStatusString("Writer accquired. Starting" + "index job."); if (rp == null) { throw new CRException("FATAL ERROR", "RequestProcessor not available"); } String bsString = (String) config.get(BATCH_SIZE_KEY); int crBatchSize = batchSize; if (bsString != null) { try { crBatchSize = Integer.parseInt(bsString); } catch (NumberFormatException e) { log.error("The configured " + BATCH_SIZE_KEY + " for the Current CR" + " did not contain a parsable integer. ", e); } } // and get the current rule String rule = (String) config.get(RULE_KEY); if (rule == null) { rule = ""; } if (rule.length() == 0) { rule = "(1 == 1)"; } else { rule = "(" + rule + ")"; } List<ContentTransformer> transformerlist = ContentTransformer.getTransformerList(config); boolean create = true; if (indexLocation.isContainingIndex()) { create = false; log.debug("Index already exists."); } if (indexLocation instanceof LuceneIndexLocation) { luceneIndexUpdateChecker = new LuceneIndexUpdateChecker( (LuceneIndexLocation) indexLocation, CR_FIELD_KEY, crid, idAttribute); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } Collection<CRResolvableBean> objectsToIndex = null; //Clear Index and remove stale Documents //if (!create) { log.debug("Will do differential index."); try { CRRequest req = new CRRequest(); req.setRequestFilter(rule); req.set(CR_FIELD_KEY, crid); status .setCurrentStatusString("Get objects to update " + "in the index ..."); objectsToIndex = getObjectsToUpdate(req, rp, false, luceneIndexUpdateChecker); } catch (Exception e) { log.error("ERROR while cleaning index", e); } //} //Obtain accessor and writer after clean if (indexLocation instanceof LuceneIndexLocation) { indexAccessor = ((LuceneIndexLocation) indexLocation) .getAccessor(); indexWriter = indexAccessor.getWriter(); indexReader = indexAccessor.getReader(false); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } log.debug("Using rule: " + rule); // prepare the map of indexed/stored attributes Map<String, Boolean> attributes = new HashMap<String, Boolean>(); List<String> containedAttributes = IndexerUtil .getListFromString( config.getString(CONTAINED_ATTRIBUTES_KEY), ","); List<String> indexedAttributes = IndexerUtil.getListFromString( config.getString(INDEXED_ATTRIBUTES_KEY), ","); List<String> reverseAttributes = ((LuceneIndexLocation) indexLocation) .getReverseAttributes(); // first put all indexed attributes into the map for (String name : indexedAttributes) { attributes.put(name, Boolean.FALSE); } // now put all contained attributes for (String name : containedAttributes) { attributes.put(name, Boolean.TRUE); } // finally, put the "contentid" (always contained) attributes.put(idAttribute, Boolean.TRUE); if (objectsToIndex == null) { log.debug("Rule returned no objects to index. Skipping..."); return; } status.setObjectCount(objectsToIndex.size()); log.debug(" index job with " + objectsToIndex.size() + " objects to index."); // now get the first batch of objects from the collection // (remove them from the original collection) and index them slice = new Vector(crBatchSize); int sliceCounter = 0; status.setCurrentStatusString("Starting to index slices."); boolean interrupted = Thread.currentThread().isInterrupted(); for (Iterator<CRResolvableBean> iterator = objectsToIndex.iterator(); iterator.hasNext();) { CRResolvableBean obj = iterator.next(); slice.add(obj); iterator.remove(); sliceCounter++; if (Thread.currentThread().isInterrupted()) { interrupted = true; break; } if (sliceCounter == crBatchSize) { // index the current slice log.debug("Indexing slice with " + slice.size() + " objects."); indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); // clear the slice and reset the counter slice.clear(); sliceCounter = 0; } } if (!slice.isEmpty()) { // index the last slice indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); } if (!interrupted) { // Only Optimize the Index if the thread // has not been interrupted if (optimize) { log.debug("Executing optimize command."); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(); } finally { uc.stop(); } } else if (maxSegmentsString != null) { log.debug("Executing optimize command with max" + " segments: " + maxSegmentsString); int maxs = Integer.parseInt(maxSegmentsString); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(maxs); } finally { uc.stop(); } } } else { log.debug("Job has been interrupted and will now be closed." + " Missing objects " + "will be reindexed next run."); } finishedIndexJobSuccessfull = true; } catch (Exception ex) { log.error("Could not complete index run... indexed Objects: " + status.getObjectsDone() + ", trying to close index and remove lock.", ex); finishedIndexJobWithError = true; status.setError("Could not complete index run... indexed " + "Objects: " + status.getObjectsDone() + ", trying to close index and remove lock."); } finally { if (!finishedIndexJobSuccessfull && !finishedIndexJobWithError) { log.fatal("There seems to be a run time exception from this" + " index job.\nLast slice was: " + slice); } //Set status for job if it was not locked status.setCurrentStatusString("Finished job."); int objectCount = status.getObjectsDone(); log.debug("Indexed " + objectCount + " objects..."); if (indexAccessor != null && indexWriter != null) { indexAccessor.release(indexWriter); } - if (indexAccessor != null && indexWriter != null) { + if (indexAccessor != null && indexReader != null) { indexAccessor.release(indexReader, false); } if (objectCount > 0) { indexLocation.createReopenFile(); } EventManager.getInstance().fireEvent( new IndexingFinishedEvent(indexLocation)); } } catch (LockedIndexException ex) { log.debug("LOCKED INDEX DETECTED. TRYING AGAIN IN NEXT JOB."); if (this.indexLocation != null && !this.indexLocation.hasLockDetection()) { log.error("IT SEEMS THAT THE INDEX HAS UNEXPECTEDLY BEEN " + "LOCKED. TRYING TO REMOVE THE LOCK", ex); ((LuceneIndexLocation) this.indexLocation).forceRemoveLock(); } } catch (Exception ex) { log.debug("ERROR WHILE CHECKING LOCK", ex); } } /** * Index a single slice. * @param crid TODO javadoc * @param indexWriter TODO javadoc * @param indexReader * @param slice TODO javadoc * @param attributes TODO javadoc * @param rp TODO javadoc * @param create TODO javadoc * @param config TODO javadoc * @param transformerlist TODO javadoc * @param reverseattributes TODO javadoc * @throws CRException TODO javadoc * @throws IOException TODO javadoc */ private void indexSlice(final String crid, final IndexWriter indexWriter, final IndexReader indexReader, final Collection<CRResolvableBean> slice, final Map<String, Boolean> attributes, final RequestProcessor rp, final boolean create, final CRConfigUtil config, final List<ContentTransformer> transformerlist, final List<String> reverseattributes) throws CRException, IOException { // prefill all needed attributes UseCase uc = MonitorFactory.startUseCase("indexSlice(" + crid + ")"); try { CRRequest req = new CRRequest(); String[] prefillAttributes = attributes.keySet() .toArray(new String[0]); req.setAttributeArray(prefillAttributes); UseCase prefillCase = MonitorFactory .startUseCase("indexSlice(" + crid + ").prefillAttributes"); rp.fillAttributes(slice, req, idAttribute); prefillCase.stop(); for (Resolvable objectToIndex : slice) { CRResolvableBean bean = new CRResolvableBean(objectToIndex, prefillAttributes); UseCase bcase = MonitorFactory.startUseCase("indexSlice(" + crid + ").indexBean"); try { //CALL PRE INDEX PROCESSORS/TRANSFORMERS //TODO This could be optimized for multicore servers with //a map/reduce algorithm if (transformerlist != null) { for (ContentTransformer transformer : transformerlist) { try { if (transformer.match(bean)) { String msg = "TRANSFORMER: " + transformer.getTransformerKey() + "; BEAN: " + bean .get(idAttribute); status.setCurrentStatusString(msg); TR_LOG.debug(msg); transformer.processBeanWithMonitoring(bean, indexWriter); } } catch (Exception e) { //TODO Remember broken files log.error("Error while Transforming Contentbean" + "with id: " + bean.get(idAttribute) + " Transformer: " + transformer.getTransformerKey() + " " + transformer.getClass().getName(), e); } } } Term idTerm = new Term(idAttribute, bean.getString(idAttribute)); Document docToUpdate = getUniqueDocument(indexReader, idTerm, crid); if (!create && docToUpdate != null) { indexWriter.updateDocument(idTerm, getDocument( docToUpdate, bean, attributes, config, reverseattributes)); } else { indexWriter.addDocument(getDocument(null, bean, attributes, config, reverseattributes)); } } finally { bcase.stop(); } //Stop Indexing when thread has been interrupted if (Thread.currentThread().isInterrupted()) { break; } this.status.setObjectsDone(this.status.getObjectsDone() + 1); } } catch (Exception e) { throw new CRException(e); } finally { uc.stop(); } } /** * Fetch an unique document from the index. * @param indexReader reader. * @param idTerm term. * @param searchCRID crid. * @return document. */ private Document getUniqueDocument(final IndexReader indexReader, final Term idTerm, final String searchCRID) { try { TermDocs docs = indexReader.termDocs(idTerm); while (docs.next()) { Document doc = indexReader.document(docs.doc()); String crID = doc.get(CR_FIELD_KEY); if (crID != null && crID.equals(searchCRID)) { return doc; } } } catch (IOException e) { log.error("An error happend while fetching the document in the index.", e); } return null; } /** * Convert a resolvable to a Lucene Document. * @param doc lucene document to reuse (update) * @param resolvable Contains the resolvable to be indexed * @param attributes A map of attribute names, which values are true if the * attribute should be stored or fales if the attribute should only be * indexed. Only attributes configured in this map will be indexed * @param config The name of this config will be used as CRID * (ContentRepository Identifyer). The ID-Attribute should also be * configured in this config (usually contentid). * @param reverseattributes Attributes that should be indexed in reverse * order. This can be used to search faster for words ending with *ing. * @return Returns a Lucene Document, ready to be added to the index. */ private Document getDocument(final Document doc, final Resolvable resolvable, final Map<String, Boolean> attributes, final CRConfigUtil config, final List<String> reverseattributes) { Document newDoc; if (doc == null) { newDoc = new Document(); } else { newDoc = doc; } String crID = (String) config.getName(); if (crID != null) { newDoc.removeFields(CR_FIELD_KEY); //Add content repository identification newDoc.add(new Field(CR_FIELD_KEY, crID, Field.Store.YES, Field.Index.NOT_ANALYZED)); } if (!"".equals(timestampattribute)) { Object updateTimestampObject = resolvable.get(timestampattribute); if (updateTimestampObject == null) { log.error("Indexing with an updateattribute (" + timestampattribute + ") has been configured but the attribute is " + "not available in the current indexed object." + "If using the SQLRequestProcesser, remember to " + "configure the updateattribute column also in the " + "'columns' configuration parameter."); } else { String updateTimestamp = updateTimestampObject.toString(); if (updateTimestamp != null && !"".equals(updateTimestamp)) { newDoc.removeField(timestampAttribute); newDoc.add(new Field(timestampattribute, updateTimestamp.toString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); } } } for (Entry<String, Boolean> entry : attributes.entrySet()) { String attributeName = (String) entry.getKey(); boolean filled = (newDoc.get(attributeName) != null); Boolean storeField = (Boolean) entry.getValue(); Object value = resolvable.getProperty(attributeName); if (idAttribute.equalsIgnoreCase(attributeName) && !filled) { newDoc.add(new Field(idAttribute, value.toString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); } else if (value != null) { if (filled) { newDoc.removeField(attributeName); } Store storeFieldStore; if (storeField) { storeFieldStore = Store.YES; } else { storeFieldStore = Store.NO; } TermVector storeTermVector; if (storeVectors) { storeTermVector = TermVector.WITH_POSITIONS_OFFSETS; } else { storeTermVector = TermVector.NO; } if (value instanceof String || value instanceof Number) { Field f = new Field(attributeName, value.toString(), storeFieldStore, Field.Index.ANALYZED, storeTermVector); Float boostValue = boostvalue.get(attributeName); if (boostValue != null) { f.setBoost(boostValue); } newDoc.add(f); //ADD REVERSEATTRIBUTE IF NEEDED if (reverseattributes != null && reverseattributes.contains(attributeName)) { String reverseAttributeName = attributeName + LuceneAnalyzerFactory.REVERSE_ATTRIBUTE_SUFFIX; Field revField = new Field(reverseAttributeName, value.toString(), storeFieldStore, Field.Index.ANALYZED, storeTermVector); Float revBoostValue = boostvalue .get(reverseAttributeName); if (revBoostValue != null) { revField.setBoost(revBoostValue); } newDoc.add(revField); } } } } return newDoc; } }
true
true
protected void indexCR(final IndexLocation indexLocation, final CRConfigUtil config) throws CRException { String crid = config.getName(); if (crid == null) { crid = this.identifyer; } fillBoostValues(config.getString(BOOSTED_ATTRIBUTES_KEY)); IndexAccessor indexAccessor = null; IndexWriter indexWriter = null; IndexReader indexReader = null; LuceneIndexUpdateChecker luceneIndexUpdateChecker = null; boolean finishedIndexJobSuccessfull = false; boolean finishedIndexJobWithError = false; try { indexLocation.checkLock(); Collection<CRResolvableBean> slice = null; try { status.setCurrentStatusString("Writer accquired. Starting" + "index job."); if (rp == null) { throw new CRException("FATAL ERROR", "RequestProcessor not available"); } String bsString = (String) config.get(BATCH_SIZE_KEY); int crBatchSize = batchSize; if (bsString != null) { try { crBatchSize = Integer.parseInt(bsString); } catch (NumberFormatException e) { log.error("The configured " + BATCH_SIZE_KEY + " for the Current CR" + " did not contain a parsable integer. ", e); } } // and get the current rule String rule = (String) config.get(RULE_KEY); if (rule == null) { rule = ""; } if (rule.length() == 0) { rule = "(1 == 1)"; } else { rule = "(" + rule + ")"; } List<ContentTransformer> transformerlist = ContentTransformer.getTransformerList(config); boolean create = true; if (indexLocation.isContainingIndex()) { create = false; log.debug("Index already exists."); } if (indexLocation instanceof LuceneIndexLocation) { luceneIndexUpdateChecker = new LuceneIndexUpdateChecker( (LuceneIndexLocation) indexLocation, CR_FIELD_KEY, crid, idAttribute); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } Collection<CRResolvableBean> objectsToIndex = null; //Clear Index and remove stale Documents //if (!create) { log.debug("Will do differential index."); try { CRRequest req = new CRRequest(); req.setRequestFilter(rule); req.set(CR_FIELD_KEY, crid); status .setCurrentStatusString("Get objects to update " + "in the index ..."); objectsToIndex = getObjectsToUpdate(req, rp, false, luceneIndexUpdateChecker); } catch (Exception e) { log.error("ERROR while cleaning index", e); } //} //Obtain accessor and writer after clean if (indexLocation instanceof LuceneIndexLocation) { indexAccessor = ((LuceneIndexLocation) indexLocation) .getAccessor(); indexWriter = indexAccessor.getWriter(); indexReader = indexAccessor.getReader(false); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } log.debug("Using rule: " + rule); // prepare the map of indexed/stored attributes Map<String, Boolean> attributes = new HashMap<String, Boolean>(); List<String> containedAttributes = IndexerUtil .getListFromString( config.getString(CONTAINED_ATTRIBUTES_KEY), ","); List<String> indexedAttributes = IndexerUtil.getListFromString( config.getString(INDEXED_ATTRIBUTES_KEY), ","); List<String> reverseAttributes = ((LuceneIndexLocation) indexLocation) .getReverseAttributes(); // first put all indexed attributes into the map for (String name : indexedAttributes) { attributes.put(name, Boolean.FALSE); } // now put all contained attributes for (String name : containedAttributes) { attributes.put(name, Boolean.TRUE); } // finally, put the "contentid" (always contained) attributes.put(idAttribute, Boolean.TRUE); if (objectsToIndex == null) { log.debug("Rule returned no objects to index. Skipping..."); return; } status.setObjectCount(objectsToIndex.size()); log.debug(" index job with " + objectsToIndex.size() + " objects to index."); // now get the first batch of objects from the collection // (remove them from the original collection) and index them slice = new Vector(crBatchSize); int sliceCounter = 0; status.setCurrentStatusString("Starting to index slices."); boolean interrupted = Thread.currentThread().isInterrupted(); for (Iterator<CRResolvableBean> iterator = objectsToIndex.iterator(); iterator.hasNext();) { CRResolvableBean obj = iterator.next(); slice.add(obj); iterator.remove(); sliceCounter++; if (Thread.currentThread().isInterrupted()) { interrupted = true; break; } if (sliceCounter == crBatchSize) { // index the current slice log.debug("Indexing slice with " + slice.size() + " objects."); indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); // clear the slice and reset the counter slice.clear(); sliceCounter = 0; } } if (!slice.isEmpty()) { // index the last slice indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); } if (!interrupted) { // Only Optimize the Index if the thread // has not been interrupted if (optimize) { log.debug("Executing optimize command."); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(); } finally { uc.stop(); } } else if (maxSegmentsString != null) { log.debug("Executing optimize command with max" + " segments: " + maxSegmentsString); int maxs = Integer.parseInt(maxSegmentsString); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(maxs); } finally { uc.stop(); } } } else { log.debug("Job has been interrupted and will now be closed." + " Missing objects " + "will be reindexed next run."); } finishedIndexJobSuccessfull = true; } catch (Exception ex) { log.error("Could not complete index run... indexed Objects: " + status.getObjectsDone() + ", trying to close index and remove lock.", ex); finishedIndexJobWithError = true; status.setError("Could not complete index run... indexed " + "Objects: " + status.getObjectsDone() + ", trying to close index and remove lock."); } finally { if (!finishedIndexJobSuccessfull && !finishedIndexJobWithError) { log.fatal("There seems to be a run time exception from this" + " index job.\nLast slice was: " + slice); } //Set status for job if it was not locked status.setCurrentStatusString("Finished job."); int objectCount = status.getObjectsDone(); log.debug("Indexed " + objectCount + " objects..."); if (indexAccessor != null && indexWriter != null) { indexAccessor.release(indexWriter); } if (indexAccessor != null && indexWriter != null) { indexAccessor.release(indexReader, false); } if (objectCount > 0) { indexLocation.createReopenFile(); } EventManager.getInstance().fireEvent( new IndexingFinishedEvent(indexLocation)); } } catch (LockedIndexException ex) { log.debug("LOCKED INDEX DETECTED. TRYING AGAIN IN NEXT JOB."); if (this.indexLocation != null && !this.indexLocation.hasLockDetection()) { log.error("IT SEEMS THAT THE INDEX HAS UNEXPECTEDLY BEEN " + "LOCKED. TRYING TO REMOVE THE LOCK", ex); ((LuceneIndexLocation) this.indexLocation).forceRemoveLock(); } } catch (Exception ex) { log.debug("ERROR WHILE CHECKING LOCK", ex); } }
protected void indexCR(final IndexLocation indexLocation, final CRConfigUtil config) throws CRException { String crid = config.getName(); if (crid == null) { crid = this.identifyer; } fillBoostValues(config.getString(BOOSTED_ATTRIBUTES_KEY)); IndexAccessor indexAccessor = null; IndexWriter indexWriter = null; IndexReader indexReader = null; LuceneIndexUpdateChecker luceneIndexUpdateChecker = null; boolean finishedIndexJobSuccessfull = false; boolean finishedIndexJobWithError = false; try { indexLocation.checkLock(); Collection<CRResolvableBean> slice = null; try { status.setCurrentStatusString("Writer accquired. Starting" + "index job."); if (rp == null) { throw new CRException("FATAL ERROR", "RequestProcessor not available"); } String bsString = (String) config.get(BATCH_SIZE_KEY); int crBatchSize = batchSize; if (bsString != null) { try { crBatchSize = Integer.parseInt(bsString); } catch (NumberFormatException e) { log.error("The configured " + BATCH_SIZE_KEY + " for the Current CR" + " did not contain a parsable integer. ", e); } } // and get the current rule String rule = (String) config.get(RULE_KEY); if (rule == null) { rule = ""; } if (rule.length() == 0) { rule = "(1 == 1)"; } else { rule = "(" + rule + ")"; } List<ContentTransformer> transformerlist = ContentTransformer.getTransformerList(config); boolean create = true; if (indexLocation.isContainingIndex()) { create = false; log.debug("Index already exists."); } if (indexLocation instanceof LuceneIndexLocation) { luceneIndexUpdateChecker = new LuceneIndexUpdateChecker( (LuceneIndexLocation) indexLocation, CR_FIELD_KEY, crid, idAttribute); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } Collection<CRResolvableBean> objectsToIndex = null; //Clear Index and remove stale Documents //if (!create) { log.debug("Will do differential index."); try { CRRequest req = new CRRequest(); req.setRequestFilter(rule); req.set(CR_FIELD_KEY, crid); status .setCurrentStatusString("Get objects to update " + "in the index ..."); objectsToIndex = getObjectsToUpdate(req, rp, false, luceneIndexUpdateChecker); } catch (Exception e) { log.error("ERROR while cleaning index", e); } //} //Obtain accessor and writer after clean if (indexLocation instanceof LuceneIndexLocation) { indexAccessor = ((LuceneIndexLocation) indexLocation) .getAccessor(); indexWriter = indexAccessor.getWriter(); indexReader = indexAccessor.getReader(false); } else { log.error("IndexLocation is not created for Lucene. " + "Using the " + CRLuceneIndexJob.class.getName() + " requires that you use the " + LuceneIndexLocation.class.getName() + ". You can configure another Job by setting the " + IndexLocation.UPDATEJOBCLASS_KEY + " key in your config."); throw new CRException( new CRError("Error", "IndexLocation is not created for Lucene.")); } log.debug("Using rule: " + rule); // prepare the map of indexed/stored attributes Map<String, Boolean> attributes = new HashMap<String, Boolean>(); List<String> containedAttributes = IndexerUtil .getListFromString( config.getString(CONTAINED_ATTRIBUTES_KEY), ","); List<String> indexedAttributes = IndexerUtil.getListFromString( config.getString(INDEXED_ATTRIBUTES_KEY), ","); List<String> reverseAttributes = ((LuceneIndexLocation) indexLocation) .getReverseAttributes(); // first put all indexed attributes into the map for (String name : indexedAttributes) { attributes.put(name, Boolean.FALSE); } // now put all contained attributes for (String name : containedAttributes) { attributes.put(name, Boolean.TRUE); } // finally, put the "contentid" (always contained) attributes.put(idAttribute, Boolean.TRUE); if (objectsToIndex == null) { log.debug("Rule returned no objects to index. Skipping..."); return; } status.setObjectCount(objectsToIndex.size()); log.debug(" index job with " + objectsToIndex.size() + " objects to index."); // now get the first batch of objects from the collection // (remove them from the original collection) and index them slice = new Vector(crBatchSize); int sliceCounter = 0; status.setCurrentStatusString("Starting to index slices."); boolean interrupted = Thread.currentThread().isInterrupted(); for (Iterator<CRResolvableBean> iterator = objectsToIndex.iterator(); iterator.hasNext();) { CRResolvableBean obj = iterator.next(); slice.add(obj); iterator.remove(); sliceCounter++; if (Thread.currentThread().isInterrupted()) { interrupted = true; break; } if (sliceCounter == crBatchSize) { // index the current slice log.debug("Indexing slice with " + slice.size() + " objects."); indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); // clear the slice and reset the counter slice.clear(); sliceCounter = 0; } } if (!slice.isEmpty()) { // index the last slice indexSlice(crid, indexWriter, indexReader, slice, attributes, rp, create, config, transformerlist, reverseAttributes); } if (!interrupted) { // Only Optimize the Index if the thread // has not been interrupted if (optimize) { log.debug("Executing optimize command."); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(); } finally { uc.stop(); } } else if (maxSegmentsString != null) { log.debug("Executing optimize command with max" + " segments: " + maxSegmentsString); int maxs = Integer.parseInt(maxSegmentsString); UseCase uc = MonitorFactory.startUseCase("optimize(" + crid + ")"); try { indexWriter.optimize(maxs); } finally { uc.stop(); } } } else { log.debug("Job has been interrupted and will now be closed." + " Missing objects " + "will be reindexed next run."); } finishedIndexJobSuccessfull = true; } catch (Exception ex) { log.error("Could not complete index run... indexed Objects: " + status.getObjectsDone() + ", trying to close index and remove lock.", ex); finishedIndexJobWithError = true; status.setError("Could not complete index run... indexed " + "Objects: " + status.getObjectsDone() + ", trying to close index and remove lock."); } finally { if (!finishedIndexJobSuccessfull && !finishedIndexJobWithError) { log.fatal("There seems to be a run time exception from this" + " index job.\nLast slice was: " + slice); } //Set status for job if it was not locked status.setCurrentStatusString("Finished job."); int objectCount = status.getObjectsDone(); log.debug("Indexed " + objectCount + " objects..."); if (indexAccessor != null && indexWriter != null) { indexAccessor.release(indexWriter); } if (indexAccessor != null && indexReader != null) { indexAccessor.release(indexReader, false); } if (objectCount > 0) { indexLocation.createReopenFile(); } EventManager.getInstance().fireEvent( new IndexingFinishedEvent(indexLocation)); } } catch (LockedIndexException ex) { log.debug("LOCKED INDEX DETECTED. TRYING AGAIN IN NEXT JOB."); if (this.indexLocation != null && !this.indexLocation.hasLockDetection()) { log.error("IT SEEMS THAT THE INDEX HAS UNEXPECTEDLY BEEN " + "LOCKED. TRYING TO REMOVE THE LOCK", ex); ((LuceneIndexLocation) this.indexLocation).forceRemoveLock(); } } catch (Exception ex) { log.debug("ERROR WHILE CHECKING LOCK", ex); } }
diff --git a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/UpdateLevelVisualSystem.java b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/UpdateLevelVisualSystem.java index a282a3a..f752317 100644 --- a/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/UpdateLevelVisualSystem.java +++ b/game/src/main/java/org/geekygoblin/nedetlesmaki/game/systems/UpdateLevelVisualSystem.java @@ -1,352 +1,352 @@ /* * Copyright © 2013, Pierre Marijon <[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 X 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 org.geekygoblin.nedetlesmaki.game.systems; import com.google.inject.Inject; import java.util.ArrayList; import com.artemis.ComponentMapper; import com.artemis.Entity; import com.artemis.annotations.Mapper; import com.artemis.systems.VoidEntitySystem; import im.bci.jnuit.animation.IAnimationCollection; import im.bci.jnuit.animation.PlayMode; import org.geekygoblin.nedetlesmaki.game.manager.EntityIndexManager; import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Plate; import org.geekygoblin.nedetlesmaki.game.components.visual.Sprite; import org.geekygoblin.nedetlesmaki.game.components.visual.SpritePuppetControls; import org.geekygoblin.nedetlesmaki.game.components.gamesystems.Position; import org.geekygoblin.nedetlesmaki.game.constants.AnimationType; import im.bci.jnuit.lwjgl.assets.IAssets; import org.geekygoblin.nedetlesmaki.game.utils.Mouvement; import org.lwjgl.util.vector.Vector3f; /** * * @author natir */ public class UpdateLevelVisualSystem extends VoidEntitySystem { @Mapper ComponentMapper<Sprite> spriteMapper; @Mapper ComponentMapper<Plate> plateMapper; @Mapper ComponentMapper<Position> positionMapper; @Mapper ComponentMapper<SpritePuppetControls> controlsMapper; private final IAssets assets; private int nbIndexSaved; private final EntityIndexManager index; @Inject public UpdateLevelVisualSystem(IAssets assets, EntityIndexManager indexSystem) { this.assets = assets; this.nbIndexSaved = 0; this.index = indexSystem; } @Override protected void processSystem() { ArrayList<Mouvement> rm = index.getRemove(); if (rm != null) { for (int i = 0; i != rm.size(); i++) { for (int j = 0; j != rm.get(i).size(); j++) { this.moveSprite(rm.get(i).getEntity(), rm.get(i).getPosition(j), rm.get(i).getAnimation(j), rm.get(i).getBeforeWait(j), rm.get(i).getAnimationTime(j)); } } this.index.setRemove(null); } if (index.sizeOfStack() > nbIndexSaved) { ArrayList<Mouvement> change = this.index.getChangement(); if (change != null) { for (int i = 0; i != change.size(); i++) { for (int j = 0; j != change.get(i).size(); j++) { this.moveSprite(change.get(i).getEntity(), change.get(i).getPosition(j), change.get(i).getAnimation(j), change.get(i).getBeforeWait(j), change.get(i).getAnimationTime(j)); } } } } nbIndexSaved = index.sizeOfStack(); } private void moveSprite(Entity e, Position diff, AnimationType a, float waitBefore, float animationTime) { Sprite sprite = e.getComponent(Sprite.class); SpritePuppetControls updatable = this.controlsMapper.getSafe(e); if (updatable == null) { updatable = new SpritePuppetControls(sprite); } IAnimationCollection nedAnim = this.assets.getAnimations("ned.nanim.gz"); IAnimationCollection makiAnim = this.assets.getAnimations("maki.nanim.gz"); IAnimationCollection boxAnim = this.assets.getAnimations("box.nanim.gz"); IAnimationCollection stairsAnim = this.assets.getAnimations("stairs.nanim.gz"); IAnimationCollection makiAnimBoost = this.assets.getAnimations("blue_maki_boost.nanim.gz"); IAnimationCollection nedAnimFly = this.assets.getAnimations("fly.nanim.gz"); if (a == AnimationType.no) { updatable.waitDuring(waitBefore) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_right) { updatable.startAnimation(nedAnim.getAnimationByName("walk_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_left) { updatable.startAnimation(nedAnim.getAnimationByName("walk_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_down) { updatable.startAnimation(nedAnim.getAnimationByName("walk_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_up) { updatable.startAnimation(nedAnim.getAnimationByName("walk_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_right) { updatable.startAnimation(nedAnim.getAnimationByName("push_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_left) { updatable.startAnimation(nedAnim.getAnimationByName("push_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_down) { updatable.startAnimation(nedAnim.getAnimationByName("push_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_up) { updatable.startAnimation(nedAnim.getAnimationByName("push_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.box_destroy) { System.out.println(waitBefore); updatable.waitDuring(waitBefore) .startAnimation(boxAnim.getAnimationByName("destroy"), PlayMode.ONCE) .waitAnimation(); this.index.disabled(e); } else if (a == AnimationType.box_create) { this.index.enabled(e); updatable.startAnimation(boxAnim.getAnimationByName("create"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_green_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_orange_one) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_blue_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_green_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_orange_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_blue_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_blue_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.disable_entity) { e.disable(); } else if (a == AnimationType.stairs_open_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.boost_start_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() - .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) - .stopAnimation(); + .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_up"), PlayMode.ONCE) + .waitAnimation(); } else if (a == AnimationType.boost_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() - .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) - .stopAnimation(); + .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_down"), PlayMode.ONCE) + .waitAnimation(); } else if (a == AnimationType.boost_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() - .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) - .stopAnimation(); + .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_left"), PlayMode.ONCE) + .waitAnimation(); } else if (a == AnimationType.boost_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() - .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) - .stopAnimation(); + .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_right"), PlayMode.ONCE) + .waitAnimation(); } else if (a == AnimationType.boost_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_start_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } e.addComponent(updatable); e.changedInWorld(); } }
false
true
private void moveSprite(Entity e, Position diff, AnimationType a, float waitBefore, float animationTime) { Sprite sprite = e.getComponent(Sprite.class); SpritePuppetControls updatable = this.controlsMapper.getSafe(e); if (updatable == null) { updatable = new SpritePuppetControls(sprite); } IAnimationCollection nedAnim = this.assets.getAnimations("ned.nanim.gz"); IAnimationCollection makiAnim = this.assets.getAnimations("maki.nanim.gz"); IAnimationCollection boxAnim = this.assets.getAnimations("box.nanim.gz"); IAnimationCollection stairsAnim = this.assets.getAnimations("stairs.nanim.gz"); IAnimationCollection makiAnimBoost = this.assets.getAnimations("blue_maki_boost.nanim.gz"); IAnimationCollection nedAnimFly = this.assets.getAnimations("fly.nanim.gz"); if (a == AnimationType.no) { updatable.waitDuring(waitBefore) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_right) { updatable.startAnimation(nedAnim.getAnimationByName("walk_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_left) { updatable.startAnimation(nedAnim.getAnimationByName("walk_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_down) { updatable.startAnimation(nedAnim.getAnimationByName("walk_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_up) { updatable.startAnimation(nedAnim.getAnimationByName("walk_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_right) { updatable.startAnimation(nedAnim.getAnimationByName("push_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_left) { updatable.startAnimation(nedAnim.getAnimationByName("push_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_down) { updatable.startAnimation(nedAnim.getAnimationByName("push_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_up) { updatable.startAnimation(nedAnim.getAnimationByName("push_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.box_destroy) { System.out.println(waitBefore); updatable.waitDuring(waitBefore) .startAnimation(boxAnim.getAnimationByName("destroy"), PlayMode.ONCE) .waitAnimation(); this.index.disabled(e); } else if (a == AnimationType.box_create) { this.index.enabled(e); updatable.startAnimation(boxAnim.getAnimationByName("create"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_green_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_orange_one) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_blue_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_green_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_orange_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_blue_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_blue_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.disable_entity) { e.disable(); } else if (a == AnimationType.stairs_open_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.boost_start_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .stopAnimation(); } else if (a == AnimationType.boost_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .stopAnimation(); } else if (a == AnimationType.boost_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .stopAnimation(); } else if (a == AnimationType.boost_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .stopAnimation(); } else if (a == AnimationType.boost_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_start_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } e.addComponent(updatable); e.changedInWorld(); }
private void moveSprite(Entity e, Position diff, AnimationType a, float waitBefore, float animationTime) { Sprite sprite = e.getComponent(Sprite.class); SpritePuppetControls updatable = this.controlsMapper.getSafe(e); if (updatable == null) { updatable = new SpritePuppetControls(sprite); } IAnimationCollection nedAnim = this.assets.getAnimations("ned.nanim.gz"); IAnimationCollection makiAnim = this.assets.getAnimations("maki.nanim.gz"); IAnimationCollection boxAnim = this.assets.getAnimations("box.nanim.gz"); IAnimationCollection stairsAnim = this.assets.getAnimations("stairs.nanim.gz"); IAnimationCollection makiAnimBoost = this.assets.getAnimations("blue_maki_boost.nanim.gz"); IAnimationCollection nedAnimFly = this.assets.getAnimations("fly.nanim.gz"); if (a == AnimationType.no) { updatable.waitDuring(waitBefore) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_right) { updatable.startAnimation(nedAnim.getAnimationByName("walk_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_left) { updatable.startAnimation(nedAnim.getAnimationByName("walk_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_down) { updatable.startAnimation(nedAnim.getAnimationByName("walk_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_up) { updatable.startAnimation(nedAnim.getAnimationByName("walk_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_right) { updatable.startAnimation(nedAnim.getAnimationByName("push_right")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_left) { updatable.startAnimation(nedAnim.getAnimationByName("push_left")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_down) { updatable.startAnimation(nedAnim.getAnimationByName("push_down")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.ned_push_up) { updatable.startAnimation(nedAnim.getAnimationByName("push_up")) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.box_destroy) { System.out.println(waitBefore); updatable.waitDuring(waitBefore) .startAnimation(boxAnim.getAnimationByName("destroy"), PlayMode.ONCE) .waitAnimation(); this.index.disabled(e); } else if (a == AnimationType.box_create) { this.index.enabled(e); updatable.startAnimation(boxAnim.getAnimationByName("create"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_green_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_orange_one) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_blue_one) { updatable.moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .startAnimation(makiAnim.getAnimationByName("maki_blue_one"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.maki_green_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_green_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_orange_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_orange_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.maki_blue_out) { updatable.startAnimation(makiAnim.getAnimationByName("maki_blue_out"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.disable_entity) { e.disable(); } else if (a == AnimationType.stairs_open_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_open_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_open"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_up) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_up_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_down) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_down_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_left) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_left_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.stairs_close_right) { updatable.waitDuring(waitBefore) .startAnimation(stairsAnim.getAnimationByName("stairs_right_close"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime); } else if (a == AnimationType.boost_start_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_start_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.boost_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_up"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.boost_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_down"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.boost_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_left"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.boost_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation() .startAnimation(makiAnimBoost.getAnimationByName("boost_clean_right"), PlayMode.ONCE) .waitAnimation(); } else if (a == AnimationType.boost_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.boost_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(makiAnimBoost.getAnimationByName("boost_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_start_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_start_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_start_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_up"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_down"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_left"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_stop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_stop_right"), PlayMode.ONCE) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .waitAnimation(); } else if (a == AnimationType.fly_loop_up) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_up"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_down) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_down"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_left) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_left"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } else if (a == AnimationType.fly_loop_right) { updatable.waitDuring(waitBefore) .startAnimation(nedAnimFly.getAnimationByName("fly_loop_right"), PlayMode.LOOP) .moveToRelative(new Vector3f(diff.getY(), diff.getX(), 0), animationTime) .stopAnimation(); } e.addComponent(updatable); e.changedInWorld(); }
diff --git a/topcat/src/main/uk/ac/starlink/topcat/plot2/CubeAxisController.java b/topcat/src/main/uk/ac/starlink/topcat/plot2/CubeAxisController.java index b8065caa8..4bb57f633 100644 --- a/topcat/src/main/uk/ac/starlink/topcat/plot2/CubeAxisController.java +++ b/topcat/src/main/uk/ac/starlink/topcat/plot2/CubeAxisController.java @@ -1,194 +1,196 @@ package uk.ac.starlink.topcat.plot2; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import uk.ac.starlink.ttools.plot2.SurfaceFactory; import uk.ac.starlink.ttools.plot2.config.ConfigKey; import uk.ac.starlink.ttools.plot2.config.ConfigMap; import uk.ac.starlink.ttools.plot2.config.StyleKeys; import uk.ac.starlink.ttools.plot2.geom.CubeAspect; import uk.ac.starlink.ttools.plot2.geom.CubeSurfaceFactory; /** * Axis control for cube plot. * This operates in two modes, one isotropic (with geometry specified * using spherical polar coordinates) and one at least potentially * anisotropic (with geometry specified using Cartesian coordinates). * Which to use is specified at construction time. * * @author Mark Taylor * @since 14 Mar 2013 */ public class CubeAxisController extends CartesianAxisController<CubeSurfaceFactory.Profile,CubeAspect> { private final boolean isIso_; private CubeAspect oldAspect_; /** * Constructor. * * @param isIso true for isotropic, false for anisotropic * @param stack plot control stack */ public CubeAxisController( boolean isIso, ControlStack stack ) { super( new CubeSurfaceFactory( isIso ), createAxisLabelKeys(), stack ); isIso_ = isIso; final SurfaceFactory<CubeSurfaceFactory.Profile,CubeAspect> surfFact = getSurfaceFactory(); ConfigControl mainControl = getMainControl(); /* Log/flip config tab - only makes sense for anisotropic mode. */ if ( ! isIso ) { mainControl.addSpecifierTab( "Coords", new ConfigSpecifier( new ConfigKey[] { CubeSurfaceFactory.XLOG_KEY, CubeSurfaceFactory.YLOG_KEY, CubeSurfaceFactory.ZLOG_KEY, CubeSurfaceFactory.XFLIP_KEY, CubeSurfaceFactory.YFLIP_KEY, CubeSurfaceFactory.ZFLIP_KEY, } ) ); } /* Navigator tab. */ addNavigatorTab(); /* Provide the aspect configuration in two separate panels. * Either can reset the whole aspect, but each takes part of the * state from the existing aspect so that adjusting the controls * on one panel does not pull in the current values set on the other, * which might not reflect the current visible state. */ final ConfigKey<?>[] rangeKeys = isIso ? new ConfigKey<?>[] { CubeSurfaceFactory.SCALE_KEY, CubeSurfaceFactory.XC_KEY, CubeSurfaceFactory.YC_KEY, CubeSurfaceFactory.ZC_KEY, } : new ConfigKey<?>[] { CubeSurfaceFactory.XMIN_KEY, CubeSurfaceFactory.XMAX_KEY, CubeSurfaceFactory.XSUBRANGE_KEY, CubeSurfaceFactory.YMIN_KEY, CubeSurfaceFactory.YMAX_KEY, CubeSurfaceFactory.YSUBRANGE_KEY, CubeSurfaceFactory.ZMIN_KEY, CubeSurfaceFactory.ZMAX_KEY, CubeSurfaceFactory.ZSUBRANGE_KEY, }; final ConfigKey<?>[] viewKeys = new ConfigKey<?>[] { CubeSurfaceFactory.PHI_KEY, CubeSurfaceFactory.THETA_KEY, CubeSurfaceFactory.ZOOM_KEY, CubeSurfaceFactory.XOFF_KEY, CubeSurfaceFactory.YOFF_KEY, }; ConfigSpecifier rangeSpecifier = new ConfigSpecifier( rangeKeys ) { @Override public ConfigMap getSpecifiedValue() { ConfigMap c = super.getSpecifiedValue(); CubeAspect asp = oldAspect_; if ( asp != null ) { c.put( CubeSurfaceFactory.ROTMAT_KEY, asp.getRotation() ); c.put( CubeSurfaceFactory.ZOOM_KEY, asp.getZoom() ); c.put( CubeSurfaceFactory.XOFF_KEY, asp.getOffsetX() ); c.put( CubeSurfaceFactory.YOFF_KEY, asp.getOffsetY() ); } return c; } }; addAspectConfigTab( "Range", rangeSpecifier ); ConfigSpecifier viewSpecifier = new ConfigSpecifier( viewKeys ); ActionSpecifierPanel viewPanel = new ActionSpecifierPanel( viewSpecifier ) { protected void doSubmit( ActionEvent evt ) { if ( oldAspect_ != null ) { ConfigMap config = super.getSpecifiedValue(); double[][] limits = oldAspect_.getLimits(); double[] rot = CubeSurfaceFactory.getRotation( config ); double zoom = config.get( CubeSurfaceFactory.ZOOM_KEY ); double xoff = config.get( CubeSurfaceFactory.XOFF_KEY ); double yoff = config.get( CubeSurfaceFactory.YOFF_KEY ); CubeAspect aspect = new CubeAspect( limits[ 0 ], limits[ 1 ], limits[ 2 ], rot, zoom, xoff, yoff ); setAspect( aspect ); } } }; viewPanel.addActionListener( getActionForwarder() ); mainControl.addControlTab( "View", viewPanel.getComponent(), true ); /* Grid config tab. */ List<ConfigKey> gridKeyList = new ArrayList<ConfigKey>(); gridKeyList.add( CubeSurfaceFactory.FRAME_KEY ); gridKeyList.add( StyleKeys.MINOR_TICKS ); if ( isIso ) { gridKeyList.add( CubeSurfaceFactory.ISOCROWD_KEY ); } else { gridKeyList.addAll( Arrays.asList( new ConfigKey[] { CubeSurfaceFactory.XCROWD_KEY, CubeSurfaceFactory.YCROWD_KEY, CubeSurfaceFactory.ZCROWD_KEY, } ) ); } gridKeyList.add( StyleKeys.GRID_ANTIALIAS ); mainControl.addSpecifierTab( "Grid", new ConfigSpecifier( gridKeyList .toArray( new ConfigKey[ 0 ] ) ) ); /* Labels config tab. */ - addLabelsTab(); + if ( ! isIso ) { + addLabelsTab(); + } /* Font config tab. */ mainControl.addSpecifierTab( "Font", new ConfigSpecifier( StyleKeys.CAPTIONER .getKeys() ) ); assert assertHasKeys( surfFact.getProfileKeys() ); } @Override public void setAspect( CubeAspect aspect ) { /* Save last aspect for later use. */ if ( aspect != null ) { oldAspect_ = aspect; } super.setAspect( aspect ); } @Override public ConfigMap getConfig() { ConfigMap config = super.getConfig(); if ( isIso_ ) { config.put( CubeSurfaceFactory.XLOG_KEY, false ); config.put( CubeSurfaceFactory.YLOG_KEY, false ); config.put( CubeSurfaceFactory.ZLOG_KEY, false ); config.put( CubeSurfaceFactory.XFLIP_KEY, false ); config.put( CubeSurfaceFactory.YFLIP_KEY, false ); config.put( CubeSurfaceFactory.ZFLIP_KEY, false ); } return config; } @Override protected boolean logChanged( CubeSurfaceFactory.Profile prof1, CubeSurfaceFactory.Profile prof2 ) { return ! Arrays.equals( prof1.getLogFlags(), prof2.getLogFlags() ); } private static ConfigKey<String>[] createAxisLabelKeys() { List<ConfigKey<String>> list = new ArrayList<ConfigKey<String>>(); list.add( CubeSurfaceFactory.XLABEL_KEY ); list.add( CubeSurfaceFactory.YLABEL_KEY ); list.add( CubeSurfaceFactory.ZLABEL_KEY ); @SuppressWarnings("unchecked") ConfigKey<String>[] keys = list.toArray( new ConfigKey[ 0 ] ); return keys; } }
true
true
public CubeAxisController( boolean isIso, ControlStack stack ) { super( new CubeSurfaceFactory( isIso ), createAxisLabelKeys(), stack ); isIso_ = isIso; final SurfaceFactory<CubeSurfaceFactory.Profile,CubeAspect> surfFact = getSurfaceFactory(); ConfigControl mainControl = getMainControl(); /* Log/flip config tab - only makes sense for anisotropic mode. */ if ( ! isIso ) { mainControl.addSpecifierTab( "Coords", new ConfigSpecifier( new ConfigKey[] { CubeSurfaceFactory.XLOG_KEY, CubeSurfaceFactory.YLOG_KEY, CubeSurfaceFactory.ZLOG_KEY, CubeSurfaceFactory.XFLIP_KEY, CubeSurfaceFactory.YFLIP_KEY, CubeSurfaceFactory.ZFLIP_KEY, } ) ); } /* Navigator tab. */ addNavigatorTab(); /* Provide the aspect configuration in two separate panels. * Either can reset the whole aspect, but each takes part of the * state from the existing aspect so that adjusting the controls * on one panel does not pull in the current values set on the other, * which might not reflect the current visible state. */ final ConfigKey<?>[] rangeKeys = isIso ? new ConfigKey<?>[] { CubeSurfaceFactory.SCALE_KEY, CubeSurfaceFactory.XC_KEY, CubeSurfaceFactory.YC_KEY, CubeSurfaceFactory.ZC_KEY, } : new ConfigKey<?>[] { CubeSurfaceFactory.XMIN_KEY, CubeSurfaceFactory.XMAX_KEY, CubeSurfaceFactory.XSUBRANGE_KEY, CubeSurfaceFactory.YMIN_KEY, CubeSurfaceFactory.YMAX_KEY, CubeSurfaceFactory.YSUBRANGE_KEY, CubeSurfaceFactory.ZMIN_KEY, CubeSurfaceFactory.ZMAX_KEY, CubeSurfaceFactory.ZSUBRANGE_KEY, }; final ConfigKey<?>[] viewKeys = new ConfigKey<?>[] { CubeSurfaceFactory.PHI_KEY, CubeSurfaceFactory.THETA_KEY, CubeSurfaceFactory.ZOOM_KEY, CubeSurfaceFactory.XOFF_KEY, CubeSurfaceFactory.YOFF_KEY, }; ConfigSpecifier rangeSpecifier = new ConfigSpecifier( rangeKeys ) { @Override public ConfigMap getSpecifiedValue() { ConfigMap c = super.getSpecifiedValue(); CubeAspect asp = oldAspect_; if ( asp != null ) { c.put( CubeSurfaceFactory.ROTMAT_KEY, asp.getRotation() ); c.put( CubeSurfaceFactory.ZOOM_KEY, asp.getZoom() ); c.put( CubeSurfaceFactory.XOFF_KEY, asp.getOffsetX() ); c.put( CubeSurfaceFactory.YOFF_KEY, asp.getOffsetY() ); } return c; } }; addAspectConfigTab( "Range", rangeSpecifier ); ConfigSpecifier viewSpecifier = new ConfigSpecifier( viewKeys ); ActionSpecifierPanel viewPanel = new ActionSpecifierPanel( viewSpecifier ) { protected void doSubmit( ActionEvent evt ) { if ( oldAspect_ != null ) { ConfigMap config = super.getSpecifiedValue(); double[][] limits = oldAspect_.getLimits(); double[] rot = CubeSurfaceFactory.getRotation( config ); double zoom = config.get( CubeSurfaceFactory.ZOOM_KEY ); double xoff = config.get( CubeSurfaceFactory.XOFF_KEY ); double yoff = config.get( CubeSurfaceFactory.YOFF_KEY ); CubeAspect aspect = new CubeAspect( limits[ 0 ], limits[ 1 ], limits[ 2 ], rot, zoom, xoff, yoff ); setAspect( aspect ); } } }; viewPanel.addActionListener( getActionForwarder() ); mainControl.addControlTab( "View", viewPanel.getComponent(), true ); /* Grid config tab. */ List<ConfigKey> gridKeyList = new ArrayList<ConfigKey>(); gridKeyList.add( CubeSurfaceFactory.FRAME_KEY ); gridKeyList.add( StyleKeys.MINOR_TICKS ); if ( isIso ) { gridKeyList.add( CubeSurfaceFactory.ISOCROWD_KEY ); } else { gridKeyList.addAll( Arrays.asList( new ConfigKey[] { CubeSurfaceFactory.XCROWD_KEY, CubeSurfaceFactory.YCROWD_KEY, CubeSurfaceFactory.ZCROWD_KEY, } ) ); } gridKeyList.add( StyleKeys.GRID_ANTIALIAS ); mainControl.addSpecifierTab( "Grid", new ConfigSpecifier( gridKeyList .toArray( new ConfigKey[ 0 ] ) ) ); /* Labels config tab. */ addLabelsTab(); /* Font config tab. */ mainControl.addSpecifierTab( "Font", new ConfigSpecifier( StyleKeys.CAPTIONER .getKeys() ) ); assert assertHasKeys( surfFact.getProfileKeys() ); }
public CubeAxisController( boolean isIso, ControlStack stack ) { super( new CubeSurfaceFactory( isIso ), createAxisLabelKeys(), stack ); isIso_ = isIso; final SurfaceFactory<CubeSurfaceFactory.Profile,CubeAspect> surfFact = getSurfaceFactory(); ConfigControl mainControl = getMainControl(); /* Log/flip config tab - only makes sense for anisotropic mode. */ if ( ! isIso ) { mainControl.addSpecifierTab( "Coords", new ConfigSpecifier( new ConfigKey[] { CubeSurfaceFactory.XLOG_KEY, CubeSurfaceFactory.YLOG_KEY, CubeSurfaceFactory.ZLOG_KEY, CubeSurfaceFactory.XFLIP_KEY, CubeSurfaceFactory.YFLIP_KEY, CubeSurfaceFactory.ZFLIP_KEY, } ) ); } /* Navigator tab. */ addNavigatorTab(); /* Provide the aspect configuration in two separate panels. * Either can reset the whole aspect, but each takes part of the * state from the existing aspect so that adjusting the controls * on one panel does not pull in the current values set on the other, * which might not reflect the current visible state. */ final ConfigKey<?>[] rangeKeys = isIso ? new ConfigKey<?>[] { CubeSurfaceFactory.SCALE_KEY, CubeSurfaceFactory.XC_KEY, CubeSurfaceFactory.YC_KEY, CubeSurfaceFactory.ZC_KEY, } : new ConfigKey<?>[] { CubeSurfaceFactory.XMIN_KEY, CubeSurfaceFactory.XMAX_KEY, CubeSurfaceFactory.XSUBRANGE_KEY, CubeSurfaceFactory.YMIN_KEY, CubeSurfaceFactory.YMAX_KEY, CubeSurfaceFactory.YSUBRANGE_KEY, CubeSurfaceFactory.ZMIN_KEY, CubeSurfaceFactory.ZMAX_KEY, CubeSurfaceFactory.ZSUBRANGE_KEY, }; final ConfigKey<?>[] viewKeys = new ConfigKey<?>[] { CubeSurfaceFactory.PHI_KEY, CubeSurfaceFactory.THETA_KEY, CubeSurfaceFactory.ZOOM_KEY, CubeSurfaceFactory.XOFF_KEY, CubeSurfaceFactory.YOFF_KEY, }; ConfigSpecifier rangeSpecifier = new ConfigSpecifier( rangeKeys ) { @Override public ConfigMap getSpecifiedValue() { ConfigMap c = super.getSpecifiedValue(); CubeAspect asp = oldAspect_; if ( asp != null ) { c.put( CubeSurfaceFactory.ROTMAT_KEY, asp.getRotation() ); c.put( CubeSurfaceFactory.ZOOM_KEY, asp.getZoom() ); c.put( CubeSurfaceFactory.XOFF_KEY, asp.getOffsetX() ); c.put( CubeSurfaceFactory.YOFF_KEY, asp.getOffsetY() ); } return c; } }; addAspectConfigTab( "Range", rangeSpecifier ); ConfigSpecifier viewSpecifier = new ConfigSpecifier( viewKeys ); ActionSpecifierPanel viewPanel = new ActionSpecifierPanel( viewSpecifier ) { protected void doSubmit( ActionEvent evt ) { if ( oldAspect_ != null ) { ConfigMap config = super.getSpecifiedValue(); double[][] limits = oldAspect_.getLimits(); double[] rot = CubeSurfaceFactory.getRotation( config ); double zoom = config.get( CubeSurfaceFactory.ZOOM_KEY ); double xoff = config.get( CubeSurfaceFactory.XOFF_KEY ); double yoff = config.get( CubeSurfaceFactory.YOFF_KEY ); CubeAspect aspect = new CubeAspect( limits[ 0 ], limits[ 1 ], limits[ 2 ], rot, zoom, xoff, yoff ); setAspect( aspect ); } } }; viewPanel.addActionListener( getActionForwarder() ); mainControl.addControlTab( "View", viewPanel.getComponent(), true ); /* Grid config tab. */ List<ConfigKey> gridKeyList = new ArrayList<ConfigKey>(); gridKeyList.add( CubeSurfaceFactory.FRAME_KEY ); gridKeyList.add( StyleKeys.MINOR_TICKS ); if ( isIso ) { gridKeyList.add( CubeSurfaceFactory.ISOCROWD_KEY ); } else { gridKeyList.addAll( Arrays.asList( new ConfigKey[] { CubeSurfaceFactory.XCROWD_KEY, CubeSurfaceFactory.YCROWD_KEY, CubeSurfaceFactory.ZCROWD_KEY, } ) ); } gridKeyList.add( StyleKeys.GRID_ANTIALIAS ); mainControl.addSpecifierTab( "Grid", new ConfigSpecifier( gridKeyList .toArray( new ConfigKey[ 0 ] ) ) ); /* Labels config tab. */ if ( ! isIso ) { addLabelsTab(); } /* Font config tab. */ mainControl.addSpecifierTab( "Font", new ConfigSpecifier( StyleKeys.CAPTIONER .getKeys() ) ); assert assertHasKeys( surfFact.getProfileKeys() ); }
diff --git a/DistFileSystem/src/distserver/ServEnterNetwork.java b/DistFileSystem/src/distserver/ServEnterNetwork.java index b5a6201..e063912 100644 --- a/DistFileSystem/src/distserver/ServEnterNetwork.java +++ b/DistFileSystem/src/distserver/ServEnterNetwork.java @@ -1,188 +1,189 @@ /** * @author paul */ package distserver; import distconfig.Sha1Generator; import distconfig.DistConfig; import distfilelisting.UserManagement; import distnodelisting.NodeSearchTable; import distnodelisting.GlobalNodeTable; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author paul */ public class ServEnterNetwork implements Runnable { private Socket client = null; private DistConfig distConf = null; /** * * @param cli The client that has already connected to the network */ public ServEnterNetwork (Socket cli) { this.client = cli; if (this.client == null) { // TODO: Throw an exception } } /** * Generates the new ID for the client and tells it where to look first for its next position */ @Override public void run() { try { System.out.println("In thread for connect to network"); distConf = DistConfig.get_Instance(); //Logger.getLogger( // ServEnterNetwork.class.getName()).log( // Level.INFO, null, // "In thread to connect a new node to the netwrok"); // Get the input stream for the client BufferedReader inStream = new BufferedReader ( new InputStreamReader(client.getInputStream())); System.out.println("Got input stream"); // Get the output stream for the client BufferedOutputStream bos = new BufferedOutputStream ( client.getOutputStream()); // Setup the writer to the output stream PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got out stream"); // Setup the writer for the object stream ObjectOutputStream oos = new ObjectOutputStream (bos); System.out.println("Got object output stream"); // Send the configuration and user management object to the new client // This will make sure all nodes have the same config System.out.println("Sending the dist config"); oos.writeObject(distConf); + oos.flush(); System.out.println("Sending user management"); oos.writeObject(UserManagement.get_Instance()); oos.flush(); // Wait to receive an acknowledgment before sending the next item System.out.println("Receiving reply"); inStream.readLine(); // Get the client IP address and create the hash NodeSearchTable distConnTable = NodeSearchTable.get_Instance(); InetAddress cliAddress = client.getInetAddress(); int newClientID = Sha1Generator.generate_Sha1(cliAddress.getHostAddress()); System.out.println("Sha1 is " + Integer.toString(newClientID)); if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); while (dgt.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } else { while (distConnTable.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } // Send the client their new ID outStream.println(Integer.toString(newClientID)); outStream.flush(); // Wait to receive an acknowledgment and request for next item inStream.readLine(); // If the configuration states to use the entire table, // Then send the entire table if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); oos.writeObject(dgt); oos.flush(); } // Else if, the current server is the only node on the network else if (distConnTable.size() == 0) { outStream.println(distConnTable.get_ownID()); outStream.println(distConnTable.get_ownIPAddress()); outStream.flush(); } // If the configuration does not specify using the full table // Send the highest ID and IP less then the ID of the new node else { // Check to see which two ID's in the connection table // the new client ID is between // First, use this server's ID as the starting point String ipAddress = distConnTable.get_ownIPAddress(); int id = Integer.parseInt(distConnTable.get_ownID()); boolean found = false; // Now loop through all of the ID's and check if the new // ID lies between them for (int index = 0; index < distConnTable.size(); index++) { // Get the next ID int nextID = Integer.parseInt(distConnTable.get_IDAt(index)); // Test if the new client is greater than or equal to the // previous ID and less than the nextID if (newClientID >= id && newClientID < nextID) { found = true; } // Test if the new client is greater than or equal to the // previous ID and greater than the next ID else if (newClientID >= id && newClientID > nextID) { found = true; } // Test if the new client is less than or equal to the // previous ID and less than the next ID else if (newClientID <= id && newClientID < nextID) { found = true; } // If it is not between the two, set the id to the next // id and the ip address to the next ip address if (!found) { id = nextID; ipAddress = distConnTable.get_IPAt(index); } } // Send the ID and IP Address to the client outStream.println(Integer.toString(id)); outStream.println(ipAddress); outStream.flush(); } // Wait for acknowledgment of receipt inStream.readLine(); // Finished setting up the new client, close all connections inStream.close(); oos.close(); outStream.close(); bos.close(); client.close(); } catch (IOException ex) { try { // Something went wrong with IO to the client client.close(); } catch (IOException ex1) { Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex1); } Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex); } } }
true
true
public void run() { try { System.out.println("In thread for connect to network"); distConf = DistConfig.get_Instance(); //Logger.getLogger( // ServEnterNetwork.class.getName()).log( // Level.INFO, null, // "In thread to connect a new node to the netwrok"); // Get the input stream for the client BufferedReader inStream = new BufferedReader ( new InputStreamReader(client.getInputStream())); System.out.println("Got input stream"); // Get the output stream for the client BufferedOutputStream bos = new BufferedOutputStream ( client.getOutputStream()); // Setup the writer to the output stream PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got out stream"); // Setup the writer for the object stream ObjectOutputStream oos = new ObjectOutputStream (bos); System.out.println("Got object output stream"); // Send the configuration and user management object to the new client // This will make sure all nodes have the same config System.out.println("Sending the dist config"); oos.writeObject(distConf); System.out.println("Sending user management"); oos.writeObject(UserManagement.get_Instance()); oos.flush(); // Wait to receive an acknowledgment before sending the next item System.out.println("Receiving reply"); inStream.readLine(); // Get the client IP address and create the hash NodeSearchTable distConnTable = NodeSearchTable.get_Instance(); InetAddress cliAddress = client.getInetAddress(); int newClientID = Sha1Generator.generate_Sha1(cliAddress.getHostAddress()); System.out.println("Sha1 is " + Integer.toString(newClientID)); if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); while (dgt.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } else { while (distConnTable.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } // Send the client their new ID outStream.println(Integer.toString(newClientID)); outStream.flush(); // Wait to receive an acknowledgment and request for next item inStream.readLine(); // If the configuration states to use the entire table, // Then send the entire table if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); oos.writeObject(dgt); oos.flush(); } // Else if, the current server is the only node on the network else if (distConnTable.size() == 0) { outStream.println(distConnTable.get_ownID()); outStream.println(distConnTable.get_ownIPAddress()); outStream.flush(); } // If the configuration does not specify using the full table // Send the highest ID and IP less then the ID of the new node else { // Check to see which two ID's in the connection table // the new client ID is between // First, use this server's ID as the starting point String ipAddress = distConnTable.get_ownIPAddress(); int id = Integer.parseInt(distConnTable.get_ownID()); boolean found = false; // Now loop through all of the ID's and check if the new // ID lies between them for (int index = 0; index < distConnTable.size(); index++) { // Get the next ID int nextID = Integer.parseInt(distConnTable.get_IDAt(index)); // Test if the new client is greater than or equal to the // previous ID and less than the nextID if (newClientID >= id && newClientID < nextID) { found = true; } // Test if the new client is greater than or equal to the // previous ID and greater than the next ID else if (newClientID >= id && newClientID > nextID) { found = true; } // Test if the new client is less than or equal to the // previous ID and less than the next ID else if (newClientID <= id && newClientID < nextID) { found = true; } // If it is not between the two, set the id to the next // id and the ip address to the next ip address if (!found) { id = nextID; ipAddress = distConnTable.get_IPAt(index); } } // Send the ID and IP Address to the client outStream.println(Integer.toString(id)); outStream.println(ipAddress); outStream.flush(); } // Wait for acknowledgment of receipt inStream.readLine(); // Finished setting up the new client, close all connections inStream.close(); oos.close(); outStream.close(); bos.close(); client.close(); } catch (IOException ex) { try { // Something went wrong with IO to the client client.close(); } catch (IOException ex1) { Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex1); } Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex); } }
public void run() { try { System.out.println("In thread for connect to network"); distConf = DistConfig.get_Instance(); //Logger.getLogger( // ServEnterNetwork.class.getName()).log( // Level.INFO, null, // "In thread to connect a new node to the netwrok"); // Get the input stream for the client BufferedReader inStream = new BufferedReader ( new InputStreamReader(client.getInputStream())); System.out.println("Got input stream"); // Get the output stream for the client BufferedOutputStream bos = new BufferedOutputStream ( client.getOutputStream()); // Setup the writer to the output stream PrintWriter outStream = new PrintWriter(bos, false); System.out.println("Got out stream"); // Setup the writer for the object stream ObjectOutputStream oos = new ObjectOutputStream (bos); System.out.println("Got object output stream"); // Send the configuration and user management object to the new client // This will make sure all nodes have the same config System.out.println("Sending the dist config"); oos.writeObject(distConf); oos.flush(); System.out.println("Sending user management"); oos.writeObject(UserManagement.get_Instance()); oos.flush(); // Wait to receive an acknowledgment before sending the next item System.out.println("Receiving reply"); inStream.readLine(); // Get the client IP address and create the hash NodeSearchTable distConnTable = NodeSearchTable.get_Instance(); InetAddress cliAddress = client.getInetAddress(); int newClientID = Sha1Generator.generate_Sha1(cliAddress.getHostAddress()); System.out.println("Sha1 is " + Integer.toString(newClientID)); if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); while (dgt.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } else { while (distConnTable.contains_ID(newClientID)) { newClientID = (newClientID + 1) % distConf.get_MaxNodes(); } } // Send the client their new ID outStream.println(Integer.toString(newClientID)); outStream.flush(); // Wait to receive an acknowledgment and request for next item inStream.readLine(); // If the configuration states to use the entire table, // Then send the entire table if (distConf.get_UseGlobalNodeTable()) { GlobalNodeTable dgt = GlobalNodeTable.get_instance(); oos.writeObject(dgt); oos.flush(); } // Else if, the current server is the only node on the network else if (distConnTable.size() == 0) { outStream.println(distConnTable.get_ownID()); outStream.println(distConnTable.get_ownIPAddress()); outStream.flush(); } // If the configuration does not specify using the full table // Send the highest ID and IP less then the ID of the new node else { // Check to see which two ID's in the connection table // the new client ID is between // First, use this server's ID as the starting point String ipAddress = distConnTable.get_ownIPAddress(); int id = Integer.parseInt(distConnTable.get_ownID()); boolean found = false; // Now loop through all of the ID's and check if the new // ID lies between them for (int index = 0; index < distConnTable.size(); index++) { // Get the next ID int nextID = Integer.parseInt(distConnTable.get_IDAt(index)); // Test if the new client is greater than or equal to the // previous ID and less than the nextID if (newClientID >= id && newClientID < nextID) { found = true; } // Test if the new client is greater than or equal to the // previous ID and greater than the next ID else if (newClientID >= id && newClientID > nextID) { found = true; } // Test if the new client is less than or equal to the // previous ID and less than the next ID else if (newClientID <= id && newClientID < nextID) { found = true; } // If it is not between the two, set the id to the next // id and the ip address to the next ip address if (!found) { id = nextID; ipAddress = distConnTable.get_IPAt(index); } } // Send the ID and IP Address to the client outStream.println(Integer.toString(id)); outStream.println(ipAddress); outStream.flush(); } // Wait for acknowledgment of receipt inStream.readLine(); // Finished setting up the new client, close all connections inStream.close(); oos.close(); outStream.close(); bos.close(); client.close(); } catch (IOException ex) { try { // Something went wrong with IO to the client client.close(); } catch (IOException ex1) { Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex1); } Logger.getLogger(ServEnterNetwork.class.getName()).log(Level.SEVERE, null, ex); } }
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java index 8c353297..f2447271 100644 --- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java +++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/render/SanitizingRequestRewriter.java @@ -1,147 +1,150 @@ /* * 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.shindig.gadgets.render; import org.apache.sanselan.ImageFormat; import org.apache.sanselan.ImageReadException; import org.apache.sanselan.Sanselan; import org.apache.sanselan.common.byteSources.ByteSourceInputStream; import org.apache.shindig.gadgets.http.HttpRequest; import org.apache.shindig.gadgets.http.HttpResponse; import org.apache.shindig.gadgets.parse.caja.CajaCssSanitizer; import org.apache.shindig.gadgets.render.SanitizingGadgetRewriter.SanitizingProxyingLinkRewriter; import org.apache.shindig.gadgets.rewrite.ContentRewriterFeature; import org.apache.shindig.gadgets.rewrite.ContentRewriterFeatureFactory; import org.apache.shindig.gadgets.rewrite.ContentRewriterUris; import org.apache.shindig.gadgets.rewrite.MutableContent; import org.apache.shindig.gadgets.rewrite.RequestRewriter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import com.google.inject.Inject; /** * Rewriter that sanitizes CSS and image content. */ public class SanitizingRequestRewriter implements RequestRewriter { private static final Logger logger = Logger.getLogger(SanitizingRequestRewriter.class.getName()); private final CajaCssSanitizer cssSanitizer; private final ContentRewriterFeatureFactory rewriterFeatureFactory; private final ContentRewriterUris rewriterUris; @Inject public SanitizingRequestRewriter( ContentRewriterFeatureFactory rewriterFeatureFactory, ContentRewriterUris rewriterUris, CajaCssSanitizer cssSanitizer) { this.rewriterUris = rewriterUris; this.cssSanitizer = cssSanitizer; this.rewriterFeatureFactory = rewriterFeatureFactory; } public boolean rewrite(HttpRequest request, HttpResponse resp, MutableContent content) { // Content fetched through the proxy can stipulate that it must be sanitized. if (request.isSanitizationRequested()) { ContentRewriterFeature rewriterFeature = rewriterFeatureFactory.createRewriteAllFeature(request.getCacheTtl()); if (request.getRewriteMimeType().equalsIgnoreCase("text/css")) { return rewriteProxiedCss(request, resp, content, rewriterFeature); } else if (request.getRewriteMimeType().toLowerCase().startsWith("image/")) { return rewriteProxiedImage(request, resp, content); } else { logger.log(Level.WARNING, "Request to sanitize unknown content type " + request.getRewriteMimeType() + " for " + request.getUri().toString()); content.setContent(""); return true; } } else { // No Op return false; } } /** * We don't actually rewrite the image we just ensure that it is in fact a valid * and known image type. */ private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp, MutableContent content) { boolean imageIsSafe = false; try { String contentType = resp.getHeader("Content-Type"); if (contentType == null || contentType.toLowerCase().startsWith("image/")) { // Unspecified or unknown image mime type. try { ImageFormat imageFormat = Sanselan .guessFormat(new ByteSourceInputStream(resp.getResponse(), request.getUri().getPath())); if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) { logger.log(Level.INFO, "Unable to sanitize unknown image type " + request.getUri().toString()); return true; } imageIsSafe = true; // Return false to indicate that no rewriting occurred return false; } catch (IOException ioe) { throw new RuntimeException(ioe); } catch (ImageReadException ire) { - throw new RuntimeException(ire); + // Unable to read the image so its not safe + logger.log(Level.INFO, "Unable to detect image type for " +request.getUri().toString() + + " for sanitized content", ire); + return true; } } else { return true; } } finally { if (!imageIsSafe) { content.setContent(""); } } } /** * Sanitize a CSS file. */ private boolean rewriteProxiedCss(HttpRequest request, HttpResponse response, MutableContent content, ContentRewriterFeature rewriterFeature) { String sanitized = ""; try { String contentType = response.getHeader("Content-Type"); if (contentType == null || contentType.toLowerCase().startsWith("text/")) { String proxyBaseNoGadget = rewriterUris.getProxyBase(request.getContainer()); SanitizingProxyingLinkRewriter cssImportRewriter = new SanitizingProxyingLinkRewriter( request.getGadget(), rewriterFeature, proxyBaseNoGadget, "text/css"); SanitizingProxyingLinkRewriter cssImageRewriter = new SanitizingProxyingLinkRewriter( request.getGadget(), rewriterFeature, proxyBaseNoGadget, "image/*"); sanitized = cssSanitizer.sanitize(content.getContent(), request.getUri(), cssImportRewriter, cssImageRewriter); } return true; } finally { // Set sanitized content in finally to ensure it is always cleared in // the case of errors content.setContent(sanitized); } } }
true
true
private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp, MutableContent content) { boolean imageIsSafe = false; try { String contentType = resp.getHeader("Content-Type"); if (contentType == null || contentType.toLowerCase().startsWith("image/")) { // Unspecified or unknown image mime type. try { ImageFormat imageFormat = Sanselan .guessFormat(new ByteSourceInputStream(resp.getResponse(), request.getUri().getPath())); if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) { logger.log(Level.INFO, "Unable to sanitize unknown image type " + request.getUri().toString()); return true; } imageIsSafe = true; // Return false to indicate that no rewriting occurred return false; } catch (IOException ioe) { throw new RuntimeException(ioe); } catch (ImageReadException ire) { throw new RuntimeException(ire); } } else { return true; } } finally { if (!imageIsSafe) { content.setContent(""); } } }
private boolean rewriteProxiedImage(HttpRequest request, HttpResponse resp, MutableContent content) { boolean imageIsSafe = false; try { String contentType = resp.getHeader("Content-Type"); if (contentType == null || contentType.toLowerCase().startsWith("image/")) { // Unspecified or unknown image mime type. try { ImageFormat imageFormat = Sanselan .guessFormat(new ByteSourceInputStream(resp.getResponse(), request.getUri().getPath())); if (imageFormat == ImageFormat.IMAGE_FORMAT_UNKNOWN) { logger.log(Level.INFO, "Unable to sanitize unknown image type " + request.getUri().toString()); return true; } imageIsSafe = true; // Return false to indicate that no rewriting occurred return false; } catch (IOException ioe) { throw new RuntimeException(ioe); } catch (ImageReadException ire) { // Unable to read the image so its not safe logger.log(Level.INFO, "Unable to detect image type for " +request.getUri().toString() + " for sanitized content", ire); return true; } } else { return true; } } finally { if (!imageIsSafe) { content.setContent(""); } } }
diff --git a/src/TreeWalker.java b/src/TreeWalker.java index 12b1615..8228c09 100644 --- a/src/TreeWalker.java +++ b/src/TreeWalker.java @@ -1,451 +1,451 @@ import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.TokenStream; import org.antlr.runtime.tree.CommonTree; import java.io.*; import org.antlr.runtime.*; import java.util.*; public class TreeWalker { public void walkTree(CommonTree t, String filename) { try { BufferedWriter out = new BufferedWriter(new FileWriter(filename + ".rb")); out.write("require \"set\"\n"); if(!(t.getType() == 0)){ walk((CommonTree) t, out); } //traverse all the child nodes of the root if root was empty else{ for ( int i = 0; i < t.getChildCount(); i++ ) { walk(((CommonTree)t.getChild(i)), out); } } out.close(); } catch (IOException e) {} } public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ // out.write(t.getText() + ".main("); - out.write(t.getText() + " "); + out.write(t.getText()); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} } }
true
true
public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ // out.write(t.getText() + ".main("); out.write(t.getText() + " "); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} }
public void walk(CommonTree t, BufferedWriter out) { try{ if ( t != null ) { // every unary operator needs to be preceded by a open parenthesis and ended with a closed parenthesis switch(t.getType()) { case TanGParser.ADDSUB: //if the operation is binary, read the two children and output that to the ruby code if(t.getChildCount() > 1) { walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); } //if the operation is a unary minus, surround the right-hand side with parentheses //this is to differenciate between unary operators and operations done within assignment operator else{ if(t.getText().equals("- ")) { out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); } else { walk((CommonTree)t.getChild(0), out); } } break; //binary operations like this simply prints out the 1st child, the operation and the 2nd child case TanGParser.AND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //expressions like these do not require translation and can simply to outputed to the ruby file case TanGParser.ASSERT: out.write(t.getText() + " "); break; case TanGParser.ASSN: walk((CommonTree)t.getChild(0), out); out.write( t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; //this operator and a few of the following operators are different in ruby so a translation was necessary case TanGParser.BITAND: walk((CommonTree)t.getChild(0), out); out.write("& "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITNOT: out.write("("); out.write(t.getText()); walk((CommonTree)t.getChild(0), out); out.write(")"); break; case TanGParser.BITOR: walk((CommonTree)t.getChild(0), out); out.write("| "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITSHIFT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BITXOR: walk((CommonTree)t.getChild(0), out); out.write("^ "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLAND: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BOOLOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.BREAK: out.write(t.getText() + " "); break; case TanGParser.BYTE: out.write(t.getText() + " "); break; case TanGParser.COMMA: out.write(t.getText() + " "); break; case TanGParser.COMMENT: out.write(t.getText()); break; case TanGParser.COND: //we start at the second child node and skip every other one to skip the newlines out.write("case "); out.newLine(); for (int j = 1; j < t.getChildCount(); j=j+2 ) { //for all the conditions, except the last, begin it with the keyword "when" //begin the last condition with else if(j < t.getChildCount()-3) { out.write("when "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())== (TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } } else if(j == t.getChildCount()-3) { out.write("else "); walk((CommonTree)t.getChild(j), out); int k=0; while (!(((t.getChild(j).getChild(k)).getType())==(TanGParser.NEWLINE))){ k++; } while (k < t.getChild(j).getChildCount()-1){ walk((CommonTree)(t.getChild(j).getChild(k)), out); k++; } }else { walk((CommonTree)t.getChild(j), out); } } break; case TanGParser.CONTINUE: out.write("next "); break; case TanGParser.DO: out.write(t.getText() + " "); break; case TanGParser.DOT: out.write(t.getText()); break; case TanGParser.ELSE: out.write(t.getText() + " "); break; case TanGParser.END: out.write(t.getText() + " "); out.newLine(); break; case TanGParser.EOF: out.write(t.getText()); break; case TanGParser.EQTEST: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.ESC_SEQ: out.write(t.getText() + " "); break; case TanGParser.EXP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.EXPONENT: //the power 10 operator in Tandem is simply e. It needs to be transformed to ruby code. out.write("("); walk((CommonTree)t.getChild(0), out); out.write("* 10 ** "); walk((CommonTree)t.getChild(1), out); out.write(")"); break; case TanGParser.FATCOMMA: out.write(t.getText()); break; case TanGParser.FILENAME: out.write(t.getText() + " "); break; case TanGParser.FLOAT: out.write(t.getText() + " "); break; case TanGParser.FOR: out.write(t.getText()); break; case TanGParser.FORK: break; case TanGParser.FROM: break; case TanGParser.HEX: out.write(t.getText() + " "); break; case TanGParser.HEX_DIGIT: out.write(t.getText() + " "); break; case TanGParser.ID: out.write("td_"+t.getText() + " "); break; case TanGParser.IF: out.write(t.getText() + " "); break; case TanGParser.IMPORT: out.write("require "); break; case TanGParser.IN: out.write(t.getText() + " "); break; case TanGParser.INT: out.write(t.getText() + " "); break; case TanGParser.INTRANGE: out.write(t.getText()); break; case TanGParser.IS: break; case TanGParser.LBRACE: out.write(t.getText()); break; case TanGParser.LBRACK: out.write(t.getText()); break; case TanGParser.LOOP: out.write("while true "); break; case TanGParser.LPAREN: out.write(t.getText()); break; case TanGParser.MAGCOMP: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MOD: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.MULT: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.NEWLINE: out.write(t.getText()); break; case TanGParser.NODE: LinkedList<CommonTree> list = new LinkedList<CommonTree>(); out.newLine(); //every node will be converted to a class with the name of the node as the class name if (t.getText().equals("public node")) { out.write("class "); out.write(t.getChild(0).getText()); // walk((CommonTree)t.getChild(0), out); } //if the class is private, add private after writing the constructor of the class else { out.write("class "); //walk((CommonTree)t.getChild(0), out); out.write(t.getChild(0).getText()); out.newLine(); out.write("private"); } out.newLine(); //then each class will have a main method with the node definition code out.write("def main"); for ( int i = 1; i < t.getChildCount(); i++ ) { if (t.getChild(i).getType()==TanGParser.NODE){ list.addLast(((CommonTree)t.getChild(i))); } else{ walk((CommonTree)t.getChild(i), out); } } while(list.isEmpty()==false){ walk((CommonTree)list.getFirst(), out); list.remove(); } out.newLine(); out.write("end "); out.newLine(); break; case TanGParser.NODEID: //transform Println to ruby's print if(t.getText().equals("Println")){ out.write("puts"); } //transform Print to ruby's print else if(t.getText().equals("Print")){ out.write("print"); } //if not, just print the id else{ // out.write(t.getText() + ".main("); out.write(t.getText()); } break; case TanGParser.NOT: out.write(t.getText()); walk((CommonTree)t.getChild(0), out); break; case TanGParser.NONE: out.write(t.getText()+ " "); break; case TanGParser.NULL: out.write(t.getText()+ " "); break; case TanGParser.OR: walk((CommonTree)t.getChild(0), out); out.write(t.getText()); walk((CommonTree)t.getChild(1), out); break; case TanGParser.PIPE: String params = ""; String first = ""; LinkedList<CommonTree> list2 = new LinkedList<CommonTree>(); for ( int i = 0; i < t.getChildCount(); i++ ) { //if child is a node, but not the last node, push it if ((t.getChild(i).getType() == TanGParser.NODEID && i != t.getChildCount()-1)) { list2.push((CommonTree)t.getChild(i)); } //if next token is a pipe, push it else if(t.getChild(i).getType() == TanGParser.PIPE) { list2.push((CommonTree)t.getChild(i)); } //if next token is an id, it is a parameter so it is not pushed //when we walk the node that has the parameters (the first node), we will print them else if(t.getChild(i).getType() == TanGParser.ID) { first = list2.peek().getText(); params = params + t.getChild(i) + ","; } else { //walk the tree if the child is the last node in the chain walk((CommonTree)t.getChild(i), out); while(list2.isEmpty()==false){ out.write("("); if((list2.peek().getText()).equals(first)) { walk((CommonTree)list2.pop(), out); out.write("("); out.write(params.substring(0, params.length()-1)); out.write(")"); }else { walk((CommonTree)list2.pop(), out); } out.write(")"); } } } break; case TanGParser.PUBPRIV: break; case TanGParser.RANGE: out.write(t.getText() + " "); break; case TanGParser.RBRACE: out.write(t.getText()); break; case TanGParser.RBRACK: out.write(t.getText()); break; case TanGParser.RETURN: out.write(t.getText() + " "); break; case TanGParser.RPAREN: out.write(t.getText()); break; case TanGParser.SOME: out.write(t.getText()+ " "); break; case TanGParser.STAR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; case TanGParser.STRING: out.write(t.getText() + " "); break; case TanGParser.TF: out.write(t.getText() + " "); break; case TanGParser.UNLESS: out.write(t.getText() + " "); break; case TanGParser.UNTIL: out.write(t.getText() + " "); break; case TanGParser.WHILE: out.write(t.getText() + " "); break; case TanGParser.WS: out.write(t.getText()); break; case TanGParser.XOR: walk((CommonTree)t.getChild(0), out); out.write(t.getText() + " "); walk((CommonTree)t.getChild(1), out); break; } } } catch (IOException e) {} }
diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java index 646662ac00..e12f28312f 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java @@ -1,95 +1,95 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.type.descriptor.java; import java.util.Comparator; import java.util.Locale; import java.util.StringTokenizer; import org.hibernate.type.descriptor.WrapperOptions; /** * Descriptor for {@link Locale} handling. * * @author Steve Ebersole */ public class LocaleTypeDescriptor extends AbstractTypeDescriptor<Locale> { public static final LocaleTypeDescriptor INSTANCE = new LocaleTypeDescriptor(); public static class LocaleComparator implements Comparator<Locale> { public static final LocaleComparator INSTANCE = new LocaleComparator(); public int compare(Locale o1, Locale o2) { return o1.toString().compareTo( o2.toString() ); } } public LocaleTypeDescriptor() { super( Locale.class ); } @Override public Comparator<Locale> getComparator() { return LocaleComparator.INSTANCE; } public String toString(Locale value) { return value.toString(); } public Locale fromString(String string) { StringTokenizer tokens = new StringTokenizer( string, "_" ); - String language = tokens.hasMoreTokens() ? tokens.nextToken() : ""; - String country = tokens.hasMoreTokens() ? tokens.nextToken() : ""; + String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : ""; + String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : ""; // Need to account for allowable '_' within the variant String variant = ""; String sep = ""; while ( tokens.hasMoreTokens() ) { variant += sep + tokens.nextToken(); sep = "_"; } return new Locale( language, country, variant ); } @SuppressWarnings({ "unchecked" }) public <X> X unwrap(Locale value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( String.class.isAssignableFrom( type ) ) { return (X) value.toString(); } throw unknownUnwrap( type ); } public <X> Locale wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if ( String.class.isInstance( value ) ) { return fromString( (String) value ); } throw unknownWrap( value.getClass() ); } }
true
true
public Locale fromString(String string) { StringTokenizer tokens = new StringTokenizer( string, "_" ); String language = tokens.hasMoreTokens() ? tokens.nextToken() : ""; String country = tokens.hasMoreTokens() ? tokens.nextToken() : ""; // Need to account for allowable '_' within the variant String variant = ""; String sep = ""; while ( tokens.hasMoreTokens() ) { variant += sep + tokens.nextToken(); sep = "_"; } return new Locale( language, country, variant ); }
public Locale fromString(String string) { StringTokenizer tokens = new StringTokenizer( string, "_" ); String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : ""; String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : ""; // Need to account for allowable '_' within the variant String variant = ""; String sep = ""; while ( tokens.hasMoreTokens() ) { variant += sep + tokens.nextToken(); sep = "_"; } return new Locale( language, country, variant ); }
diff --git a/swig/java/test.java b/swig/java/test.java index 6b47148..dfa86bf 100644 --- a/swig/java/test.java +++ b/swig/java/test.java @@ -1,11 +1,11 @@ import com.github.whym.*; public class test { static { System.loadLibrary("TinyClassifier"); } public static void main(String[] args) { - IntPerceptron p = new IntPerceptron(3); + IntPKPerceptron p = new IntPKPerceptron(3); System.out.println(""+p.getKernel_order()); } }
true
true
public static void main(String[] args) { IntPerceptron p = new IntPerceptron(3); System.out.println(""+p.getKernel_order()); }
public static void main(String[] args) { IntPKPerceptron p = new IntPKPerceptron(3); System.out.println(""+p.getKernel_order()); }
diff --git a/src/main/java/org/dynmap/DynmapCore.java b/src/main/java/org/dynmap/DynmapCore.java index cd793170..b08c9b96 100644 --- a/src/main/java/org/dynmap/DynmapCore.java +++ b/src/main/java/org/dynmap/DynmapCore.java @@ -1,1447 +1,1447 @@ package org.dynmap; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import org.dynmap.MapType.ImageFormat; import org.dynmap.common.DynmapCommandSender; import org.dynmap.common.DynmapListenerManager; import org.dynmap.common.DynmapListenerManager.EventType; import org.dynmap.common.DynmapPlayer; import org.dynmap.common.DynmapServerInterface; import org.dynmap.debug.Debug; import org.dynmap.debug.Debugger; import org.dynmap.hdmap.HDBlockModels; import org.dynmap.hdmap.HDMapManager; import org.dynmap.hdmap.TexturePack; import org.dynmap.markers.MarkerAPI; import org.dynmap.markers.impl.MarkerAPIImpl; import org.dynmap.servlet.FileLockResourceHandler; import org.dynmap.servlet.JettyNullLogger; import org.dynmap.web.BanIPFilter; import org.dynmap.web.CustomHeaderFilter; import org.dynmap.web.FilterHandler; import org.dynmap.web.HandlerRouter; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.servlet.ServletHolder; import org.eclipse.jetty.util.log.Logger; import org.eclipse.jetty.util.resource.FileResource; import org.yaml.snakeyaml.Yaml; import javax.servlet.*; import javax.servlet.http.HttpServlet; public class DynmapCore { private DynmapServerInterface server; private String version; private Server webServer = null; private String webhostname = null; private int webport = 0; private HandlerRouter router = null; public MapManager mapManager = null; public PlayerList playerList; public ConfigurationNode configuration; public ConfigurationNode world_config; public ComponentManager componentManager = new ComponentManager(); public DynmapListenerManager listenerManager = new DynmapListenerManager(this); public PlayerFaces playerfacemgr; public Events events = new Events(); public String deftemplatesuffix = ""; private DynmapMapCommands dmapcmds = new DynmapMapCommands(); boolean bettergrass = false; boolean smoothlighting = false; private String def_image_format = "png"; private HashSet<String> enabledTriggers = new HashSet<String>(); public boolean disable_chat_to_web = false; public CompassMode compassmode = CompassMode.PRE19; private int config_hashcode; /* Used to signal need to reload web configuration (world changes, config update, etc) */ private int fullrenderplayerlimit; /* Number of online players that will cause fullrender processing to pause */ private boolean didfullpause; private Map<String, LinkedList<String>> ids_by_ip = new HashMap<String, LinkedList<String>>(); private boolean persist_ids_by_ip = false; private int snapshotcachesize; public enum CompassMode { PRE19, /* Default for 1.8 and earlier (east is Z+) */ NEWROSE, /* Use same map orientation, fix rose */ NEWNORTH /* Use new map orientation */ }; /* Flag to let code know that we're doing reload - make sure we don't double-register event handlers */ public boolean is_reload = false; public static boolean ignore_chunk_loads = false; /* Flag keep us from processing our own chunk loads */ private MarkerAPIImpl markerapi; private File dataDirectory; private File tilesDirectory; private String plugin_ver; private String mc_ver; /* Constructor for core */ public DynmapCore() { } /* Cleanup method */ public void cleanup() { server = null; markerapi = null; } /* Dependencies - need to be supplied by plugin wrapper */ public void setPluginVersion(String pluginver) { plugin_ver = pluginver; } public void setDataFolder(File dir) { dataDirectory = dir; } public final File getDataFolder() { return dataDirectory; } public final File getTilesFolder() { return tilesDirectory; } public void setMinecraftVersion(String mcver) { mc_ver = mcver; } public void setServer(DynmapServerInterface srv) { server = srv; } public final DynmapServerInterface getServer() { return server; } public final MapManager getMapManager() { return mapManager; } /* Add/Replace branches in configuration tree with contribution from a separate file */ private void mergeConfigurationBranch(ConfigurationNode cfgnode, String branch, boolean replace_existing, boolean islist) { Object srcbranch = cfgnode.getObject(branch); if(srcbranch == null) return; /* See if top branch is in configuration - if not, just add whole thing */ Object destbranch = configuration.getObject(branch); if(destbranch == null) { /* Not found */ configuration.put(branch, srcbranch); /* Add new tree to configuration */ return; } /* If list, merge by "name" attribute */ if(islist) { List<ConfigurationNode> dest = configuration.getNodes(branch); List<ConfigurationNode> src = cfgnode.getNodes(branch); /* Go through new records : see what to do with each */ for(ConfigurationNode node : src) { String name = node.getString("name", null); if(name == null) continue; /* Walk destination - see if match */ boolean matched = false; for(ConfigurationNode dnode : dest) { String dname = dnode.getString("name", null); if(dname == null) continue; if(dname.equals(name)) { /* Match? */ if(replace_existing) { dnode.clear(); dnode.putAll(node); } matched = true; break; } } /* If no match, add to end */ if(!matched) { dest.add(node); } } configuration.put(branch,dest); } /* If configuration node, merge by key */ else { ConfigurationNode src = cfgnode.getNode(branch); ConfigurationNode dest = configuration.getNode(branch); for(String key : src.keySet()) { /* Check each contribution */ if(dest.containsKey(key)) { /* Exists? */ if(replace_existing) { /* If replacing, do so */ dest.put(key, src.getObject(key)); } } else { /* Else, always add if not there */ dest.put(key, src.getObject(key)); } } } } /* Table of default templates - all are resources in dynmap.jar unnder templates/, and go in templates directory when needed */ private static final String[] stdtemplates = { "normal.txt", "nether.txt", "skylands.txt", "normal-lowres.txt", "nether-lowres.txt", "skylands-lowres.txt", "normal-hires.txt", "nether-hires.txt", "skylands-hires.txt", "normal-vlowres.txt", "skylands-vlowres.txt", "nether-vlowres.txt", "the_end.txt", "the_end-vlowres.txt", "the_end-lowres.txt", "the_end-hires.txt" }; private static final String CUSTOM_PREFIX = "custom-"; /* Load templates from template folder */ private void loadTemplates() { File templatedir = new File(dataDirectory, "templates"); templatedir.mkdirs(); /* First, prime the templates directory with default standard templates, if needed */ for(String stdtemplate : stdtemplates) { File f = new File(templatedir, stdtemplate); createDefaultFileFromResource("/templates/" + stdtemplate, f); } /* Now process files */ String[] templates = templatedir.list(); /* Go through list - process all ones not starting with 'custom' first */ for(String tname: templates) { /* If matches naming convention */ if(tname.endsWith(".txt") && (!tname.startsWith(CUSTOM_PREFIX))) { File tf = new File(templatedir, tname); ConfigurationNode cn = new ConfigurationNode(tf); cn.load(); /* Supplement existing values (don't replace), since configuration.txt is more custom than these */ mergeConfigurationBranch(cn, "templates", false, false); } } /* Go through list again - this time do custom- ones */ for(String tname: templates) { /* If matches naming convention */ if(tname.endsWith(".txt") && tname.startsWith(CUSTOM_PREFIX)) { File tf = new File(templatedir, tname); ConfigurationNode cn = new ConfigurationNode(tf); cn.load(); /* This are overrides - replace even configuration.txt content */ mergeConfigurationBranch(cn, "templates", true, false); } } } public boolean enableCore() { /* Start with clean events */ events = new Events(); /* Load plugin version info */ loadVersion(); /* Initialize confguration.txt if needed */ File f = new File(dataDirectory, "configuration.txt"); if(!createDefaultFileFromResource("/configuration.txt", f)) { return false; } /* Load configuration.txt */ configuration = new ConfigurationNode(f); configuration.load(); /* Add options to avoid 0.29 re-render (fixes very inconsistent with previous maps) */ HDMapManager.usegeneratedtextures = configuration.getBoolean("use-generated-textures", false); HDMapManager.waterlightingfix = configuration.getBoolean("correct-water-lighting", false); HDMapManager.biomeshadingfix = configuration.getBoolean("correct-biome-shading", false); /* Get default image format */ def_image_format = configuration.getString("image-format", "png"); MapType.ImageFormat fmt = MapType.ImageFormat.fromID(def_image_format); if(fmt == null) { Log.severe("Invalid image-format: " + def_image_format); def_image_format = "png"; } smoothlighting = configuration.getBoolean("smooth-lighting", false); Log.verbose = configuration.getBoolean("verbose", true); deftemplatesuffix = configuration.getString("deftemplatesuffix", ""); /* Get snapshot cache size */ snapshotcachesize = configuration.getInteger("snapshotcachesize", 500); /* Default compassmode to newrose */ String cmode = configuration.getString("compass-mode", "newrose"); if(cmode.equals("newnorth")) compassmode = CompassMode.NEWNORTH; else if(cmode.equals("newrose")) compassmode = CompassMode.NEWROSE; else compassmode = CompassMode.PRE19; /* Default better-grass */ bettergrass = configuration.getBoolean("better-grass", false); /* Load full render processing player limit */ fullrenderplayerlimit = configuration.getInteger("fullrenderplayerlimit", 0); /* Load block models */ HDBlockModels.loadModels(dataDirectory, configuration); /* Load texture mappings */ TexturePack.loadTextureMapping(dataDirectory, configuration); /* Now, process worlds.txt - merge it in as an override of existing values (since it is only user supplied values) */ f = new File(dataDirectory, "worlds.txt"); if(!createDefaultFileFromResource("/worlds.txt", f)) { return false; } world_config = new ConfigurationNode(f); world_config.load(); /* Now, process templates */ loadTemplates(); /* If we're persisting ids-by-ip, load it */ persist_ids_by_ip = configuration.getBoolean("persist-ids-by-ip", true); if(persist_ids_by_ip) loadIDsByIP(); loadDebuggers(); tilesDirectory = getFile(configuration.getString("tilespath", "web/tiles")); if (!tilesDirectory.isDirectory() && !tilesDirectory.mkdirs()) { Log.warning("Could not create directory for tiles ('" + tilesDirectory + "')."); } playerList = new PlayerList(getServer(), getFile("hiddenplayers.txt"), configuration); playerList.load(); mapManager = new MapManager(this, configuration); mapManager.startRendering(); playerfacemgr = new PlayerFaces(this); updateConfigHashcode(); /* Initialize/update config hashcode */ loadWebserver(); enabledTriggers.clear(); List<String> triggers = configuration.getStrings("render-triggers", new ArrayList<String>()); if (triggers != null) { for (Object trigger : triggers) { enabledTriggers.add((String) trigger); } } // Load components. for(Component component : configuration.<Component>createInstances("components", new Class<?>[] { DynmapCore.class }, new Object[] { this })) { componentManager.add(component); } Log.verboseinfo("Loaded " + componentManager.components.size() + " components."); if (!configuration.getBoolean("disable-webserver", false)) { startWebserver(); } /* Add login/logoff listeners */ listenerManager.addListener(EventType.PLAYER_JOIN, new DynmapListenerManager.PlayerEventListener() { @Override public void playerEvent(DynmapPlayer p) { playerJoined(p); } }); listenerManager.addListener(EventType.PLAYER_QUIT, new DynmapListenerManager.PlayerEventListener() { @Override public void playerEvent(DynmapPlayer p) { playerQuit(p); } }); /* Print version info */ Log.info("version " + plugin_ver + " is enabled - core version " + version ); events.<Object>trigger("initialized", null); return true; } private void playerJoined(DynmapPlayer p) { playerList.updateOnlinePlayers(null); if(fullrenderplayerlimit > 0) { if(getServer().getOnlinePlayers().length >= fullrenderplayerlimit) { if(getPauseFullRadiusRenders() == false) { /* If not paused, pause it */ setPauseFullRadiusRenders(true); Log.info("Pause full/radius renders - player limit reached"); didfullpause = true; } } } /* Add player info to IP-to-ID table */ InetSocketAddress addr = p.getAddress(); if(addr != null) { String ip = addr.getAddress().getHostAddress(); LinkedList<String> ids = ids_by_ip.get(ip); if(ids == null) { ids = new LinkedList<String>(); ids_by_ip.put(ip, ids); } String pid = p.getName(); if(ids.indexOf(pid) != 0) { ids.remove(pid); /* Remove from list */ ids.addFirst(pid); /* Put us first on list */ } } /* And re-attach to active jobs */ if(mapManager != null) mapManager.connectTasksToPlayer(p); } /* Called by plugin each time a player quits the server */ private void playerQuit(DynmapPlayer p) { playerList.updateOnlinePlayers(p.getName()); if(fullrenderplayerlimit > 0) { /* Quitting player is still online at this moment, so discount count by 1 */ if((getServer().getOnlinePlayers().length - 1) < fullrenderplayerlimit) { if(didfullpause) { /* Only unpause if we did the pause */ setPauseFullRadiusRenders(false); Log.info("Resume full/radius renders - below player limit"); didfullpause = false; } } } } public void updateConfigHashcode() { config_hashcode = (int)System.currentTimeMillis(); } public int getConfigHashcode() { return config_hashcode; } private FileResource createFileResource(String path) { try { File f = new File(path); URI uri = f.toURI(); URL url = uri.toURL(); return new FileResource(url); } catch(Exception e) { Log.info("Could not create file resource"); return null; } } public void loadWebserver() { org.eclipse.jetty.util.log.Log.setLog(new JettyNullLogger()); webhostname = configuration.getString("webserver-bindaddress", "0.0.0.0"); webport = configuration.getInteger("webserver-port", 8123); webServer = new Server(); Connector connector=new SelectChannelConnector(); if(webhostname.equals("0.0.0.0") == false) connector.setHost(webhostname); connector.setPort(webport); webServer.setConnectors(new Connector[]{connector}); webServer.setStopAtShutdown(true); //webServer.setGracefulShutdown(1000); final boolean allow_symlinks = configuration.getBoolean("allow-symlinks", false); int maxconnections = configuration.getInteger("max-sessions", 30); if(maxconnections < 2) maxconnections = 2; router = new HandlerRouter() {{ this.addHandler("/", new FileLockResourceHandler() {{ this.setAliases(allow_symlinks); this.setWelcomeFiles(new String[] { "index.html" }); this.setDirectoriesListed(true); this.setBaseResource(createFileResource(getFile(getWebPath()).getAbsolutePath())); }}); this.addHandler("/tiles/*", new FileLockResourceHandler() {{ this.setAliases(allow_symlinks); this.setWelcomeFiles(new String[] { }); this.setDirectoriesListed(true); this.setBaseResource(createFileResource(tilesDirectory.getAbsolutePath())); }}); }}; if(allow_symlinks) Log.verboseinfo("Web server is permitting symbolic links"); else Log.verboseinfo("Web server is not permitting symbolic links"); List<Filter> filters = new LinkedList<Filter>(); /* Check for banned IPs */ boolean checkbannedips = configuration.getBoolean("check-banned-ips", true); if (checkbannedips) { filters.add(new BanIPFilter(this)); } /* Load customized response headers, if any */ filters.add(new CustomHeaderFilter(configuration.getNode("http-response-headers"))); webServer.setHandler(new FilterHandler(router, filters)); addServlet("/up/configuration", new org.dynmap.servlet.ClientConfigurationServlet(this)); } public Set<String> getIPBans() { return getServer().getIPBans(); } public void addServlet(String path, HttpServlet servlet) { new ServletHolder(servlet); router.addServlet(path, servlet); } public void startWebserver() { try { if(webServer != null) { webServer.start(); Log.info("Web server started on address " + webhostname + ":" + webport); } } catch (Exception e) { Log.severe("Failed to start WebServer on address " + webhostname + ":" + webport + " : " + e.getMessage()); } } public void disableCore() { if(persist_ids_by_ip) saveIDsByIP(); if (webServer != null) { try { webServer.stop(); for(int i = 0; i < 100; i++) { /* Limit wait to 10 seconds */ if(webServer.isStopping()) Thread.sleep(100); } if(webServer.isStopping()) { Log.warning("Graceful shutdown timed out - continuing to terminate"); } } catch (Exception e) { Log.severe("Failed to stop WebServer!", e); } webServer = null; } if (componentManager != null) { int componentCount = componentManager.components.size(); for(Component component : componentManager.components) { component.dispose(); } componentManager.clear(); Log.info("Unloaded " + componentCount + " components."); } if (mapManager != null) { mapManager.stopRendering(); mapManager = null; } playerfacemgr = null; /* Clean up registered listeners */ listenerManager.cleanup(); /* Don't clean up markerAPI - other plugins may still be accessing it */ Debug.clearDebuggers(); } private static File combinePaths(File parent, String path) { return combinePaths(parent, new File(path)); } private static File combinePaths(File parent, File path) { if (path.isAbsolute()) return path; return new File(parent, path.getPath()); } public File getFile(String path) { return combinePaths(getDataFolder(), path); } protected void loadDebuggers() { List<ConfigurationNode> debuggersConfiguration = configuration.getNodes("debuggers"); Debug.clearDebuggers(); for (ConfigurationNode debuggerConfiguration : debuggersConfiguration) { try { Class<?> debuggerClass = Class.forName((String) debuggerConfiguration.getString("class")); Constructor<?> constructor = debuggerClass.getConstructor(DynmapCore.class, ConfigurationNode.class); Debugger debugger = (Debugger) constructor.newInstance(this, debuggerConfiguration); Debug.addDebugger(debugger); } catch (Exception e) { Log.severe("Error loading debugger: " + e); e.printStackTrace(); continue; } } } /* Parse argument strings : handle quoted strings */ public static String[] parseArgs(String[] args, DynmapCommandSender snd) { ArrayList<String> rslt = new ArrayList<String>(); /* Build command line, so we can parse our way - make sure there is trailing space */ String cmdline = ""; for(int i = 0; i < args.length; i++) { cmdline += args[i] + " "; } boolean inquote = false; StringBuilder sb = new StringBuilder(); for(int i = 0; i < cmdline.length(); i++) { char c = cmdline.charAt(i); if(inquote) { /* If in quote, accumulate until end or another quote */ if(c == '\"') { /* End quote */ inquote = false; } else { sb.append(c); } } else if(c == '\"') { /* Start of quote? */ inquote = true; } else if(c == ' ') { /* Ending space? */ rslt.add(sb.toString()); sb.setLength(0); } else { sb.append(c); } } if(inquote) { /* If still in quote, syntax error */ snd.sendMessage("Error: unclosed doublequote"); return null; } return rslt.toArray(new String[rslt.size()]); } private static final Set<String> commands = new HashSet<String>(Arrays.asList(new String[] { "render", "hide", "show", "fullrender", "cancelrender", "radiusrender", "updaterender", "reload", "stats", "triggerstats", "resetstats", "sendtoweb", "pause", "purgequeue", "ids-for-ip", "ips-for-id", "add-id-for-ip", "del-id-for-ip"})); public boolean processCommand(DynmapCommandSender sender, String cmd, String commandLabel, String[] args) { if(cmd.equalsIgnoreCase("dmarker")) { return MarkerAPIImpl.onCommand(this, sender, cmd, commandLabel, args); } if (cmd.equalsIgnoreCase("dmap")) { return dmapcmds.processCommand(sender, cmd, commandLabel, args, this); } if (!cmd.equalsIgnoreCase("dynmap")) return false; DynmapPlayer player = null; if (sender instanceof DynmapPlayer) player = (DynmapPlayer) sender; /* Re-parse args - handle doublequotes */ args = parseArgs(args, sender); if(args == null) return false; if (args.length > 0) { String c = args[0]; if (!commands.contains(c)) { return false; } if (c.equals("render") && checkPlayerPermission(sender,"render")) { if (player != null) { DynmapLocation loc = player.getLocation(); mapManager.touch(loc.world, (int)loc.x, (int)loc.y, (int)loc.z, "render"); sender.sendMessage("Tile render queued."); } else { sender.sendMessage("Command can only be issued by player."); } } else if(c.equals("radiusrender") && checkPlayerPermission(sender,"radiusrender")) { int radius = 0; String mapname = null; DynmapLocation loc = null; if((args.length == 2) || (args.length == 3)) { /* Just radius, or <radius> <map> */ radius = Integer.parseInt(args[1]); /* Parse radius */ if(radius < 0) radius = 0; if(args.length > 2) mapname = args[2]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else if(args.length > 3) { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) radius = Integer.parseInt(args[4]); if(args.length > 5) mapname = args[5]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderWorldRadius(loc, sender, mapname, radius); } else if(c.equals("updaterender") && checkPlayerPermission(sender,"updaterender")) { String mapname = null; DynmapLocation loc = null; if(args.length <= 3) { /* Just command, or command plus map */ - if(args.length > 2) - mapname = args[2]; + if(args.length > 1) + mapname = args[1]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) mapname = args[4]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderFullWorld(loc, sender, mapname, true); } else if (c.equals("hide")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"hide.self")) { playerList.setVisible(player.getName(),false); sender.sendMessage("You are now hidden on Dynmap."); } } else if (checkPlayerPermission(sender,"hide.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],false); sender.sendMessage(args[i] + " is now hidden on Dynmap."); } } } else if (c.equals("show")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"show.self")) { playerList.setVisible(player.getName(),true); sender.sendMessage("You are now visible on Dynmap."); } } else if (checkPlayerPermission(sender,"show.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],true); sender.sendMessage(args[i] + " is now visible on Dynmap."); } } } else if (c.equals("fullrender") && checkPlayerPermission(sender,"fullrender")) { String map = null; if (args.length > 1) { for (int i = 1; i < args.length; i++) { int dot = args[i].indexOf(":"); DynmapWorld w; String wname = args[i]; if(dot >= 0) { wname = args[i].substring(0, dot); map = args[i].substring(dot+1); } w = mapManager.getWorld(wname); if(w != null) { DynmapLocation loc; if(w.center != null) loc = w.center; else loc = w.getSpawnLocation(); mapManager.renderFullWorld(loc,sender, map, false); } else sender.sendMessage("World '" + wname + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(args.length > 1) map = args[1]; if(loc != null) mapManager.renderFullWorld(loc, sender, map, false); } else { sender.sendMessage("World name is required"); } } else if (c.equals("cancelrender") && checkPlayerPermission(sender,"cancelrender")) { if (args.length > 1) { for (int i = 1; i < args.length; i++) { DynmapWorld w = mapManager.getWorld(args[i]); if(w != null) mapManager.cancelRender(w.getName(), sender); else sender.sendMessage("World '" + args[i] + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(loc != null) mapManager.cancelRender(loc.world, sender); } else { sender.sendMessage("World name is required"); } } else if (c.equals("purgequeue") && checkPlayerPermission(sender, "purgequeue")) { mapManager.purgeQueue(sender); } else if (c.equals("reload") && checkPlayerPermission(sender, "reload")) { sender.sendMessage("Reloading Dynmap..."); getServer().reload(); sender.sendMessage("Dynmap reloaded"); } else if (c.equals("stats") && checkPlayerPermission(sender, "stats")) { if(args.length == 1) mapManager.printStats(sender, null); else mapManager.printStats(sender, args[1]); } else if (c.equals("triggerstats") && checkPlayerPermission(sender, "stats")) { mapManager.printTriggerStats(sender); } else if (c.equals("pause") && checkPlayerPermission(sender, "pause")) { if(args.length == 1) { } else if(args[1].equals("full")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(false); } else if(args[1].equals("update")) { setPauseFullRadiusRenders(false); setPauseUpdateRenders(true); } else if(args[1].equals("all")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(true); } else { setPauseFullRadiusRenders(false); setPauseUpdateRenders(false); } if(getPauseFullRadiusRenders()) sender.sendMessage("Full/Radius renders are PAUSED"); else sender.sendMessage("Full/Radius renders are ACTIVE"); if(getPauseUpdateRenders()) sender.sendMessage("Update renders are PAUSED"); else sender.sendMessage("Update renders are ACTIVE"); } else if (c.equals("resetstats") && checkPlayerPermission(sender, "resetstats")) { if(args.length == 1) mapManager.resetStats(sender, null); else mapManager.resetStats(sender, args[1]); } else if (c.equals("sendtoweb") && checkPlayerPermission(sender, "sendtoweb")) { String msg = ""; for(int i = 1; i < args.length; i++) { msg += args[i] + " "; } this.sendBroadcastToWeb("dynmap", msg); } else if(c.equals("ids-for-ip") && checkPlayerPermission(sender, "ids-for-ip")) { if(args.length > 1) { List<String> ids = getIDsForIP(args[1]); sender.sendMessage("IDs logged in from address " + args[1] + " (most recent to least):"); if(ids != null) { for(String id : ids) sender.sendMessage(" " + id); } } else { sender.sendMessage("IP address required as parameter"); } } else if(c.equals("ips-for-id") && checkPlayerPermission(sender, "ips-for-id")) { if(args.length > 1) { sender.sendMessage("IP addresses logged for player " + args[1] + ":"); for(String ip: ids_by_ip.keySet()) { LinkedList<String> ids = ids_by_ip.get(ip); if((ids != null) && ids.contains(args[1])) { sender.sendMessage(" " + ip); } } } else { sender.sendMessage("Player ID required as parameter"); } } else if((c.equals("add-id-for-ip") && checkPlayerPermission(sender, "add-id-for-ip")) || (c.equals("del-id-for-ip") && checkPlayerPermission(sender, "del-id-for-ip"))) { if(args.length > 2) { String ipaddr = ""; try { InetAddress ip = InetAddress.getByName(args[2]); ipaddr = ip.getHostAddress(); } catch (UnknownHostException uhx) { sender.sendMessage("Invalid address : " + args[2]); return false; } LinkedList<String> ids = ids_by_ip.get(ipaddr); if(ids == null) { ids = new LinkedList<String>(); ids_by_ip.put(ipaddr, ids); } ids.remove(args[1]); /* Remove existing, if any */ if(c.equals("add-id-for-ip")) { ids.addFirst(args[1]); /* And add us first */ sender.sendMessage("Added player ID '" + args[1] + "' to address '" + ipaddr + "'"); } else { sender.sendMessage("Removed player ID '" + args[1] + "' from address '" + ipaddr + "'"); } saveIDsByIP(); } else { sender.sendMessage("Needs player ID and IP address"); } } return true; } return false; } public boolean checkPlayerPermission(DynmapCommandSender sender, String permission) { if (!(sender instanceof DynmapPlayer) || sender.isOp()) { return true; } else if (!sender.hasPrivilege(permission.toLowerCase())) { sender.sendMessage("You don't have permission to use this command!"); return false; } return true; } public ConfigurationNode getWorldConfiguration(DynmapWorld world) { String wname = world.getName(); ConfigurationNode finalConfiguration = new ConfigurationNode(); finalConfiguration.put("name", wname); finalConfiguration.put("title", wname); ConfigurationNode worldConfiguration = getWorldConfigurationNode(wname); // Get the template. ConfigurationNode templateConfiguration = null; if (worldConfiguration != null) { String templateName = worldConfiguration.getString("template"); if (templateName != null) { templateConfiguration = getTemplateConfigurationNode(templateName); } } // Template not found, using default template. if (templateConfiguration == null) { templateConfiguration = getDefaultTemplateConfigurationNode(world); } // Merge the finalConfiguration, templateConfiguration and worldConfiguration. finalConfiguration.extend(templateConfiguration); finalConfiguration.extend(worldConfiguration); Log.verboseinfo("Configuration of world " + world.getName()); for(Map.Entry<String, Object> e : finalConfiguration.entrySet()) { Log.verboseinfo(e.getKey() + ": " + e.getValue()); } /* Update world_config with final */ List<Map<String,Object>> worlds = world_config.getMapList("worlds"); if(worlds == null) { worlds = new ArrayList<Map<String,Object>>(); world_config.put("worlds", worlds); } boolean did_upd = false; for(int idx = 0; idx < worlds.size(); idx++) { Map<String,Object> m = worlds.get(idx); if(wname.equals(m.get("name"))) { worlds.set(idx, finalConfiguration); did_upd = true; break; } } if(!did_upd) worlds.add(finalConfiguration); return finalConfiguration; } ConfigurationNode getDefaultTemplateConfigurationNode(DynmapWorld world) { String environmentName = world.getEnvironment(); if(deftemplatesuffix.length() > 0) { environmentName += "-" + deftemplatesuffix; } Log.verboseinfo("Using environment as template: " + environmentName); return getTemplateConfigurationNode(environmentName); } private ConfigurationNode getWorldConfigurationNode(String worldName) { worldName = DynmapWorld.normalizeWorldName(worldName); for(ConfigurationNode worldNode : world_config.getNodes("worlds")) { if (worldName.equals(worldNode.getString("name"))) { return worldNode; } } return new ConfigurationNode(); } ConfigurationNode getTemplateConfigurationNode(String templateName) { ConfigurationNode templatesNode = configuration.getNode("templates"); if (templatesNode != null) { return templatesNode.getNode(templateName); } return null; } public String getWebPath() { return configuration.getString("webpath", "web"); } public static void setIgnoreChunkLoads(boolean ignore) { ignore_chunk_loads = ignore; } /* Uses resource to create default file, if file does not yet exist */ public boolean createDefaultFileFromResource(String resourcename, File deffile) { if(deffile.canRead()) return true; Log.info(deffile.getPath() + " not found - creating default"); InputStream in = getClass().getResourceAsStream(resourcename); if(in == null) { Log.severe("Unable to find default resource - " + resourcename); return false; } else { FileOutputStream fos = null; try { fos = new FileOutputStream(deffile); byte[] buf = new byte[512]; int len; while((len = in.read(buf)) > 0) { fos.write(buf, 0, len); } } catch (IOException iox) { Log.severe("ERROR creatomg default for " + deffile.getPath()); return false; } finally { if(fos != null) try { fos.close(); } catch (IOException iox) {} if(in != null) try { in.close(); } catch (IOException iox) {} } return true; } } /* * Add in any missing sections to existing file, using resource */ public boolean updateUsingDefaultResource(String resourcename, File deffile, String basenode) { InputStream in = getClass().getResourceAsStream(resourcename); if(in == null) { Log.severe("Unable to find resource - " + resourcename); return false; } if(deffile.canRead() == false) { /* Doesn't exist? */ return createDefaultFileFromResource(resourcename, deffile); } /* Load default from resource */ ConfigurationNode def_fc = new ConfigurationNode(in); /* Load existing from file */ ConfigurationNode fc = new ConfigurationNode(deffile); fc.load(); /* Now, get the list associated with the base node default */ List<Map<String,Object>> existing = fc.getMapList(basenode); Set<String> existing_names = new HashSet<String>(); /* Make map, indexed by 'name' in map */ if(existing != null) { for(Map<String,Object> m : existing) { Object name = m.get("name"); if(name instanceof String) existing_names.add((String)name); } } boolean did_update = false; /* Now, loop through defaults, and see if any are missing */ List<Map<String,Object>> defmaps = def_fc.getMapList(basenode); if(defmaps != null) { for(Map<String,Object> m : defmaps) { Object name = m.get("name"); if(name instanceof String) { /* If not an existing one, need to add it */ if(existing_names.contains((String)name) == false) { existing.add(m); did_update = true; } } } } /* If we did update, save existing */ if(did_update) { fc.put(basenode, existing); fc.save(deffile); Log.info("Updated file " + deffile.getPath()); } return true; } /** * ** This is the public API for other plugins to use for accessing the Marker API ** * This method can return null if the 'markers' component has not been configured - * a warning message will be issued to the server.log in this event. * * @return MarkerAPI, or null if not configured */ public MarkerAPI getMarkerAPI() { if(markerapi == null) { Log.warning("Marker API has been requested, but is not enabled. Uncomment or add 'markers' component to configuration.txt."); } return markerapi; } public boolean markerAPIInitialized() { return (markerapi != null); } /** * Send generic message to all web users * @param sender - label for sender of message ("[<sender>] nessage") - if null, no from notice * @param msg - message to be sent */ public boolean sendBroadcastToWeb(String sender, String msg) { if(mapManager != null) { mapManager.pushUpdate(new Client.ChatMessage("plugin", sender, "", msg, "")); return true; } return false; } /** * Register markers API - used by component to supply marker API to plugin */ public void registerMarkerAPI(MarkerAPIImpl api) { markerapi = api; } /* * Pause full/radius render processing * @param dopause - true to pause, false to unpause */ public void setPauseFullRadiusRenders(boolean dopause) { mapManager.setPauseFullRadiusRenders(dopause); } /* * Test if full renders are paused */ public boolean getPauseFullRadiusRenders() { return mapManager.getPauseFullRadiusRenders(); } /* * Pause update render processing * @param dopause - true to pause, false to unpause */ public void setPauseUpdateRenders(boolean dopause) { mapManager.setPauseUpdateRenders(dopause); } /* * Test if update renders are paused */ public boolean getPauseUpdateRenders() { return mapManager.getPauseUpdateRenders(); } /** * Get list of IDs seen on give IP (most recent to least recent) */ public List<String> getIDsForIP(InetAddress addr) { return getIDsForIP(addr.getHostAddress()); } /** * Get list of IDs seen on give IP (most recent to least recent) */ public List<String> getIDsForIP(String ip) { LinkedList<String> ids = ids_by_ip.get(ip); if(ids != null) return new ArrayList<String>(ids); return null; } private void loadIDsByIP() { File f = new File(getDataFolder(), "ids-by-ip.txt"); if(f.exists() == false) return; ConfigurationNode fc = new ConfigurationNode(new File(getDataFolder(), "ids-by-ip.txt")); try { fc.load(); ids_by_ip.clear(); for(String k : fc.keySet()) { List<String> ids = fc.getList(k); if(ids != null) { k = k.replace("_", "."); ids_by_ip.put(k, new LinkedList<String>(ids)); } } } catch (Exception iox) { Log.severe("Error loading " + f.getPath() + " - " + iox.getMessage()); } } private void saveIDsByIP() { File f = new File(getDataFolder(), "ids-by-ip.txt"); ConfigurationNode fc = new ConfigurationNode(); for(String k : ids_by_ip.keySet()) { List<String> v = ids_by_ip.get(k); if(v != null) { k = k.replace(".", "_"); fc.put(k, v); } } try { fc.save(f); } catch (Exception x) { Log.severe("Error saving " + f.getPath() + " - " + x.getMessage()); } } public void setPlayerVisiblity(String player, boolean is_visible) { playerList.setVisible(player, is_visible); } public boolean getPlayerVisbility(String player) { return playerList.isVisiblePlayer(player); } public void assertPlayerInvisibility(String player, boolean is_invisible, String plugin_id) { playerList.assertInvisiblilty(player, is_invisible, plugin_id); } public void assertPlayerVisibility(String player, boolean is_visible, String plugin_id) { playerList.assertVisiblilty(player, is_visible, plugin_id); } public void postPlayerMessageToWeb(String playerid, String playerdisplay, String message) { if(playerdisplay == null) playerdisplay = playerid; if(mapManager != null) mapManager.pushUpdate(new Client.ChatMessage("player", "", playerdisplay, message, playerid)); } public void postPlayerJoinQuitToWeb(String playerid, String playerdisplay, boolean isjoin) { if(playerdisplay == null) playerdisplay = playerid; if((mapManager != null) && (playerList != null) && (playerList.isVisiblePlayer(playerid))) { if(isjoin) mapManager.pushUpdate(new Client.PlayerJoinMessage(playerid, playerdisplay)); else mapManager.pushUpdate(new Client.PlayerQuitMessage(playerid, playerdisplay)); } } public String getDynmapCoreVersion() { return version; } public String getDynmapPluginVersion() { return plugin_ver; } public int triggerRenderOfBlock(String wid, int x, int y, int z) { if(mapManager != null) mapManager.touch(wid, x, y, z, "api"); return 0; } public int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz) { if(mapManager != null) { if((minx == maxx) && (miny == maxy) && (minz == maxz)) mapManager.touch(wid, minx, miny, minz, "api"); else mapManager.touchVolume(wid, minx, miny, minz, maxx, maxy, maxz, "api"); } return 0; } public boolean isTrigger(String s) { return enabledTriggers.contains(s); } public DynmapWorld getWorld(String wid) { if(mapManager != null) return mapManager.getWorld(wid); return null; } /* Called by plugin when world loaded */ public boolean processWorldLoad(DynmapWorld w) { return mapManager.activateWorld(w); } /* Enable/disable world */ public boolean setWorldEnable(String wname, boolean isenab) { wname = DynmapWorld.normalizeWorldName(wname); List<Map<String,Object>> worlds = world_config.getMapList("worlds"); for(Map<String,Object> m : worlds) { String wn = (String)m.get("name"); if((wn != null) && (wn.equals(wname))) { m.put("enabled", isenab); return true; } } /* If not found, and disable, add disable node */ if(isenab == false) { Map<String,Object> newworld = new LinkedHashMap<String,Object>(); newworld.put("name", wname); newworld.put("enabled", isenab); } return true; } public boolean setWorldZoomOut(String wname, int xzoomout) { wname = DynmapWorld.normalizeWorldName(wname); List<Map<String,Object>> worlds = world_config.getMapList("worlds"); for(Map<String,Object> m : worlds) { String wn = (String)m.get("name"); if((wn != null) && (wn.equals(wname))) { m.put("extrazoomout", xzoomout); return true; } } return false; } public boolean setWorldCenter(String wname, DynmapLocation loc) { wname = DynmapWorld.normalizeWorldName(wname); List<Map<String,Object>> worlds = world_config.getMapList("worlds"); for(Map<String,Object> m : worlds) { String wn = (String)m.get("name"); if((wn != null) && (wn.equals(wname))) { if(loc != null) { Map<String,Object> c = new LinkedHashMap<String,Object>(); c.put("x", loc.x); c.put("y", loc.y); c.put("z", loc.z); m.put("center", c); } else { m.remove("center"); } return true; } } return false; } public boolean setWorldOrder(String wname, int order) { wname = DynmapWorld.normalizeWorldName(wname); List<Map<String,Object>> worlds = world_config.getMapList("worlds"); ArrayList<Map<String,Object>> newworlds = new ArrayList<Map<String,Object>>(worlds); Map<String,Object> w = null; for(Map<String,Object> m : worlds) { String wn = (String)m.get("name"); if((wn != null) && (wn.equals(wname))) { w = m; newworlds.remove(m); /* Remove from list */ break; } } if(w != null) { /* If found it, add back at right pount */ if(order >= newworlds.size()) { /* At end? */ newworlds.add(w); } else { newworlds.add(order, w); } world_config.put("worlds", newworlds); return true; } return false; } public boolean updateWorldConfig(DynmapWorld w) { ConfigurationNode cn = w.saveConfiguration(); return replaceWorldConfig(w.getName(), cn); } public boolean replaceWorldConfig(String wname, ConfigurationNode cn) { wname = DynmapWorld.normalizeWorldName(wname); List<Map<String,Object>> worlds = world_config.getMapList("worlds"); if(worlds == null) { worlds = new ArrayList<Map<String,Object>>(); world_config.put("worlds", worlds); } for(int i = 0; i < worlds.size(); i++) { Map<String,Object> m = worlds.get(i); String wn = (String)m.get("name"); if((wn != null) && (wn.equals(wname))) { worlds.set(i, cn.entries); /* Replace */ return true; } } return false; } public boolean saveWorldConfig() { boolean rslt = world_config.save(); /* Save world config */ updateConfigHashcode(); /* Update config hashcode */ return rslt; } /* Refresh world config */ public boolean refreshWorld(String wname) { wname = DynmapWorld.normalizeWorldName(wname); saveWorldConfig(); if(mapManager != null) { mapManager.deactivateWorld(wname); /* Clean it up */ DynmapWorld w = getServer().getWorldByName(wname); /* Get new instance */ if(w != null) mapManager.activateWorld(w); /* And activate it again */ } return true; } /* Load core version */ private void loadVersion() { InputStream in = getClass().getResourceAsStream("/core.yml"); if(in == null) return; Yaml yaml = new Yaml(); @SuppressWarnings("unchecked") Map<String,Object> val = (Map<String,Object>)yaml.load(in); if(val != null) version = (String)val.get("version"); } public int getSnapShotCacheSize() { return snapshotcachesize; } public String getDefImageFormat() { return def_image_format; } public void webChat(final String name, final String message) { if(mapManager == null) return; Runnable c = new Runnable() { @Override public void run() { mapManager.pushUpdate(new Client.ChatMessage("web", null, name, message, null)); String msgfmt = configuration.getString("webmsgformat", null); if(msgfmt != null) { msgfmt = ClientComponent.unescapeString(msgfmt); Log.info(msgfmt.replace("%playername%", name).replace("%message%", message)); } else { Log.info(ClientComponent.unescapeString(configuration.getString("webprefix", "\u00A72[WEB] ")) + name + ": " + ClientComponent.unescapeString(configuration.getString("websuffix", "\u00A7f")) + message); } ChatEvent event = new ChatEvent("web", name, message); events.trigger("webchat", event); } }; getServer().scheduleServerTask(c, 1); } /** * Disable chat message processing (used by mods that will handle sending chat to the web themselves, via sendBroadcastToWeb() * @param disable - if true, suppress internal chat-to-web messages */ public boolean setDisableChatToWebProcessing(boolean disable) { boolean prev = disable_chat_to_web; disable_chat_to_web = disable; return prev; } }
true
true
public boolean processCommand(DynmapCommandSender sender, String cmd, String commandLabel, String[] args) { if(cmd.equalsIgnoreCase("dmarker")) { return MarkerAPIImpl.onCommand(this, sender, cmd, commandLabel, args); } if (cmd.equalsIgnoreCase("dmap")) { return dmapcmds.processCommand(sender, cmd, commandLabel, args, this); } if (!cmd.equalsIgnoreCase("dynmap")) return false; DynmapPlayer player = null; if (sender instanceof DynmapPlayer) player = (DynmapPlayer) sender; /* Re-parse args - handle doublequotes */ args = parseArgs(args, sender); if(args == null) return false; if (args.length > 0) { String c = args[0]; if (!commands.contains(c)) { return false; } if (c.equals("render") && checkPlayerPermission(sender,"render")) { if (player != null) { DynmapLocation loc = player.getLocation(); mapManager.touch(loc.world, (int)loc.x, (int)loc.y, (int)loc.z, "render"); sender.sendMessage("Tile render queued."); } else { sender.sendMessage("Command can only be issued by player."); } } else if(c.equals("radiusrender") && checkPlayerPermission(sender,"radiusrender")) { int radius = 0; String mapname = null; DynmapLocation loc = null; if((args.length == 2) || (args.length == 3)) { /* Just radius, or <radius> <map> */ radius = Integer.parseInt(args[1]); /* Parse radius */ if(radius < 0) radius = 0; if(args.length > 2) mapname = args[2]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else if(args.length > 3) { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) radius = Integer.parseInt(args[4]); if(args.length > 5) mapname = args[5]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderWorldRadius(loc, sender, mapname, radius); } else if(c.equals("updaterender") && checkPlayerPermission(sender,"updaterender")) { String mapname = null; DynmapLocation loc = null; if(args.length <= 3) { /* Just command, or command plus map */ if(args.length > 2) mapname = args[2]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) mapname = args[4]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderFullWorld(loc, sender, mapname, true); } else if (c.equals("hide")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"hide.self")) { playerList.setVisible(player.getName(),false); sender.sendMessage("You are now hidden on Dynmap."); } } else if (checkPlayerPermission(sender,"hide.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],false); sender.sendMessage(args[i] + " is now hidden on Dynmap."); } } } else if (c.equals("show")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"show.self")) { playerList.setVisible(player.getName(),true); sender.sendMessage("You are now visible on Dynmap."); } } else if (checkPlayerPermission(sender,"show.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],true); sender.sendMessage(args[i] + " is now visible on Dynmap."); } } } else if (c.equals("fullrender") && checkPlayerPermission(sender,"fullrender")) { String map = null; if (args.length > 1) { for (int i = 1; i < args.length; i++) { int dot = args[i].indexOf(":"); DynmapWorld w; String wname = args[i]; if(dot >= 0) { wname = args[i].substring(0, dot); map = args[i].substring(dot+1); } w = mapManager.getWorld(wname); if(w != null) { DynmapLocation loc; if(w.center != null) loc = w.center; else loc = w.getSpawnLocation(); mapManager.renderFullWorld(loc,sender, map, false); } else sender.sendMessage("World '" + wname + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(args.length > 1) map = args[1]; if(loc != null) mapManager.renderFullWorld(loc, sender, map, false); } else { sender.sendMessage("World name is required"); } } else if (c.equals("cancelrender") && checkPlayerPermission(sender,"cancelrender")) { if (args.length > 1) { for (int i = 1; i < args.length; i++) { DynmapWorld w = mapManager.getWorld(args[i]); if(w != null) mapManager.cancelRender(w.getName(), sender); else sender.sendMessage("World '" + args[i] + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(loc != null) mapManager.cancelRender(loc.world, sender); } else { sender.sendMessage("World name is required"); } } else if (c.equals("purgequeue") && checkPlayerPermission(sender, "purgequeue")) { mapManager.purgeQueue(sender); } else if (c.equals("reload") && checkPlayerPermission(sender, "reload")) { sender.sendMessage("Reloading Dynmap..."); getServer().reload(); sender.sendMessage("Dynmap reloaded"); } else if (c.equals("stats") && checkPlayerPermission(sender, "stats")) { if(args.length == 1) mapManager.printStats(sender, null); else mapManager.printStats(sender, args[1]); } else if (c.equals("triggerstats") && checkPlayerPermission(sender, "stats")) { mapManager.printTriggerStats(sender); } else if (c.equals("pause") && checkPlayerPermission(sender, "pause")) { if(args.length == 1) { } else if(args[1].equals("full")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(false); } else if(args[1].equals("update")) { setPauseFullRadiusRenders(false); setPauseUpdateRenders(true); } else if(args[1].equals("all")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(true); } else { setPauseFullRadiusRenders(false); setPauseUpdateRenders(false); } if(getPauseFullRadiusRenders()) sender.sendMessage("Full/Radius renders are PAUSED"); else sender.sendMessage("Full/Radius renders are ACTIVE"); if(getPauseUpdateRenders()) sender.sendMessage("Update renders are PAUSED"); else sender.sendMessage("Update renders are ACTIVE"); } else if (c.equals("resetstats") && checkPlayerPermission(sender, "resetstats")) { if(args.length == 1) mapManager.resetStats(sender, null); else mapManager.resetStats(sender, args[1]); } else if (c.equals("sendtoweb") && checkPlayerPermission(sender, "sendtoweb")) { String msg = ""; for(int i = 1; i < args.length; i++) { msg += args[i] + " "; } this.sendBroadcastToWeb("dynmap", msg); } else if(c.equals("ids-for-ip") && checkPlayerPermission(sender, "ids-for-ip")) { if(args.length > 1) { List<String> ids = getIDsForIP(args[1]); sender.sendMessage("IDs logged in from address " + args[1] + " (most recent to least):"); if(ids != null) { for(String id : ids) sender.sendMessage(" " + id); } } else { sender.sendMessage("IP address required as parameter"); } } else if(c.equals("ips-for-id") && checkPlayerPermission(sender, "ips-for-id")) { if(args.length > 1) { sender.sendMessage("IP addresses logged for player " + args[1] + ":"); for(String ip: ids_by_ip.keySet()) { LinkedList<String> ids = ids_by_ip.get(ip); if((ids != null) && ids.contains(args[1])) { sender.sendMessage(" " + ip); } } } else { sender.sendMessage("Player ID required as parameter"); } } else if((c.equals("add-id-for-ip") && checkPlayerPermission(sender, "add-id-for-ip")) || (c.equals("del-id-for-ip") && checkPlayerPermission(sender, "del-id-for-ip"))) { if(args.length > 2) { String ipaddr = ""; try { InetAddress ip = InetAddress.getByName(args[2]); ipaddr = ip.getHostAddress(); } catch (UnknownHostException uhx) { sender.sendMessage("Invalid address : " + args[2]); return false; } LinkedList<String> ids = ids_by_ip.get(ipaddr); if(ids == null) { ids = new LinkedList<String>(); ids_by_ip.put(ipaddr, ids); } ids.remove(args[1]); /* Remove existing, if any */ if(c.equals("add-id-for-ip")) { ids.addFirst(args[1]); /* And add us first */ sender.sendMessage("Added player ID '" + args[1] + "' to address '" + ipaddr + "'"); } else { sender.sendMessage("Removed player ID '" + args[1] + "' from address '" + ipaddr + "'"); } saveIDsByIP(); } else { sender.sendMessage("Needs player ID and IP address"); } } return true; } return false; }
public boolean processCommand(DynmapCommandSender sender, String cmd, String commandLabel, String[] args) { if(cmd.equalsIgnoreCase("dmarker")) { return MarkerAPIImpl.onCommand(this, sender, cmd, commandLabel, args); } if (cmd.equalsIgnoreCase("dmap")) { return dmapcmds.processCommand(sender, cmd, commandLabel, args, this); } if (!cmd.equalsIgnoreCase("dynmap")) return false; DynmapPlayer player = null; if (sender instanceof DynmapPlayer) player = (DynmapPlayer) sender; /* Re-parse args - handle doublequotes */ args = parseArgs(args, sender); if(args == null) return false; if (args.length > 0) { String c = args[0]; if (!commands.contains(c)) { return false; } if (c.equals("render") && checkPlayerPermission(sender,"render")) { if (player != null) { DynmapLocation loc = player.getLocation(); mapManager.touch(loc.world, (int)loc.x, (int)loc.y, (int)loc.z, "render"); sender.sendMessage("Tile render queued."); } else { sender.sendMessage("Command can only be issued by player."); } } else if(c.equals("radiusrender") && checkPlayerPermission(sender,"radiusrender")) { int radius = 0; String mapname = null; DynmapLocation loc = null; if((args.length == 2) || (args.length == 3)) { /* Just radius, or <radius> <map> */ radius = Integer.parseInt(args[1]); /* Parse radius */ if(radius < 0) radius = 0; if(args.length > 2) mapname = args[2]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else if(args.length > 3) { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) radius = Integer.parseInt(args[4]); if(args.length > 5) mapname = args[5]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderWorldRadius(loc, sender, mapname, radius); } else if(c.equals("updaterender") && checkPlayerPermission(sender,"updaterender")) { String mapname = null; DynmapLocation loc = null; if(args.length <= 3) { /* Just command, or command plus map */ if(args.length > 1) mapname = args[1]; if (player != null) loc = player.getLocation(); else sender.sendMessage("Command require <world> <x> <z> <radius> if issued from console."); } else { /* <world> <x> <z> */ DynmapWorld w = mapManager.worldsLookup.get(args[1]); /* Look up world */ if(w == null) { sender.sendMessage("World '" + args[1] + "' not defined/loaded"); } int x = 0, z = 0; x = Integer.parseInt(args[2]); z = Integer.parseInt(args[3]); if(args.length > 4) mapname = args[4]; if(w != null) loc = new DynmapLocation(w.getName(), x, 64, z); } if(loc != null) mapManager.renderFullWorld(loc, sender, mapname, true); } else if (c.equals("hide")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"hide.self")) { playerList.setVisible(player.getName(),false); sender.sendMessage("You are now hidden on Dynmap."); } } else if (checkPlayerPermission(sender,"hide.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],false); sender.sendMessage(args[i] + " is now hidden on Dynmap."); } } } else if (c.equals("show")) { if (args.length == 1) { if(player != null && checkPlayerPermission(sender,"show.self")) { playerList.setVisible(player.getName(),true); sender.sendMessage("You are now visible on Dynmap."); } } else if (checkPlayerPermission(sender,"show.others")) { for (int i = 1; i < args.length; i++) { playerList.setVisible(args[i],true); sender.sendMessage(args[i] + " is now visible on Dynmap."); } } } else if (c.equals("fullrender") && checkPlayerPermission(sender,"fullrender")) { String map = null; if (args.length > 1) { for (int i = 1; i < args.length; i++) { int dot = args[i].indexOf(":"); DynmapWorld w; String wname = args[i]; if(dot >= 0) { wname = args[i].substring(0, dot); map = args[i].substring(dot+1); } w = mapManager.getWorld(wname); if(w != null) { DynmapLocation loc; if(w.center != null) loc = w.center; else loc = w.getSpawnLocation(); mapManager.renderFullWorld(loc,sender, map, false); } else sender.sendMessage("World '" + wname + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(args.length > 1) map = args[1]; if(loc != null) mapManager.renderFullWorld(loc, sender, map, false); } else { sender.sendMessage("World name is required"); } } else if (c.equals("cancelrender") && checkPlayerPermission(sender,"cancelrender")) { if (args.length > 1) { for (int i = 1; i < args.length; i++) { DynmapWorld w = mapManager.getWorld(args[i]); if(w != null) mapManager.cancelRender(w.getName(), sender); else sender.sendMessage("World '" + args[i] + "' not defined/loaded"); } } else if (player != null) { DynmapLocation loc = player.getLocation(); if(loc != null) mapManager.cancelRender(loc.world, sender); } else { sender.sendMessage("World name is required"); } } else if (c.equals("purgequeue") && checkPlayerPermission(sender, "purgequeue")) { mapManager.purgeQueue(sender); } else if (c.equals("reload") && checkPlayerPermission(sender, "reload")) { sender.sendMessage("Reloading Dynmap..."); getServer().reload(); sender.sendMessage("Dynmap reloaded"); } else if (c.equals("stats") && checkPlayerPermission(sender, "stats")) { if(args.length == 1) mapManager.printStats(sender, null); else mapManager.printStats(sender, args[1]); } else if (c.equals("triggerstats") && checkPlayerPermission(sender, "stats")) { mapManager.printTriggerStats(sender); } else if (c.equals("pause") && checkPlayerPermission(sender, "pause")) { if(args.length == 1) { } else if(args[1].equals("full")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(false); } else if(args[1].equals("update")) { setPauseFullRadiusRenders(false); setPauseUpdateRenders(true); } else if(args[1].equals("all")) { setPauseFullRadiusRenders(true); setPauseUpdateRenders(true); } else { setPauseFullRadiusRenders(false); setPauseUpdateRenders(false); } if(getPauseFullRadiusRenders()) sender.sendMessage("Full/Radius renders are PAUSED"); else sender.sendMessage("Full/Radius renders are ACTIVE"); if(getPauseUpdateRenders()) sender.sendMessage("Update renders are PAUSED"); else sender.sendMessage("Update renders are ACTIVE"); } else if (c.equals("resetstats") && checkPlayerPermission(sender, "resetstats")) { if(args.length == 1) mapManager.resetStats(sender, null); else mapManager.resetStats(sender, args[1]); } else if (c.equals("sendtoweb") && checkPlayerPermission(sender, "sendtoweb")) { String msg = ""; for(int i = 1; i < args.length; i++) { msg += args[i] + " "; } this.sendBroadcastToWeb("dynmap", msg); } else if(c.equals("ids-for-ip") && checkPlayerPermission(sender, "ids-for-ip")) { if(args.length > 1) { List<String> ids = getIDsForIP(args[1]); sender.sendMessage("IDs logged in from address " + args[1] + " (most recent to least):"); if(ids != null) { for(String id : ids) sender.sendMessage(" " + id); } } else { sender.sendMessage("IP address required as parameter"); } } else if(c.equals("ips-for-id") && checkPlayerPermission(sender, "ips-for-id")) { if(args.length > 1) { sender.sendMessage("IP addresses logged for player " + args[1] + ":"); for(String ip: ids_by_ip.keySet()) { LinkedList<String> ids = ids_by_ip.get(ip); if((ids != null) && ids.contains(args[1])) { sender.sendMessage(" " + ip); } } } else { sender.sendMessage("Player ID required as parameter"); } } else if((c.equals("add-id-for-ip") && checkPlayerPermission(sender, "add-id-for-ip")) || (c.equals("del-id-for-ip") && checkPlayerPermission(sender, "del-id-for-ip"))) { if(args.length > 2) { String ipaddr = ""; try { InetAddress ip = InetAddress.getByName(args[2]); ipaddr = ip.getHostAddress(); } catch (UnknownHostException uhx) { sender.sendMessage("Invalid address : " + args[2]); return false; } LinkedList<String> ids = ids_by_ip.get(ipaddr); if(ids == null) { ids = new LinkedList<String>(); ids_by_ip.put(ipaddr, ids); } ids.remove(args[1]); /* Remove existing, if any */ if(c.equals("add-id-for-ip")) { ids.addFirst(args[1]); /* And add us first */ sender.sendMessage("Added player ID '" + args[1] + "' to address '" + ipaddr + "'"); } else { sender.sendMessage("Removed player ID '" + args[1] + "' from address '" + ipaddr + "'"); } saveIDsByIP(); } else { sender.sendMessage("Needs player ID and IP address"); } } return true; } return false; }
diff --git a/src/com/android/settings/ChooseLockPassword.java b/src/com/android/settings/ChooseLockPassword.java index 018dfd2aa..a0f23465e 100644 --- a/src/com/android/settings/ChooseLockPassword.java +++ b/src/com/android/settings/ChooseLockPassword.java @@ -1,461 +1,461 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import com.android.internal.widget.LockPatternUtils; import com.android.internal.widget.PasswordEntryKeyboardHelper; import com.android.internal.widget.PasswordEntryKeyboardView; import android.app.Activity; import android.app.Fragment; import android.app.admin.DevicePolicyManager; import android.content.Intent; import android.inputmethodservice.KeyboardView; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceActivity; import android.text.Editable; import android.text.InputType; import android.text.Selection; import android.text.Spannable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class ChooseLockPassword extends PreferenceActivity { public static final String PASSWORD_MIN_KEY = "lockscreen.password_min"; public static final String PASSWORD_MAX_KEY = "lockscreen.password_max"; public static final String PASSWORD_MIN_LETTERS_KEY = "lockscreen.password_min_letters"; public static final String PASSWORD_MIN_LOWERCASE_KEY = "lockscreen.password_min_lowercase"; public static final String PASSWORD_MIN_UPPERCASE_KEY = "lockscreen.password_min_uppercase"; public static final String PASSWORD_MIN_NUMERIC_KEY = "lockscreen.password_min_numeric"; public static final String PASSWORD_MIN_SYMBOLS_KEY = "lockscreen.password_min_symbols"; public static final String PASSWORD_MIN_NONLETTER_KEY = "lockscreen.password_min_nonletter"; @Override public Intent getIntent() { Intent modIntent = new Intent(super.getIntent()); modIntent.putExtra(EXTRA_SHOW_FRAGMENT, ChooseLockPasswordFragment.class.getName()); modIntent.putExtra(EXTRA_NO_HEADERS, true); return modIntent; } @Override public void onCreate(Bundle savedInstanceState) { // TODO: Fix on phones // Disable IME on our window since we provide our own keyboard //getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, //WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); super.onCreate(savedInstanceState); CharSequence msg = getText(R.string.lockpassword_choose_your_password_header); showBreadCrumbs(msg, msg); } public static class ChooseLockPasswordFragment extends Fragment implements OnClickListener, OnEditorActionListener, TextWatcher { private static final String KEY_FIRST_PIN = "first_pin"; private static final String KEY_UI_STAGE = "ui_stage"; private TextView mPasswordEntry; private int mPasswordMinLength = 4; private int mPasswordMaxLength = 16; private int mPasswordMinLetters = 0; private int mPasswordMinUpperCase = 0; private int mPasswordMinLowerCase = 0; private int mPasswordMinSymbols = 0; private int mPasswordMinNumeric = 0; private int mPasswordMinNonLetter = 0; private LockPatternUtils mLockPatternUtils; private int mRequestedQuality = DevicePolicyManager.PASSWORD_QUALITY_NUMERIC; private ChooseLockSettingsHelper mChooseLockSettingsHelper; private Stage mUiStage = Stage.Introduction; private TextView mHeaderText; private String mFirstPin; private KeyboardView mKeyboardView; private PasswordEntryKeyboardHelper mKeyboardHelper; private boolean mIsAlphaMode; private Button mCancelButton; private Button mNextButton; private static Handler mHandler = new Handler(); private static final int CONFIRM_EXISTING_REQUEST = 58; static final int RESULT_FINISHED = RESULT_FIRST_USER; private static final long ERROR_MESSAGE_TIMEOUT = 3000; /** * Keep track internally of where the user is in choosing a pattern. */ protected enum Stage { Introduction(R.string.lockpassword_choose_your_password_header, R.string.lockpassword_choose_your_pin_header, R.string.lockpassword_continue_label), NeedToConfirm(R.string.lockpassword_confirm_your_password_header, R.string.lockpassword_confirm_your_pin_header, R.string.lockpassword_ok_label), ConfirmWrong(R.string.lockpassword_confirm_passwords_dont_match, R.string.lockpassword_confirm_pins_dont_match, R.string.lockpassword_continue_label); /** * @param headerMessage The message displayed at the top. */ Stage(int hintInAlpha, int hintInNumeric, int nextButtonText) { this.alphaHint = hintInAlpha; this.numericHint = hintInNumeric; this.buttonText = nextButtonText; } public final int alphaHint; public final int numericHint; public final int buttonText; } // required constructor for fragments public ChooseLockPasswordFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLockPatternUtils = new LockPatternUtils(getActivity()); Intent intent = getActivity().getIntent(); mRequestedQuality = Math.max(intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, mRequestedQuality), mLockPatternUtils.getRequestedPasswordQuality()); mPasswordMinLength = Math.max( intent.getIntExtra(PASSWORD_MIN_KEY, mPasswordMinLength), mLockPatternUtils .getRequestedMinimumPasswordLength()); mPasswordMaxLength = intent.getIntExtra(PASSWORD_MAX_KEY, mPasswordMaxLength); mPasswordMinLetters = Math.max(intent.getIntExtra(PASSWORD_MIN_LETTERS_KEY, mPasswordMinLetters), mLockPatternUtils.getRequestedPasswordMinimumLetters()); mPasswordMinUpperCase = Math.max(intent.getIntExtra(PASSWORD_MIN_UPPERCASE_KEY, mPasswordMinUpperCase), mLockPatternUtils.getRequestedPasswordMinimumUpperCase()); mPasswordMinLowerCase = Math.max(intent.getIntExtra(PASSWORD_MIN_LOWERCASE_KEY, mPasswordMinLowerCase), mLockPatternUtils.getRequestedPasswordMinimumLowerCase()); mPasswordMinNumeric = Math.max(intent.getIntExtra(PASSWORD_MIN_NUMERIC_KEY, mPasswordMinNumeric), mLockPatternUtils.getRequestedPasswordMinimumNumeric()); mPasswordMinSymbols = Math.max(intent.getIntExtra(PASSWORD_MIN_SYMBOLS_KEY, mPasswordMinSymbols), mLockPatternUtils.getRequestedPasswordMinimumSymbols()); mPasswordMinNonLetter = Math.max(intent.getIntExtra(PASSWORD_MIN_NONLETTER_KEY, mPasswordMinNonLetter), mLockPatternUtils.getRequestedPasswordMinimumNonLetter()); mChooseLockSettingsHelper = new ChooseLockSettingsHelper(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_lock_password, null); mCancelButton = (Button) view.findViewById(R.id.cancel_button); mCancelButton.setOnClickListener(this); mNextButton = (Button) view.findViewById(R.id.next_button); mNextButton.setOnClickListener(this); mIsAlphaMode = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality || DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality || DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality; mKeyboardView = (PasswordEntryKeyboardView) view.findViewById(R.id.keyboard); mPasswordEntry = (TextView) view.findViewById(R.id.password_entry); mPasswordEntry.setOnEditorActionListener(this); mPasswordEntry.addTextChangedListener(this); final Activity activity = getActivity(); mKeyboardHelper = new PasswordEntryKeyboardHelper(activity, mKeyboardView, mPasswordEntry); mKeyboardHelper.setKeyboardMode(mIsAlphaMode ? PasswordEntryKeyboardHelper.KEYBOARD_MODE_ALPHA : PasswordEntryKeyboardHelper.KEYBOARD_MODE_NUMERIC); mHeaderText = (TextView) view.findViewById(R.id.headerText); mKeyboardView.requestFocus(); int currentType = mPasswordEntry.getInputType(); mPasswordEntry.setInputType(mIsAlphaMode ? currentType : (InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD)); Intent intent = getActivity().getIntent(); final boolean confirmCredentials = intent.getBooleanExtra("confirm_credentials", true); if (savedInstanceState == null) { updateStage(Stage.Introduction); if (confirmCredentials) { mChooseLockSettingsHelper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST, null, null); } } else { mFirstPin = savedInstanceState.getString(KEY_FIRST_PIN); final String state = savedInstanceState.getString(KEY_UI_STAGE); if (state != null) { mUiStage = Stage.valueOf(state); updateStage(mUiStage); } } // Update the breadcrumb (title) if this is embedded in a PreferenceActivity if (activity instanceof PreferenceActivity) { final PreferenceActivity preferenceActivity = (PreferenceActivity) activity; int id = mIsAlphaMode ? R.string.lockpassword_choose_your_password_header : R.string.lockpassword_choose_your_pin_header; CharSequence title = getText(id); preferenceActivity.showBreadCrumbs(title, title); } return view; } @Override public void onResume() { super.onResume(); updateStage(mUiStage); mKeyboardView.requestFocus(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_UI_STAGE, mUiStage.name()); outState.putString(KEY_FIRST_PIN, mFirstPin); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case CONFIRM_EXISTING_REQUEST: if (resultCode != Activity.RESULT_OK) { getActivity().setResult(RESULT_FINISHED); getActivity().finish(); } break; } } protected void updateStage(Stage stage) { mUiStage = stage; updateUi(); } /** * Validates PIN and returns a message to display if PIN fails test. * @param password the raw password the user typed in * @return error message to show to user or null if password is OK */ private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long - : R.string.lockpassword_pin_too_long, mPasswordMaxLength); + : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); // allow non white space Latin-1 characters only if (c <= 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; } private void handleNext() { final String pin = mPasswordEntry.getText().toString(); if (TextUtils.isEmpty(pin)) { return; } String errorMsg = null; if (mUiStage == Stage.Introduction) { errorMsg = validatePassword(pin); if (errorMsg == null) { mFirstPin = pin; updateStage(Stage.NeedToConfirm); mPasswordEntry.setText(""); } } else if (mUiStage == Stage.NeedToConfirm) { if (mFirstPin.equals(pin)) { mLockPatternUtils.clearLock(); mLockPatternUtils.saveLockPassword(pin, mRequestedQuality); getActivity().finish(); } else { updateStage(Stage.ConfirmWrong); CharSequence tmp = mPasswordEntry.getText(); if (tmp != null) { Selection.setSelection((Spannable) tmp, 0, tmp.length()); } } } if (errorMsg != null) { showError(errorMsg, mUiStage); } } public void onClick(View v) { switch (v.getId()) { case R.id.next_button: handleNext(); break; case R.id.cancel_button: getActivity().finish(); break; } } private void showError(String msg, final Stage next) { mHeaderText.setText(msg); mHandler.postDelayed(new Runnable() { public void run() { updateStage(next); } }, ERROR_MESSAGE_TIMEOUT); } public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // Check if this was the result of hitting the enter key if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { handleNext(); return true; } return false; } /** * Update the hint based on current Stage and length of password entry */ private void updateUi() { String password = mPasswordEntry.getText().toString(); final int length = password.length(); if (mUiStage == Stage.Introduction && length > 0) { if (length < mPasswordMinLength) { String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); mHeaderText.setText(msg); mNextButton.setEnabled(false); } else { String error = validatePassword(password); if (error != null) { mHeaderText.setText(error); mNextButton.setEnabled(false); } else { mHeaderText.setText(R.string.lockpassword_press_continue); mNextButton.setEnabled(true); } } } else { mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint); mNextButton.setEnabled(length > 0); } mNextButton.setText(mUiStage.buttonText); } public void afterTextChanged(Editable s) { // Changing the text while error displayed resets to NeedToConfirm state if (mUiStage == Stage.ConfirmWrong) { mUiStage = Stage.NeedToConfirm; } updateUi(); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { } } }
true
true
private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long : R.string.lockpassword_pin_too_long, mPasswordMaxLength); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); // allow non white space Latin-1 characters only if (c <= 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; }
private String validatePassword(String password) { if (password.length() < mPasswordMinLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_short : R.string.lockpassword_pin_too_short, mPasswordMinLength); } if (password.length() > mPasswordMaxLength) { return getString(mIsAlphaMode ? R.string.lockpassword_password_too_long : R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1); } int letters = 0; int numbers = 0; int lowercase = 0; int symbols = 0; int uppercase = 0; int nonletter = 0; for (int i = 0; i < password.length(); i++) { char c = password.charAt(i); // allow non white space Latin-1 characters only if (c <= 32 || c > 127) { return getString(R.string.lockpassword_illegal_character); } if (c >= '0' && c <= '9') { numbers++; nonletter++; } else if (c >= 'A' && c <= 'Z') { letters++; uppercase++; } else if (c >= 'a' && c <= 'z') { letters++; lowercase++; } else { symbols++; nonletter++; } } if (DevicePolicyManager.PASSWORD_QUALITY_NUMERIC == mRequestedQuality && (letters > 0 || symbols > 0)) { // This shouldn't be possible unless user finds some way to bring up // soft keyboard return getString(R.string.lockpassword_pin_contains_non_digits); } else if (DevicePolicyManager.PASSWORD_QUALITY_COMPLEX == mRequestedQuality) { if (letters < mPasswordMinLetters) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_letters, mPasswordMinLetters), mPasswordMinLetters); } else if (numbers < mPasswordMinNumeric) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_numeric, mPasswordMinNumeric), mPasswordMinNumeric); } else if (lowercase < mPasswordMinLowerCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_lowercase, mPasswordMinLowerCase), mPasswordMinLowerCase); } else if (uppercase < mPasswordMinUpperCase) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_uppercase, mPasswordMinUpperCase), mPasswordMinUpperCase); } else if (symbols < mPasswordMinSymbols) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_symbols, mPasswordMinSymbols), mPasswordMinSymbols); } else if (nonletter < mPasswordMinNonLetter) { return String.format(getResources().getQuantityString( R.plurals.lockpassword_password_requires_nonletter, mPasswordMinNonLetter), mPasswordMinNonLetter); } } else { final boolean alphabetic = DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC == mRequestedQuality; final boolean alphanumeric = DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC == mRequestedQuality; if ((alphabetic || alphanumeric) && letters == 0) { return getString(R.string.lockpassword_password_requires_alpha); } if (alphanumeric && numbers == 0) { return getString(R.string.lockpassword_password_requires_digit); } } if(mLockPatternUtils.checkPasswordHistory(password)) { return getString(mIsAlphaMode ? R.string.lockpassword_password_recently_used : R.string.lockpassword_pin_recently_used); } return null; }
diff --git a/org.nodeclipse.debug/src/org/nodeclipse/debug/launch/LaunchConfigurationDelegate.java b/org.nodeclipse.debug/src/org/nodeclipse/debug/launch/LaunchConfigurationDelegate.java index cd3ed6a4..5084db39 100644 --- a/org.nodeclipse.debug/src/org/nodeclipse/debug/launch/LaunchConfigurationDelegate.java +++ b/org.nodeclipse.debug/src/org/nodeclipse/debug/launch/LaunchConfigurationDelegate.java @@ -1,272 +1,277 @@ package org.nodeclipse.debug.launch; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.chromium.debug.core.ChromiumDebugPlugin; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.model.ILaunchConfigurationDelegate; import org.eclipse.debug.core.model.RuntimeProcess; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; import org.nodeclipse.debug.util.Constants; import org.nodeclipse.debug.util.NodeDebugUtil; import org.nodeclipse.debug.util.VariablesUtil; import org.nodeclipse.ui.Activator; import org.nodeclipse.ui.preferences.Dialogs; import org.nodeclipse.ui.preferences.PreferenceConstants; import org.nodeclipse.ui.util.NodeclipseConsole; /** * launch() implements starting Node and passing all parameters. * Node is launched as node, coffee, coffee -c, tsc or node-dev(or other monitors) * * @author Lamb, Tomoyuki, Pushkar, Paul Verest */ public class LaunchConfigurationDelegate implements ILaunchConfigurationDelegate { private static RuntimeProcess nodeProcess = null; //since 0.7 it should be debuggable instance //@since 0.7. contain all running Node thread, including under debug. Non Thread-safe, as it should be only in GUI thread //private static List<RuntimeProcess> nodeRunningProcesses = new LinkedList<RuntimeProcess>(); /* * (non-Javadoc) * * @see * org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org. * eclipse.debug.core.ILaunchConfiguration, java.lang.String, * org.eclipse.debug.core.ILaunch, * org.eclipse.core.runtime.IProgressMonitor) */ @Override public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); boolean allowedMany = preferenceStore.getBoolean(PreferenceConstants.NODE_ALLOW_MANY);//@since 0.7 boolean isDebugMode = mode.equals(ILaunchManager.DEBUG_MODE); if (allowedMany){//@since 0.7 if ( isDebugMode && (nodeProcess != null && !nodeProcess.isTerminated()) ) { showErrorDialog("Only 1 node process can be debugged in 1 Eclipse instance!\n\n"+ "Open other Eclipse/Enide Studio with different node debug port configurred. "); return; } }else{ if(nodeProcess != null && !nodeProcess.isTerminated()) { //throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, null, null)); showErrorDialog("Other node process is running!"); return; //TODO suggest to terminate and start new } } // Using configuration to build command line List<String> cmdLine = new ArrayList<String>(); if (preferenceStore.getBoolean(PreferenceConstants.NODE_JUST_NODE)){ cmdLine.add("node"); }else{ // old way: Application path should be stored in preference. String nodePath= preferenceStore.getString(PreferenceConstants.NODE_PATH); // Check if the node location is correctly configured File nodeFile = new File(nodePath); if(!nodeFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js runtime is not correctly configured.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodePath); } if (isDebugMode) { // -brk says to Node runtime wait until Chromium Debugger starts and connects // that is causing "stop on first line" behavior, // otherwise small apps or first line can be undebuggable. String brk = "-brk" ; //default "-brk" if (preferenceStore.getBoolean(PreferenceConstants.NODE_DEBUG_NO_BREAK)) //default false brk = ""; // done: flexible debugging port, instead of hard-coded 5858 // #61 https://github.com/Nodeclipse/nodeclipse-1/issues/61 int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); if (nodeDebugPort==0) { nodeDebugPort=5858;}; cmdLine.add("--debug"+brk+"="+nodeDebugPort); //--debug-brk=5858 } //@since 0.9 from Preferences String nodeOptions= preferenceStore.getString(PreferenceConstants.NODE_OPTIONS); if(!nodeOptions.equals("")) { String[] sa = nodeOptions.split(" "); for(String s : sa) { cmdLine.add(s); } } String nodeArgs = configuration.getAttribute(Constants.ATTR_NODE_ARGUMENTS, ""); if(!nodeArgs.equals("")) { String[] sa = nodeArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String file = configuration.getAttribute(Constants.KEY_FILE_PATH, Constants.BLANK_STRING); String extension = null; int i = file.lastIndexOf('.'); if(i > 0) { extension = file.substring(i+1); } else { throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, "Target file does not have extension: " + file, null)); } // #57 running app.js with node-dev, forever, supervisor, nodemon etc // https://github.com/Nodeclipse/nodeclipse-1/issues/57 String nodeMonitor = configuration.getAttribute(Constants.ATTR_NODE_MONITOR, ""); if(!nodeMonitor.equals("")) { // any value //TODO support selection, now only one String nodeMonitorPath= preferenceStore.getString(PreferenceConstants.NODE_MONITOR_PATH); // Check if the node monitor location is correctly configured File nodeMonitorFile = new File(nodeMonitorPath); if(!nodeMonitorFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js monitor is not correctly configured.\n" + "Select path to installed util: forever, node-dev, nodemon or superviser.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodeMonitorPath); } else if ( ("coffee".equals(extension))||("litcoffee".equals(extension))||("md".equals(extension)) ) { //if (preferenceStore.getBoolean(PreferenceConstants.COFFEE_JUST_COFFEE)){ // cmdLine.add("coffee"); //TODO should be instead of node above //}else{ cmdLine.add(preferenceStore.getString(PreferenceConstants.COFFEE_PATH)); //} // coffee -c String coffeeCompile = configuration.getAttribute(Constants.ATTR_COFFEE_COMPILE, ""); if(!coffeeCompile.equals("")) { // any value cmdLine.add("-c"); String coffeeCompileOptions = preferenceStore.getString(PreferenceConstants.COFFEE_COMPILE_OPTIONS); if(!coffeeCompileOptions.equals("")) { cmdLine.add(coffeeCompileOptions); } } } else if ("ts".equals(extension)) { // the only thing we can do now with .ts is to compile, so no need to check if it was launched as tsc //String typescriptCompiler = configuration.getAttribute(Constants.ATTR_TYPESCRIPT_COMPILER, ""); cmdLine.add(preferenceStore.getString(PreferenceConstants.TYPESCRIPT_COMPILER_PATH)); } String filePath = ResourcesPlugin.getWorkspace().getRoot().findMember(file).getLocation().toOSString(); // path is relative, so can not found it. cmdLine.add(filePath); //@since 0.9 from Preferences String nodeApplicationArguments = preferenceStore.getString(PreferenceConstants.NODE_APPLICATION_ARGUMENTS); if(!nodeApplicationArguments.equals("")) { String[] sa = nodeApplicationArguments.split(" "); for(String s : sa) { cmdLine.add(s); } } String programArgs = configuration.getAttribute(Constants.ATTR_PROGRAM_ARGUMENTS, ""); if(!programArgs.equals("")) { String[] sa = programArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String workingDirectory = configuration.getAttribute(Constants.ATTR_WORKING_DIRECTORY, ""); File workingPath = null; if(workingDirectory.length() == 0) { workingPath = (new File(filePath)).getParentFile(); } else { workingDirectory = VariablesUtil.resolveValue(workingDirectory); if(workingDirectory == null) { workingPath = (new File(filePath)).getParentFile(); } else { workingPath = new File(workingDirectory); } } Map<String, String> envm = new HashMap<String, String>(); envm = configuration.getAttribute(Constants.ATTR_ENVIRONMENT_VARIABLES, envm); - String[] envp = new String[envm.size()]; + String[] envp = new String[envm.size()+4]; // see below int idx = 0; for(String key : envm.keySet()) { String value = envm.get(key); envp[idx++] = key + "=" + value; } + //+ #81 + envp[idx++] = "PATH=" + System.getenv("PATH"); + envp[idx++] = "TEMP=" + System.getenv("TEMP"); + envp[idx++] = "TMP=" + System.getenv("TMP"); + envp[idx++] = "SystemDrive=" + System.getenv("SystemDrive"); for(String s : cmdLine) NodeclipseConsole.write(s+" "); NodeclipseConsole.write("\n"); String[] cmds = {}; cmds = cmdLine.toArray(cmds); // Launch a process to run/debug. See also #71 (output is less or no output) Process p = DebugPlugin.exec(cmds, workingPath, envp); // no way to get private p.handle from java.lang.ProcessImpl RuntimeProcess process = (RuntimeProcess)DebugPlugin.newProcess(launch, p, Constants.PROCESS_MESSAGE); if (isDebugMode) { if(!process.isTerminated()) { int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); NodeDebugUtil.launch(mode, launch, monitor, nodeDebugPort); } } if (allowedMany){ //@since 0.7 if (isDebugMode){ nodeProcess = process; } //nodeRunningProcesses.add(process); }else{ nodeProcess = process; } } private void showErrorDialog(final String message) { Display.getDefault().syncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); MessageDialog dialog = new MessageDialog(shell, "Nodeclipse", null, message, MessageDialog.ERROR, new String[] { "OK" }, 0); dialog.open(); } }); } public static void terminateNodeProcess() { if(nodeProcess != null) { try { nodeProcess.terminate(); } catch (DebugException e) { //e.printStackTrace(); NodeclipseConsole.write(e.getLocalizedMessage()+"\n"); } nodeProcess = null; } } }
false
true
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); boolean allowedMany = preferenceStore.getBoolean(PreferenceConstants.NODE_ALLOW_MANY);//@since 0.7 boolean isDebugMode = mode.equals(ILaunchManager.DEBUG_MODE); if (allowedMany){//@since 0.7 if ( isDebugMode && (nodeProcess != null && !nodeProcess.isTerminated()) ) { showErrorDialog("Only 1 node process can be debugged in 1 Eclipse instance!\n\n"+ "Open other Eclipse/Enide Studio with different node debug port configurred. "); return; } }else{ if(nodeProcess != null && !nodeProcess.isTerminated()) { //throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, null, null)); showErrorDialog("Other node process is running!"); return; //TODO suggest to terminate and start new } } // Using configuration to build command line List<String> cmdLine = new ArrayList<String>(); if (preferenceStore.getBoolean(PreferenceConstants.NODE_JUST_NODE)){ cmdLine.add("node"); }else{ // old way: Application path should be stored in preference. String nodePath= preferenceStore.getString(PreferenceConstants.NODE_PATH); // Check if the node location is correctly configured File nodeFile = new File(nodePath); if(!nodeFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js runtime is not correctly configured.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodePath); } if (isDebugMode) { // -brk says to Node runtime wait until Chromium Debugger starts and connects // that is causing "stop on first line" behavior, // otherwise small apps or first line can be undebuggable. String brk = "-brk" ; //default "-brk" if (preferenceStore.getBoolean(PreferenceConstants.NODE_DEBUG_NO_BREAK)) //default false brk = ""; // done: flexible debugging port, instead of hard-coded 5858 // #61 https://github.com/Nodeclipse/nodeclipse-1/issues/61 int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); if (nodeDebugPort==0) { nodeDebugPort=5858;}; cmdLine.add("--debug"+brk+"="+nodeDebugPort); //--debug-brk=5858 } //@since 0.9 from Preferences String nodeOptions= preferenceStore.getString(PreferenceConstants.NODE_OPTIONS); if(!nodeOptions.equals("")) { String[] sa = nodeOptions.split(" "); for(String s : sa) { cmdLine.add(s); } } String nodeArgs = configuration.getAttribute(Constants.ATTR_NODE_ARGUMENTS, ""); if(!nodeArgs.equals("")) { String[] sa = nodeArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String file = configuration.getAttribute(Constants.KEY_FILE_PATH, Constants.BLANK_STRING); String extension = null; int i = file.lastIndexOf('.'); if(i > 0) { extension = file.substring(i+1); } else { throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, "Target file does not have extension: " + file, null)); } // #57 running app.js with node-dev, forever, supervisor, nodemon etc // https://github.com/Nodeclipse/nodeclipse-1/issues/57 String nodeMonitor = configuration.getAttribute(Constants.ATTR_NODE_MONITOR, ""); if(!nodeMonitor.equals("")) { // any value //TODO support selection, now only one String nodeMonitorPath= preferenceStore.getString(PreferenceConstants.NODE_MONITOR_PATH); // Check if the node monitor location is correctly configured File nodeMonitorFile = new File(nodeMonitorPath); if(!nodeMonitorFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js monitor is not correctly configured.\n" + "Select path to installed util: forever, node-dev, nodemon or superviser.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodeMonitorPath); } else if ( ("coffee".equals(extension))||("litcoffee".equals(extension))||("md".equals(extension)) ) { //if (preferenceStore.getBoolean(PreferenceConstants.COFFEE_JUST_COFFEE)){ // cmdLine.add("coffee"); //TODO should be instead of node above //}else{ cmdLine.add(preferenceStore.getString(PreferenceConstants.COFFEE_PATH)); //} // coffee -c String coffeeCompile = configuration.getAttribute(Constants.ATTR_COFFEE_COMPILE, ""); if(!coffeeCompile.equals("")) { // any value cmdLine.add("-c"); String coffeeCompileOptions = preferenceStore.getString(PreferenceConstants.COFFEE_COMPILE_OPTIONS); if(!coffeeCompileOptions.equals("")) { cmdLine.add(coffeeCompileOptions); } } } else if ("ts".equals(extension)) { // the only thing we can do now with .ts is to compile, so no need to check if it was launched as tsc //String typescriptCompiler = configuration.getAttribute(Constants.ATTR_TYPESCRIPT_COMPILER, ""); cmdLine.add(preferenceStore.getString(PreferenceConstants.TYPESCRIPT_COMPILER_PATH)); } String filePath = ResourcesPlugin.getWorkspace().getRoot().findMember(file).getLocation().toOSString(); // path is relative, so can not found it. cmdLine.add(filePath); //@since 0.9 from Preferences String nodeApplicationArguments = preferenceStore.getString(PreferenceConstants.NODE_APPLICATION_ARGUMENTS); if(!nodeApplicationArguments.equals("")) { String[] sa = nodeApplicationArguments.split(" "); for(String s : sa) { cmdLine.add(s); } } String programArgs = configuration.getAttribute(Constants.ATTR_PROGRAM_ARGUMENTS, ""); if(!programArgs.equals("")) { String[] sa = programArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String workingDirectory = configuration.getAttribute(Constants.ATTR_WORKING_DIRECTORY, ""); File workingPath = null; if(workingDirectory.length() == 0) { workingPath = (new File(filePath)).getParentFile(); } else { workingDirectory = VariablesUtil.resolveValue(workingDirectory); if(workingDirectory == null) { workingPath = (new File(filePath)).getParentFile(); } else { workingPath = new File(workingDirectory); } } Map<String, String> envm = new HashMap<String, String>(); envm = configuration.getAttribute(Constants.ATTR_ENVIRONMENT_VARIABLES, envm); String[] envp = new String[envm.size()]; int idx = 0; for(String key : envm.keySet()) { String value = envm.get(key); envp[idx++] = key + "=" + value; } for(String s : cmdLine) NodeclipseConsole.write(s+" "); NodeclipseConsole.write("\n"); String[] cmds = {}; cmds = cmdLine.toArray(cmds); // Launch a process to run/debug. See also #71 (output is less or no output) Process p = DebugPlugin.exec(cmds, workingPath, envp); // no way to get private p.handle from java.lang.ProcessImpl RuntimeProcess process = (RuntimeProcess)DebugPlugin.newProcess(launch, p, Constants.PROCESS_MESSAGE); if (isDebugMode) { if(!process.isTerminated()) { int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); NodeDebugUtil.launch(mode, launch, monitor, nodeDebugPort); } } if (allowedMany){ //@since 0.7 if (isDebugMode){ nodeProcess = process; } //nodeRunningProcesses.add(process); }else{ nodeProcess = process; } }
public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch, IProgressMonitor monitor) throws CoreException { IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore(); boolean allowedMany = preferenceStore.getBoolean(PreferenceConstants.NODE_ALLOW_MANY);//@since 0.7 boolean isDebugMode = mode.equals(ILaunchManager.DEBUG_MODE); if (allowedMany){//@since 0.7 if ( isDebugMode && (nodeProcess != null && !nodeProcess.isTerminated()) ) { showErrorDialog("Only 1 node process can be debugged in 1 Eclipse instance!\n\n"+ "Open other Eclipse/Enide Studio with different node debug port configurred. "); return; } }else{ if(nodeProcess != null && !nodeProcess.isTerminated()) { //throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, null, null)); showErrorDialog("Other node process is running!"); return; //TODO suggest to terminate and start new } } // Using configuration to build command line List<String> cmdLine = new ArrayList<String>(); if (preferenceStore.getBoolean(PreferenceConstants.NODE_JUST_NODE)){ cmdLine.add("node"); }else{ // old way: Application path should be stored in preference. String nodePath= preferenceStore.getString(PreferenceConstants.NODE_PATH); // Check if the node location is correctly configured File nodeFile = new File(nodePath); if(!nodeFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js runtime is not correctly configured.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodePath); } if (isDebugMode) { // -brk says to Node runtime wait until Chromium Debugger starts and connects // that is causing "stop on first line" behavior, // otherwise small apps or first line can be undebuggable. String brk = "-brk" ; //default "-brk" if (preferenceStore.getBoolean(PreferenceConstants.NODE_DEBUG_NO_BREAK)) //default false brk = ""; // done: flexible debugging port, instead of hard-coded 5858 // #61 https://github.com/Nodeclipse/nodeclipse-1/issues/61 int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); if (nodeDebugPort==0) { nodeDebugPort=5858;}; cmdLine.add("--debug"+brk+"="+nodeDebugPort); //--debug-brk=5858 } //@since 0.9 from Preferences String nodeOptions= preferenceStore.getString(PreferenceConstants.NODE_OPTIONS); if(!nodeOptions.equals("")) { String[] sa = nodeOptions.split(" "); for(String s : sa) { cmdLine.add(s); } } String nodeArgs = configuration.getAttribute(Constants.ATTR_NODE_ARGUMENTS, ""); if(!nodeArgs.equals("")) { String[] sa = nodeArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String file = configuration.getAttribute(Constants.KEY_FILE_PATH, Constants.BLANK_STRING); String extension = null; int i = file.lastIndexOf('.'); if(i > 0) { extension = file.substring(i+1); } else { throw new CoreException(new Status(IStatus.OK, ChromiumDebugPlugin.PLUGIN_ID, "Target file does not have extension: " + file, null)); } // #57 running app.js with node-dev, forever, supervisor, nodemon etc // https://github.com/Nodeclipse/nodeclipse-1/issues/57 String nodeMonitor = configuration.getAttribute(Constants.ATTR_NODE_MONITOR, ""); if(!nodeMonitor.equals("")) { // any value //TODO support selection, now only one String nodeMonitorPath= preferenceStore.getString(PreferenceConstants.NODE_MONITOR_PATH); // Check if the node monitor location is correctly configured File nodeMonitorFile = new File(nodeMonitorPath); if(!nodeMonitorFile.exists()){ // If the location is not valid than show a dialog which prompts the user to goto the preferences page Dialogs.showPreferencesDialog("Node.js monitor is not correctly configured.\n" + "Select path to installed util: forever, node-dev, nodemon or superviser.\n\n" + "Please goto Window -> Prefrences -> Nodeclipse and configure the correct location"); return; } cmdLine.add(nodeMonitorPath); } else if ( ("coffee".equals(extension))||("litcoffee".equals(extension))||("md".equals(extension)) ) { //if (preferenceStore.getBoolean(PreferenceConstants.COFFEE_JUST_COFFEE)){ // cmdLine.add("coffee"); //TODO should be instead of node above //}else{ cmdLine.add(preferenceStore.getString(PreferenceConstants.COFFEE_PATH)); //} // coffee -c String coffeeCompile = configuration.getAttribute(Constants.ATTR_COFFEE_COMPILE, ""); if(!coffeeCompile.equals("")) { // any value cmdLine.add("-c"); String coffeeCompileOptions = preferenceStore.getString(PreferenceConstants.COFFEE_COMPILE_OPTIONS); if(!coffeeCompileOptions.equals("")) { cmdLine.add(coffeeCompileOptions); } } } else if ("ts".equals(extension)) { // the only thing we can do now with .ts is to compile, so no need to check if it was launched as tsc //String typescriptCompiler = configuration.getAttribute(Constants.ATTR_TYPESCRIPT_COMPILER, ""); cmdLine.add(preferenceStore.getString(PreferenceConstants.TYPESCRIPT_COMPILER_PATH)); } String filePath = ResourcesPlugin.getWorkspace().getRoot().findMember(file).getLocation().toOSString(); // path is relative, so can not found it. cmdLine.add(filePath); //@since 0.9 from Preferences String nodeApplicationArguments = preferenceStore.getString(PreferenceConstants.NODE_APPLICATION_ARGUMENTS); if(!nodeApplicationArguments.equals("")) { String[] sa = nodeApplicationArguments.split(" "); for(String s : sa) { cmdLine.add(s); } } String programArgs = configuration.getAttribute(Constants.ATTR_PROGRAM_ARGUMENTS, ""); if(!programArgs.equals("")) { String[] sa = programArgs.split(" "); for(String s : sa) { cmdLine.add(s); } } String workingDirectory = configuration.getAttribute(Constants.ATTR_WORKING_DIRECTORY, ""); File workingPath = null; if(workingDirectory.length() == 0) { workingPath = (new File(filePath)).getParentFile(); } else { workingDirectory = VariablesUtil.resolveValue(workingDirectory); if(workingDirectory == null) { workingPath = (new File(filePath)).getParentFile(); } else { workingPath = new File(workingDirectory); } } Map<String, String> envm = new HashMap<String, String>(); envm = configuration.getAttribute(Constants.ATTR_ENVIRONMENT_VARIABLES, envm); String[] envp = new String[envm.size()+4]; // see below int idx = 0; for(String key : envm.keySet()) { String value = envm.get(key); envp[idx++] = key + "=" + value; } //+ #81 envp[idx++] = "PATH=" + System.getenv("PATH"); envp[idx++] = "TEMP=" + System.getenv("TEMP"); envp[idx++] = "TMP=" + System.getenv("TMP"); envp[idx++] = "SystemDrive=" + System.getenv("SystemDrive"); for(String s : cmdLine) NodeclipseConsole.write(s+" "); NodeclipseConsole.write("\n"); String[] cmds = {}; cmds = cmdLine.toArray(cmds); // Launch a process to run/debug. See also #71 (output is less or no output) Process p = DebugPlugin.exec(cmds, workingPath, envp); // no way to get private p.handle from java.lang.ProcessImpl RuntimeProcess process = (RuntimeProcess)DebugPlugin.newProcess(launch, p, Constants.PROCESS_MESSAGE); if (isDebugMode) { if(!process.isTerminated()) { int nodeDebugPort = preferenceStore.getInt(PreferenceConstants.NODE_DEBUG_PORT); NodeDebugUtil.launch(mode, launch, monitor, nodeDebugPort); } } if (allowedMany){ //@since 0.7 if (isDebugMode){ nodeProcess = process; } //nodeRunningProcesses.add(process); }else{ nodeProcess = process; } }
diff --git a/src/main/java/com/tp/action/ImageAction.java b/src/main/java/com/tp/action/ImageAction.java index e539c70..ad4dad9 100644 --- a/src/main/java/com/tp/action/ImageAction.java +++ b/src/main/java/com/tp/action/ImageAction.java @@ -1,161 +1,162 @@ package com.tp.action; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URLDecoder; import java.util.zip.GZIPOutputStream; import javax.activation.MimetypesFileTypeMap; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.opensymphony.xwork2.ActionSupport; import com.tp.utils.Constants; import com.tp.utils.ServletUtils; import com.tp.utils.Struts2Utils; public class ImageAction extends ActionSupport { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(ImageAction.class); private static final String[] GZIP_MIME_TYPES = { "text/html", "text/xml", "text/plain", "text/css", "text/javascript", "application/xml", "application/xhtml+xml", "application/x-javascript" }; private static final int GZIP_MINI_LENGTH = 512; private MimetypesFileTypeMap mimetypesFileTypeMap; public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365; @Override public String execute() throws Exception { return getImage(); } public String getImage() throws Exception { String contentPath = Struts2Utils.getParameter("path"); responseImage(contentPath); return null; } private void responseImage(String contentPath) throws Exception { HttpServletResponse response = Struts2Utils.getResponse(); HttpServletRequest request = Struts2Utils.getRequest(); + String queryString=(String)request.getSession().getAttribute(Constants.QUERY_STRING); if (StringUtils.isBlank(contentPath)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "path parametter is required."); return; } contentPath = URLDecoder.decode(contentPath, "UTF-8"); String realPath = Constants.LOCKER_STORAGE + new String(contentPath.getBytes("iso-8859-1"), "utf-8"); ContentInfo contentInfo = getContentInfo(realPath); //根据Etag或ModifiedSince Header判断客户端的缓存文件是否有效, 如仍有效则设置返回码为304,直接返回. if (!ServletUtils.checkIfModifiedSince(request, response, contentInfo.lastModified) || !ServletUtils.checkIfNoneMatchEtag(request, response, contentInfo.etag)) { return; } ServletUtils.setExpiresHeader(response, ONE_YEAR_SECONDS); ServletUtils.setLastModifiedHeader(response, System.currentTimeMillis()); ServletUtils.setEtag(response, contentInfo.etag); response.setContentType(contentInfo.mimeType); //设置弹出下载文件请求窗口的Header if (request.getParameter("download") != null) { ServletUtils.setFileDownloadHeader(response, contentInfo.fileName); } //构造OutputStream OutputStream output; if (checkAccetptGzip(request) && contentInfo.needGzip) { //使用压缩传输的outputstream, 使用http1.1 trunked编码不设置content-length. output = buildGzipOutputStream(response); } else { //使用普通outputstream, 设置content-length. response.setContentLength(contentInfo.length); output = response.getOutputStream(); } //高效读取文件内容并输出,然后关闭input file try { FileUtils.copyFile(contentInfo.file, output); output.flush(); } catch (Exception e) { String ip = ServletUtils.getIpAddr(request); String userAgent = request.getHeader("User-Agent"); String eMsg = e.getMessage(); if (StringUtils.isBlank(eMsg)) { eMsg = contentInfo.contentPath; } - logger.warn(eMsg + ",ip:" + ip + ",User-Agent:" + userAgent+",param: "+request.getSession().getAttribute(Constants.QUERY_STRING)); + logger.warn(eMsg + ",ip:" + ip + ",User-Agent:" + userAgent+",param: "+queryString); } } /** * 检查浏览器客户端是否支持gzip编码. */ private static boolean checkAccetptGzip(HttpServletRequest request) { //Http1.1 header String acceptEncoding = request.getHeader("Accept-Encoding"); return StringUtils.contains(acceptEncoding, "gzip"); } /** * 设置Gzip Header并返回GZIPOutputStream. */ private OutputStream buildGzipOutputStream(HttpServletResponse response) throws IOException { response.setHeader("Content-Encoding", "gzip"); response.setHeader("Vary", "Accept-Encoding"); return new GZIPOutputStream(response.getOutputStream()); } @PostConstruct public void init() { mimetypesFileTypeMap = new MimetypesFileTypeMap(); mimetypesFileTypeMap.addMimeTypes("text/css css"); } private ContentInfo getContentInfo(String contentPath) { ContentInfo contentInfo = new ContentInfo(); File file = new File(contentPath); contentInfo.file = file; contentInfo.contentPath = contentPath; contentInfo.fileName = file.getName(); contentInfo.length = (int) file.length(); contentInfo.lastModified = file.lastModified(); contentInfo.etag = "W/\"" + contentInfo.lastModified + "\""; contentInfo.mimeType = mimetypesFileTypeMap.getContentType(contentInfo.fileName); if (contentInfo.length >= GZIP_MINI_LENGTH && ArrayUtils.contains(GZIP_MIME_TYPES, contentInfo.mimeType)) { contentInfo.needGzip = true; } else { contentInfo.needGzip = false; } return contentInfo; } static class ContentInfo { protected String contentPath; protected File file; protected String fileName; protected int length; protected String mimeType; protected long lastModified; protected String etag; protected boolean needGzip; } }
false
true
private void responseImage(String contentPath) throws Exception { HttpServletResponse response = Struts2Utils.getResponse(); HttpServletRequest request = Struts2Utils.getRequest(); if (StringUtils.isBlank(contentPath)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "path parametter is required."); return; } contentPath = URLDecoder.decode(contentPath, "UTF-8"); String realPath = Constants.LOCKER_STORAGE + new String(contentPath.getBytes("iso-8859-1"), "utf-8"); ContentInfo contentInfo = getContentInfo(realPath); //根据Etag或ModifiedSince Header判断客户端的缓存文件是否有效, 如仍有效则设置返回码为304,直接返回. if (!ServletUtils.checkIfModifiedSince(request, response, contentInfo.lastModified) || !ServletUtils.checkIfNoneMatchEtag(request, response, contentInfo.etag)) { return; } ServletUtils.setExpiresHeader(response, ONE_YEAR_SECONDS); ServletUtils.setLastModifiedHeader(response, System.currentTimeMillis()); ServletUtils.setEtag(response, contentInfo.etag); response.setContentType(contentInfo.mimeType); //设置弹出下载文件请求窗口的Header if (request.getParameter("download") != null) { ServletUtils.setFileDownloadHeader(response, contentInfo.fileName); } //构造OutputStream OutputStream output; if (checkAccetptGzip(request) && contentInfo.needGzip) { //使用压缩传输的outputstream, 使用http1.1 trunked编码不设置content-length. output = buildGzipOutputStream(response); } else { //使用普通outputstream, 设置content-length. response.setContentLength(contentInfo.length); output = response.getOutputStream(); } //高效读取文件内容并输出,然后关闭input file try { FileUtils.copyFile(contentInfo.file, output); output.flush(); } catch (Exception e) { String ip = ServletUtils.getIpAddr(request); String userAgent = request.getHeader("User-Agent"); String eMsg = e.getMessage(); if (StringUtils.isBlank(eMsg)) { eMsg = contentInfo.contentPath; } logger.warn(eMsg + ",ip:" + ip + ",User-Agent:" + userAgent+",param: "+request.getSession().getAttribute(Constants.QUERY_STRING)); } }
private void responseImage(String contentPath) throws Exception { HttpServletResponse response = Struts2Utils.getResponse(); HttpServletRequest request = Struts2Utils.getRequest(); String queryString=(String)request.getSession().getAttribute(Constants.QUERY_STRING); if (StringUtils.isBlank(contentPath)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "path parametter is required."); return; } contentPath = URLDecoder.decode(contentPath, "UTF-8"); String realPath = Constants.LOCKER_STORAGE + new String(contentPath.getBytes("iso-8859-1"), "utf-8"); ContentInfo contentInfo = getContentInfo(realPath); //根据Etag或ModifiedSince Header判断客户端的缓存文件是否有效, 如仍有效则设置返回码为304,直接返回. if (!ServletUtils.checkIfModifiedSince(request, response, contentInfo.lastModified) || !ServletUtils.checkIfNoneMatchEtag(request, response, contentInfo.etag)) { return; } ServletUtils.setExpiresHeader(response, ONE_YEAR_SECONDS); ServletUtils.setLastModifiedHeader(response, System.currentTimeMillis()); ServletUtils.setEtag(response, contentInfo.etag); response.setContentType(contentInfo.mimeType); //设置弹出下载文件请求窗口的Header if (request.getParameter("download") != null) { ServletUtils.setFileDownloadHeader(response, contentInfo.fileName); } //构造OutputStream OutputStream output; if (checkAccetptGzip(request) && contentInfo.needGzip) { //使用压缩传输的outputstream, 使用http1.1 trunked编码不设置content-length. output = buildGzipOutputStream(response); } else { //使用普通outputstream, 设置content-length. response.setContentLength(contentInfo.length); output = response.getOutputStream(); } //高效读取文件内容并输出,然后关闭input file try { FileUtils.copyFile(contentInfo.file, output); output.flush(); } catch (Exception e) { String ip = ServletUtils.getIpAddr(request); String userAgent = request.getHeader("User-Agent"); String eMsg = e.getMessage(); if (StringUtils.isBlank(eMsg)) { eMsg = contentInfo.contentPath; } logger.warn(eMsg + ",ip:" + ip + ",User-Agent:" + userAgent+",param: "+queryString); } }
diff --git a/plugins/maven-resolver-plugin/src/main/java/npanday/plugin/resolver/CopyDependenciesMojo.java b/plugins/maven-resolver-plugin/src/main/java/npanday/plugin/resolver/CopyDependenciesMojo.java index 83f9ed4b..a3e0e71b 100644 --- a/plugins/maven-resolver-plugin/src/main/java/npanday/plugin/resolver/CopyDependenciesMojo.java +++ b/plugins/maven-resolver-plugin/src/main/java/npanday/plugin/resolver/CopyDependenciesMojo.java @@ -1,196 +1,196 @@ /* * 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 npanday.plugin.resolver; import com.google.common.base.Strings; import npanday.ArtifactType; import npanday.LocalRepositoryUtil; import npanday.PathUtil; import npanday.registry.RepositoryRegistry; import npanday.resolver.NPandayDependencyResolution; import npanday.resolver.filter.DotnetExecutableArtifactFilter; import npanday.resolver.filter.DotnetLibraryArtifactFilter; import npanday.resolver.filter.OrArtifactFilter; import npanday.vendor.SettingsUtil; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.metadata.ArtifactMetadata; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; import org.apache.maven.artifact.resolver.filter.InversionArtifactFilter; import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.FileUtils; import java.io.File; import java.io.IOException; import java.util.Set; /** * Resolves and copies .NET assemblies. * * @author <a href="[email protected]">Lars Corneliussen, Faktum Software</a> * @goal copy-dependencies */ public class CopyDependenciesMojo extends AbstractMojo { /** * @parameter expression="${npanday.settings}" default-value="${user.home}/.m2" */ private String settingsPath; /** * @component */ private RepositoryRegistry repositoryRegistry; /** * The maven project. * * @parameter expression="${project}" * @required */ private MavenProject project; /** * The local Maven repository. * * @parameter expression="${settings.localRepository}" */ private File localRepository; /** * @parameter default-value="compile" */ private String includeScope; /** * @parameter */ private String excludeScope; /** * @component */ private NPandayDependencyResolution dependencyResolution; /** * @parameter default-value="${project.build.directory}\.references" */ private File outputDirectory; /** * @parameter default-value="false" */ private boolean skip; public void execute() throws MojoExecutionException, MojoFailureException { String skipReason = ""; if ( !skip ) { ArtifactType knownType = ArtifactType.getArtifactTypeForPackagingName( project.getPackaging() ); if ( knownType.equals( ArtifactType.NULL )) { skip = true; skipReason = - ", because the current project (type:" + project.getPackaging() + ") is not build with NPanday"; + ", because the current project (type:" + project.getPackaging() + ") is not built with NPanday"; } } if ( skip ) { getLog().info( "NPANDAY-158-001: Mojo for copying dependencies was intentionally skipped" + skipReason ); return; } SettingsUtil.applyCustomSettingsIfAvailable( getLog(), repositoryRegistry, settingsPath ); AndArtifactFilter includeFilter = new AndArtifactFilter(); OrArtifactFilter typeIncludes = new OrArtifactFilter(); typeIncludes.add( new DotnetExecutableArtifactFilter() ); typeIncludes.add( new DotnetLibraryArtifactFilter() ); includeFilter.add( typeIncludes ); if ( !Strings.isNullOrEmpty( includeScope ) ) { includeFilter.add( new ScopeArtifactFilter( includeScope ) ); } Set<Artifact> artifacts; try { artifacts = dependencyResolution.require( project, LocalRepositoryUtil.create( localRepository ), includeFilter ); } catch ( ArtifactResolutionException e ) { throw new MojoExecutionException( "NPANDAY-158-003: dependency resolution for scope " + includeScope + " failed!", e ); } /** * Should be resolved, but then not copied */ if ( !Strings.isNullOrEmpty( excludeScope ) ) { includeFilter.add( new InversionArtifactFilter( new ScopeArtifactFilter( excludeScope ) ) ); } for ( Artifact dependency : artifacts ) { if ( !includeFilter.include( dependency ) ) { getLog().debug( "NPANDAY-158-006: dependency " + dependency + " was excluded" ); continue; } try { File targetFile = new File( outputDirectory, PathUtil.getPlainArtifactFileName( dependency ) ); if ( !targetFile.exists() || targetFile.lastModified() != dependency.getFile().lastModified() || targetFile.length() != dependency.getFile().length() ) { getLog().info( "NPANDAY-158-004: copy " + dependency.getFile() + " to " + targetFile ); FileUtils.copyFile( dependency.getFile(), targetFile ); } else{ getLog().debug( "NPANDAY-158-007: dependency " + dependency + " is yet up to date" ); } } catch ( IOException ioe ) { throw new MojoExecutionException( "NPANDAY-158-005: Error copying dependency " + dependency, ioe ); } } } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { String skipReason = ""; if ( !skip ) { ArtifactType knownType = ArtifactType.getArtifactTypeForPackagingName( project.getPackaging() ); if ( knownType.equals( ArtifactType.NULL )) { skip = true; skipReason = ", because the current project (type:" + project.getPackaging() + ") is not build with NPanday"; } } if ( skip ) { getLog().info( "NPANDAY-158-001: Mojo for copying dependencies was intentionally skipped" + skipReason ); return; } SettingsUtil.applyCustomSettingsIfAvailable( getLog(), repositoryRegistry, settingsPath ); AndArtifactFilter includeFilter = new AndArtifactFilter(); OrArtifactFilter typeIncludes = new OrArtifactFilter(); typeIncludes.add( new DotnetExecutableArtifactFilter() ); typeIncludes.add( new DotnetLibraryArtifactFilter() ); includeFilter.add( typeIncludes ); if ( !Strings.isNullOrEmpty( includeScope ) ) { includeFilter.add( new ScopeArtifactFilter( includeScope ) ); } Set<Artifact> artifacts; try { artifacts = dependencyResolution.require( project, LocalRepositoryUtil.create( localRepository ), includeFilter ); } catch ( ArtifactResolutionException e ) { throw new MojoExecutionException( "NPANDAY-158-003: dependency resolution for scope " + includeScope + " failed!", e ); } /** * Should be resolved, but then not copied */ if ( !Strings.isNullOrEmpty( excludeScope ) ) { includeFilter.add( new InversionArtifactFilter( new ScopeArtifactFilter( excludeScope ) ) ); } for ( Artifact dependency : artifacts ) { if ( !includeFilter.include( dependency ) ) { getLog().debug( "NPANDAY-158-006: dependency " + dependency + " was excluded" ); continue; } try { File targetFile = new File( outputDirectory, PathUtil.getPlainArtifactFileName( dependency ) ); if ( !targetFile.exists() || targetFile.lastModified() != dependency.getFile().lastModified() || targetFile.length() != dependency.getFile().length() ) { getLog().info( "NPANDAY-158-004: copy " + dependency.getFile() + " to " + targetFile ); FileUtils.copyFile( dependency.getFile(), targetFile ); } else{ getLog().debug( "NPANDAY-158-007: dependency " + dependency + " is yet up to date" ); } } catch ( IOException ioe ) { throw new MojoExecutionException( "NPANDAY-158-005: Error copying dependency " + dependency, ioe ); } } }
public void execute() throws MojoExecutionException, MojoFailureException { String skipReason = ""; if ( !skip ) { ArtifactType knownType = ArtifactType.getArtifactTypeForPackagingName( project.getPackaging() ); if ( knownType.equals( ArtifactType.NULL )) { skip = true; skipReason = ", because the current project (type:" + project.getPackaging() + ") is not built with NPanday"; } } if ( skip ) { getLog().info( "NPANDAY-158-001: Mojo for copying dependencies was intentionally skipped" + skipReason ); return; } SettingsUtil.applyCustomSettingsIfAvailable( getLog(), repositoryRegistry, settingsPath ); AndArtifactFilter includeFilter = new AndArtifactFilter(); OrArtifactFilter typeIncludes = new OrArtifactFilter(); typeIncludes.add( new DotnetExecutableArtifactFilter() ); typeIncludes.add( new DotnetLibraryArtifactFilter() ); includeFilter.add( typeIncludes ); if ( !Strings.isNullOrEmpty( includeScope ) ) { includeFilter.add( new ScopeArtifactFilter( includeScope ) ); } Set<Artifact> artifacts; try { artifacts = dependencyResolution.require( project, LocalRepositoryUtil.create( localRepository ), includeFilter ); } catch ( ArtifactResolutionException e ) { throw new MojoExecutionException( "NPANDAY-158-003: dependency resolution for scope " + includeScope + " failed!", e ); } /** * Should be resolved, but then not copied */ if ( !Strings.isNullOrEmpty( excludeScope ) ) { includeFilter.add( new InversionArtifactFilter( new ScopeArtifactFilter( excludeScope ) ) ); } for ( Artifact dependency : artifacts ) { if ( !includeFilter.include( dependency ) ) { getLog().debug( "NPANDAY-158-006: dependency " + dependency + " was excluded" ); continue; } try { File targetFile = new File( outputDirectory, PathUtil.getPlainArtifactFileName( dependency ) ); if ( !targetFile.exists() || targetFile.lastModified() != dependency.getFile().lastModified() || targetFile.length() != dependency.getFile().length() ) { getLog().info( "NPANDAY-158-004: copy " + dependency.getFile() + " to " + targetFile ); FileUtils.copyFile( dependency.getFile(), targetFile ); } else{ getLog().debug( "NPANDAY-158-007: dependency " + dependency + " is yet up to date" ); } } catch ( IOException ioe ) { throw new MojoExecutionException( "NPANDAY-158-005: Error copying dependency " + dependency, ioe ); } } }
diff --git a/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/launching/PathFilesContainer.java b/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/launching/PathFilesContainer.java index f12da8cb3..a20803c4d 100644 --- a/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/launching/PathFilesContainer.java +++ b/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/launching/PathFilesContainer.java @@ -1,143 +1,143 @@ package org.eclipse.dltk.core.tests.launching; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.dltk.core.environment.IEnvironment; import org.eclipse.dltk.core.environment.IFileHandle; public class PathFilesContainer { private static final String PATH = "path"; private IEnvironment environment; public PathFilesContainer(IEnvironment environment) { this.environment = environment; } public void accept(IFileVisitor visitor) { accept(visitor, new NullProgressMonitor()); } public void accept(IFileVisitor visitor, IProgressMonitor monitor) { accept(visitor, -1, monitor); } public void accept(IFileVisitor visitor, int deep, IProgressMonitor monitor) { if (monitor.isCanceled()) { return; } // Path variable Map env = DebugPlugin.getDefault().getLaunchManager() .getNativeEnvironmentCasePreserved(); String path = null; final Iterator it = env.keySet().iterator(); while (it.hasNext()) { final String name = (String) it.next(); if (name.compareToIgnoreCase(PATH) == 0) { //$NON-NLS-1$ path = (String) env.get(name); } } if (path == null) { return; } // Folder list final String separator = Platform.getOS().equals(Platform.OS_WIN32) ? ";" : ":"; //$NON-NLS-1$ $NON-NLS-1$ final List folders = new ArrayList(); String[] res = path.split(separator); for (int i = 0; i < res.length; i++) { folders.add(Path.fromOSString(res[i])); } ArrayList searchedFiles = new ArrayList(); final Iterator iter = folders.iterator(); while (iter.hasNext()) { final IPath folder = (IPath) iter.next(); if (folder != null) { IFileHandle f = environment.getFile(folder); if (f.isDirectory()) { visitFolder(visitor, f, monitor, deep, searchedFiles); } } } } /** * Searches the specified directory recursively for installed Interpreters, * adding each detected Interpreter to the <code>found</code> list. Any * directories specified in the <code>ignore</code> are not traversed. * * @param visitor * * @param ry * @param found * @param types * @param ignore * @param deep * deepness of search. -1 if infinite. * @param searchedFiles */ protected void visitFolder(IFileVisitor visitor, IFileHandle directory, IProgressMonitor monitor, int deep, ArrayList searchedFiles) { if (deep == 0) { return; } if (monitor.isCanceled()) { return; } if (searchedFiles.contains(directory)) { return; } IFileHandle[] childFiles = directory.getChildren(); if (childFiles == null) { return; } List subDirs = new ArrayList(); for (int i = 0; i < childFiles.length; i++) { if (monitor.isCanceled()) { return; } final IFileHandle file = childFiles[i]; monitor.subTask(MessageFormat.format("Searching {0}", new String[] { file.getCanonicalPath() })); // Check if file is a symlink if (file.isDirectory() && (!file.getCanonicalPath().equals( - file.getAbsolutePath()))) { + file.toOSString()))) { continue; } if (visitor.visit(file)) { while (!subDirs.isEmpty()) { IFileHandle subDir = (IFileHandle) subDirs.remove(0); visitFolder(visitor, subDir, monitor, deep - 1, searchedFiles); } } } searchedFiles.add(directory); } }
true
true
protected void visitFolder(IFileVisitor visitor, IFileHandle directory, IProgressMonitor monitor, int deep, ArrayList searchedFiles) { if (deep == 0) { return; } if (monitor.isCanceled()) { return; } if (searchedFiles.contains(directory)) { return; } IFileHandle[] childFiles = directory.getChildren(); if (childFiles == null) { return; } List subDirs = new ArrayList(); for (int i = 0; i < childFiles.length; i++) { if (monitor.isCanceled()) { return; } final IFileHandle file = childFiles[i]; monitor.subTask(MessageFormat.format("Searching {0}", new String[] { file.getCanonicalPath() })); // Check if file is a symlink if (file.isDirectory() && (!file.getCanonicalPath().equals( file.getAbsolutePath()))) { continue; } if (visitor.visit(file)) { while (!subDirs.isEmpty()) { IFileHandle subDir = (IFileHandle) subDirs.remove(0); visitFolder(visitor, subDir, monitor, deep - 1, searchedFiles); } } } searchedFiles.add(directory); }
protected void visitFolder(IFileVisitor visitor, IFileHandle directory, IProgressMonitor monitor, int deep, ArrayList searchedFiles) { if (deep == 0) { return; } if (monitor.isCanceled()) { return; } if (searchedFiles.contains(directory)) { return; } IFileHandle[] childFiles = directory.getChildren(); if (childFiles == null) { return; } List subDirs = new ArrayList(); for (int i = 0; i < childFiles.length; i++) { if (monitor.isCanceled()) { return; } final IFileHandle file = childFiles[i]; monitor.subTask(MessageFormat.format("Searching {0}", new String[] { file.getCanonicalPath() })); // Check if file is a symlink if (file.isDirectory() && (!file.getCanonicalPath().equals( file.toOSString()))) { continue; } if (visitor.visit(file)) { while (!subDirs.isEmpty()) { IFileHandle subDir = (IFileHandle) subDirs.remove(0); visitFolder(visitor, subDir, monitor, deep - 1, searchedFiles); } } } searchedFiles.add(directory); }
diff --git a/src/jogl/classes/com/jogamp/opengl/impl/windows/wgl/WindowsWGLContext.java b/src/jogl/classes/com/jogamp/opengl/impl/windows/wgl/WindowsWGLContext.java index e0a255ad9..266868d69 100644 --- a/src/jogl/classes/com/jogamp/opengl/impl/windows/wgl/WindowsWGLContext.java +++ b/src/jogl/classes/com/jogamp/opengl/impl/windows/wgl/WindowsWGLContext.java @@ -1,443 +1,443 @@ /* * Copyright (c) 2003 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 or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package com.jogamp.opengl.impl.windows.wgl; import java.nio.*; import java.util.*; import javax.media.opengl.*; import javax.media.nativewindow.*; import com.jogamp.opengl.impl.*; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; public class WindowsWGLContext extends GLContextImpl { protected long hglrc; private boolean wglGetExtensionsStringEXTInitialized; private boolean wglGetExtensionsStringEXTAvailable; private boolean wglMakeContextCurrentInitialized; private boolean wglMakeContextCurrentARBAvailable; private boolean wglMakeContextCurrentEXTAvailable; private static final Map/*<String, String>*/ functionNameMap; private static final Map/*<String, String>*/ extensionNameMap; private WGLExt wglExt; // Table that holds the addresses of the native C-language entry points for // WGL extension functions. private WGLExtProcAddressTable wglExtProcAddressTable; static { functionNameMap = new HashMap(); functionNameMap.put("glAllocateMemoryNV", "wglAllocateMemoryNV"); functionNameMap.put("glFreeMemoryNV", "wglFreeMemoryNV"); extensionNameMap = new HashMap(); extensionNameMap.put("GL_ARB_pbuffer", "WGL_ARB_pbuffer"); extensionNameMap.put("GL_ARB_pixel_format", "WGL_ARB_pixel_format"); } // FIXME: figure out how to hook back in the Java 2D / JOGL bridge public WindowsWGLContext(GLDrawableImpl drawable, GLDrawableImpl drawableRead, GLContext shareWith) { super(drawable, drawableRead, shareWith); } public WindowsWGLContext(GLDrawableImpl drawable, GLContext shareWith) { this(drawable, null, shareWith); } public Object getPlatformGLExtensions() { return getWGLExt(); } public WGLExt getWGLExt() { if (wglExt == null) { wglExt = new WGLExtImpl(this); } return wglExt; } public boolean wglMakeContextCurrent(long hDrawDC, long hReadDC, long hglrc) { WGLExt wglExt = getWGLExt(); if (!wglMakeContextCurrentInitialized) { wglMakeContextCurrentARBAvailable = isFunctionAvailable("wglMakeContextCurrentARB"); wglMakeContextCurrentEXTAvailable = isFunctionAvailable("wglMakeContextCurrentEXT"); wglMakeContextCurrentInitialized = true; if(DEBUG) { System.err.println("WindowsWGLContext.wglMakeContextCurrent: ARB "+wglMakeContextCurrentARBAvailable+", EXT "+wglMakeContextCurrentEXTAvailable); } } if(wglMakeContextCurrentARBAvailable) { return wglExt.wglMakeContextCurrentARB(hDrawDC, hReadDC, hglrc); } else if(wglMakeContextCurrentEXTAvailable) { return wglExt.wglMakeContextCurrentEXT(hDrawDC, hReadDC, hglrc); } return WGL.wglMakeCurrent(hDrawDC, hglrc); } public final ProcAddressTable getPlatformExtProcAddressTable() { return getWGLExtProcAddressTable(); } public final WGLExtProcAddressTable getWGLExtProcAddressTable() { return wglExtProcAddressTable; } protected Map/*<String, String>*/ getFunctionNameMap() { return functionNameMap; } protected Map/*<String, String>*/ getExtensionNameMap() { return extensionNameMap; } protected void destroyContextARBImpl(long context) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(context); } protected long createContextARBImpl(long share, boolean direct, int ctp, int major, int minor) { WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); WGLExt wglExt; if(null==factory.getSharedContext()) { wglExt = getWGLExt(); } else { wglExt = ((WindowsWGLContext)factory.getSharedContext()).getWGLExt(); } boolean ctBwdCompat = 0 != ( CTX_PROFILE_COMPAT & ctp ) ; boolean ctFwdCompat = 0 != ( CTX_OPTION_FORWARD & ctp ) ; boolean ctDebug = 0 != ( CTX_OPTION_DEBUG & ctp ) ; long _context=0; int attribs[] = { /* 0 */ WGLExt.WGL_CONTEXT_MAJOR_VERSION_ARB, major, /* 2 */ WGLExt.WGL_CONTEXT_MINOR_VERSION_ARB, minor, /* 4 */ WGLExt.WGL_CONTEXT_LAYER_PLANE_ARB, WGLExt.WGL_CONTEXT_LAYER_PLANE_ARB, // default /* 6 */ WGLExt.WGL_CONTEXT_FLAGS_ARB, 0, /* 8 */ 0, 0, /* 10 */ 0 }; if ( major > 3 || major == 3 && minor >= 2 ) { // FIXME: Verify with a None drawable binding (default framebuffer) attribs[8+0] = WGLExt.WGL_CONTEXT_PROFILE_MASK_ARB; if( ctBwdCompat ) { attribs[8+1] = WGLExt.WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; } else { attribs[8+1] = WGLExt.WGL_CONTEXT_CORE_PROFILE_BIT_ARB; } } if ( major >= 3 ) { if( !ctBwdCompat && ctFwdCompat ) { attribs[6+1] |= WGLExt.WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; } if( ctDebug) { attribs[6+1] |= WGLExt.WGL_CONTEXT_DEBUG_BIT_ARB; } } _context = wglExt.wglCreateContextAttribsARB(drawable.getNativeWindow().getSurfaceHandle(), share, attribs, 0); if(0==_context) { if(DEBUG) { System.err.println("WindowsWGLContext.createContextARB couldn't create "+getGLVersion(null, major, minor, ctp, "@creation")); } } else { // In contrast to GLX no verification with a drawable binding, ie default framebuffer, is necessary, // if no 3.2 is available creation fails already! // Nevertheless .. we do it .. if (!WGL.wglMakeCurrent(drawable.getNativeWindow().getSurfaceHandle(), _context)) { if(DEBUG) { System.err.println("WindowsWGLContext.createContextARB couldn't make current "+getGLVersion(null, major, minor, ctp, "@creation")); } WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(_context); _context = 0; } } return _context; } /** * Creates and initializes an appropriate OpenGL context. Should only be * called by {@link #makeCurrentImpl()}. */ protected void create() { if(0!=context) { throw new GLException("context is not null: "+context); } WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); GLCapabilities glCaps = drawable.getChosenGLCapabilities(); // Windows can set up sharing of display lists after creation time WindowsWGLContext other = (WindowsWGLContext) GLContextShareSet.getShareContext(this); long share = 0; if (other != null) { share = other.getHGLRC(); if (share == 0) { throw new GLException("GLContextShareSet returned an invalid OpenGL context"); } } int minor[] = new int[1]; int major[] = new int[1]; int ctp[] = new int[1]; boolean createContextARBTried = false; // utilize the shared context's GLXExt in case it was using the ARB method and it already exists - if(null!=factory.getSharedContext() && factory.getSharedContext().isCreatedWithARBMethod()) { + if(false && null!=factory.getSharedContext() && factory.getSharedContext().isCreatedWithARBMethod()) { // FIXME JAU if(DEBUG) { System.err.println("WindowsWGLContext.createContext using shared Context: "+factory.getSharedContext()); } hglrc = createContextARB(share, true, major, minor, ctp); createContextARBTried = true; } long temp_hglrc = 0; if(0==hglrc) { // To use WGL_ARB_create_context, we have to make a temp context current, // so we are able to use GetProcAddress temp_hglrc = WGL.wglCreateContext(drawable.getNativeWindow().getSurfaceHandle()); if (temp_hglrc == 0) { throw new GLException("Unable to create temp OpenGL context for device context " + toHexString(drawable.getNativeWindow().getSurfaceHandle())); } if (!WGL.wglMakeCurrent(drawable.getNativeWindow().getSurfaceHandle(), temp_hglrc)) { throw new GLException("Error making temp context current: 0x" + Integer.toHexString(WGL.GetLastError())); } setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); if( createContextARBTried || !isFunctionAvailable("wglCreateContextAttribsARB") || !isExtensionAvailable("WGL_ARB_create_context") ) { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("Unable to create OpenGL >= 3.1 context (no WGL_ARB_create_context)"); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; return; } - hglrc = createContextARB(share, true, major, minor, ctp); - createContextARBTried=true; + // FIXME JAU hglrc = createContextARB(share, true, major, minor, ctp); + // FIXME JAU createContextARBTried=true; } if(0!=hglrc) { share = 0; // mark as shared .. WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { throw new GLException("Cannot make previous verified context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } else { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("WindowsWGLContext.createContext failed, but context > GL2 requested "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")+", "); } if(DEBUG) { System.err.println("WindowsWGLContext.createContext failed, fall back to !ARB context "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(hglrc); throw new GLException("Error making old context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } if(0!=share) { if (!WGL.wglShareLists(share, hglrc)) { throw new GLException("wglShareLists(" + toHexString(share) + ", " + toHexString(hglrc) + ") failed: error code 0x" + Integer.toHexString(WGL.GetLastError())); } } GLContextShareSet.contextCreated(this); } protected int makeCurrentImpl() throws GLException { if (0 == drawable.getNativeWindow().getSurfaceHandle()) { throw new GLException("drawable has invalid surface handle: "+drawable); } boolean created = false; if (hglrc == 0) { create(); created = true; if (DEBUG) { System.err.println(getThreadName() + ": !!! Created GL context for " + getClass().getName()); } } if (WGL.wglGetCurrentContext() != hglrc) { if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { throw new GLException("Error making context current: 0x" + Integer.toHexString(WGL.GetLastError()) + ", " + this); } else { if (DEBUG && VERBOSE) { System.err.println(getThreadName() + ": wglMakeCurrent(hdc " + toHexString(drawable.getNativeWindow().getSurfaceHandle()) + ", hglrc " + toHexString(hglrc) + ") succeeded"); } } } if (created) { setGLFunctionAvailability(false, -1, -1, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); WindowsWGLGraphicsConfiguration config = (WindowsWGLGraphicsConfiguration)drawable.getNativeWindow().getGraphicsConfiguration().getNativeGraphicsConfiguration(); config.updateCapabilitiesByWGL(this); return CONTEXT_CURRENT_NEW; } return CONTEXT_CURRENT; } protected void releaseImpl() throws GLException { if (!wglMakeContextCurrent(0, 0, 0)) { throw new GLException("Error freeing OpenGL context: 0x" + Integer.toHexString(WGL.GetLastError())); } } protected void destroyImpl() throws GLException { if (DEBUG) { Exception e = new Exception(getThreadName() + ": !!! Destroyed OpenGL context " + toHexString(hglrc)); e.printStackTrace(); } if (hglrc != 0) { if (!WGL.wglDeleteContext(hglrc)) { throw new GLException("Unable to delete OpenGL context"); } hglrc = 0; GLContextShareSet.contextDestroyed(this); } } public boolean isCreated() { return (hglrc != 0); } public void copy(GLContext source, int mask) throws GLException { long dst = getHGLRC(); long src = ((WindowsWGLContext) source).getHGLRC(); if (src == 0) { throw new GLException("Source OpenGL context has not been created"); } if (dst == 0) { throw new GLException("Destination OpenGL context has not been created"); } if (!WGL.wglCopyContext(src, dst, mask)) { throw new GLException("wglCopyContext failed"); } } protected void updateGLProcAddressTable(int major, int minor, int ctp) { if (DEBUG) { System.err.println(getThreadName() + ": !!! Initializing WGL extension address table for " + this); } wglGetExtensionsStringEXTInitialized=false; wglGetExtensionsStringEXTAvailable=false; wglMakeContextCurrentInitialized=false; wglMakeContextCurrentARBAvailable=false; wglMakeContextCurrentEXTAvailable=false; if (wglExtProcAddressTable == null) { // FIXME: cache ProcAddressTables by capability bits so we can // share them among contexts with the same capabilities wglExtProcAddressTable = new WGLExtProcAddressTable(new GLProcAddressResolver()); } resetProcAddressTable(getWGLExtProcAddressTable()); super.updateGLProcAddressTable(major, minor, ctp); } public String getPlatformExtensionsString() { if (!wglGetExtensionsStringEXTInitialized) { wglGetExtensionsStringEXTAvailable = (WGL.wglGetProcAddress("wglGetExtensionsStringEXT") != 0); wglGetExtensionsStringEXTInitialized = true; } if (wglGetExtensionsStringEXTAvailable) { return getWGLExt().wglGetExtensionsStringEXT(); } else { return ""; } } protected void setSwapIntervalImpl(int interval) { WGLExt wglExt = getWGLExt(); if (wglExt.isExtensionAvailable("WGL_EXT_swap_control")) { if ( wglExt.wglSwapIntervalEXT(interval) ) { currentSwapInterval = interval ; } } } public ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3) { return getWGLExt().wglAllocateMemoryNV(arg0, arg1, arg2, arg3); } public int getOffscreenContextPixelDataType() { throw new GLException("Should not call this"); } public int getOffscreenContextReadBuffer() { throw new GLException("Should not call this"); } public boolean offscreenImageNeedsVerticalFlip() { throw new GLException("Should not call this"); } public void bindPbufferToTexture() { throw new GLException("Should not call this"); } public void releasePbufferFromTexture() { throw new GLException("Should not call this"); } //---------------------------------------------------------------------- // Internals only below this point // public long getHGLRC() { return hglrc; } }
false
true
protected void create() { if(0!=context) { throw new GLException("context is not null: "+context); } WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); GLCapabilities glCaps = drawable.getChosenGLCapabilities(); // Windows can set up sharing of display lists after creation time WindowsWGLContext other = (WindowsWGLContext) GLContextShareSet.getShareContext(this); long share = 0; if (other != null) { share = other.getHGLRC(); if (share == 0) { throw new GLException("GLContextShareSet returned an invalid OpenGL context"); } } int minor[] = new int[1]; int major[] = new int[1]; int ctp[] = new int[1]; boolean createContextARBTried = false; // utilize the shared context's GLXExt in case it was using the ARB method and it already exists if(null!=factory.getSharedContext() && factory.getSharedContext().isCreatedWithARBMethod()) { if(DEBUG) { System.err.println("WindowsWGLContext.createContext using shared Context: "+factory.getSharedContext()); } hglrc = createContextARB(share, true, major, minor, ctp); createContextARBTried = true; } long temp_hglrc = 0; if(0==hglrc) { // To use WGL_ARB_create_context, we have to make a temp context current, // so we are able to use GetProcAddress temp_hglrc = WGL.wglCreateContext(drawable.getNativeWindow().getSurfaceHandle()); if (temp_hglrc == 0) { throw new GLException("Unable to create temp OpenGL context for device context " + toHexString(drawable.getNativeWindow().getSurfaceHandle())); } if (!WGL.wglMakeCurrent(drawable.getNativeWindow().getSurfaceHandle(), temp_hglrc)) { throw new GLException("Error making temp context current: 0x" + Integer.toHexString(WGL.GetLastError())); } setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); if( createContextARBTried || !isFunctionAvailable("wglCreateContextAttribsARB") || !isExtensionAvailable("WGL_ARB_create_context") ) { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("Unable to create OpenGL >= 3.1 context (no WGL_ARB_create_context)"); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; return; } hglrc = createContextARB(share, true, major, minor, ctp); createContextARBTried=true; } if(0!=hglrc) { share = 0; // mark as shared .. WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { throw new GLException("Cannot make previous verified context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } else { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("WindowsWGLContext.createContext failed, but context > GL2 requested "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")+", "); } if(DEBUG) { System.err.println("WindowsWGLContext.createContext failed, fall back to !ARB context "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(hglrc); throw new GLException("Error making old context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } if(0!=share) { if (!WGL.wglShareLists(share, hglrc)) { throw new GLException("wglShareLists(" + toHexString(share) + ", " + toHexString(hglrc) + ") failed: error code 0x" + Integer.toHexString(WGL.GetLastError())); } } GLContextShareSet.contextCreated(this); }
protected void create() { if(0!=context) { throw new GLException("context is not null: "+context); } WindowsWGLDrawableFactory factory = (WindowsWGLDrawableFactory)drawable.getFactoryImpl(); GLCapabilities glCaps = drawable.getChosenGLCapabilities(); // Windows can set up sharing of display lists after creation time WindowsWGLContext other = (WindowsWGLContext) GLContextShareSet.getShareContext(this); long share = 0; if (other != null) { share = other.getHGLRC(); if (share == 0) { throw new GLException("GLContextShareSet returned an invalid OpenGL context"); } } int minor[] = new int[1]; int major[] = new int[1]; int ctp[] = new int[1]; boolean createContextARBTried = false; // utilize the shared context's GLXExt in case it was using the ARB method and it already exists if(false && null!=factory.getSharedContext() && factory.getSharedContext().isCreatedWithARBMethod()) { // FIXME JAU if(DEBUG) { System.err.println("WindowsWGLContext.createContext using shared Context: "+factory.getSharedContext()); } hglrc = createContextARB(share, true, major, minor, ctp); createContextARBTried = true; } long temp_hglrc = 0; if(0==hglrc) { // To use WGL_ARB_create_context, we have to make a temp context current, // so we are able to use GetProcAddress temp_hglrc = WGL.wglCreateContext(drawable.getNativeWindow().getSurfaceHandle()); if (temp_hglrc == 0) { throw new GLException("Unable to create temp OpenGL context for device context " + toHexString(drawable.getNativeWindow().getSurfaceHandle())); } if (!WGL.wglMakeCurrent(drawable.getNativeWindow().getSurfaceHandle(), temp_hglrc)) { throw new GLException("Error making temp context current: 0x" + Integer.toHexString(WGL.GetLastError())); } setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT|CTX_OPTION_ANY); if( createContextARBTried || !isFunctionAvailable("wglCreateContextAttribsARB") || !isExtensionAvailable("WGL_ARB_create_context") ) { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("Unable to create OpenGL >= 3.1 context (no WGL_ARB_create_context)"); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; return; } // FIXME JAU hglrc = createContextARB(share, true, major, minor, ctp); // FIXME JAU createContextARBTried=true; } if(0!=hglrc) { share = 0; // mark as shared .. WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { throw new GLException("Cannot make previous verified context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } else { if(glCaps.getGLProfile().isGL3()) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(temp_hglrc); throw new GLException("WindowsWGLContext.createContext failed, but context > GL2 requested "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")+", "); } if(DEBUG) { System.err.println("WindowsWGLContext.createContext failed, fall back to !ARB context "+getGLVersion(null, major[0], minor[0], ctp[0], "@creation")); } // continue with temp context for GL < 3.0 hglrc = temp_hglrc; if (!wglMakeContextCurrent(drawable.getNativeWindow().getSurfaceHandle(), drawableRead.getNativeWindow().getSurfaceHandle(), hglrc)) { WGL.wglMakeCurrent(0, 0); WGL.wglDeleteContext(hglrc); throw new GLException("Error making old context current: 0x" + Integer.toHexString(WGL.GetLastError())); } } if(0!=share) { if (!WGL.wglShareLists(share, hglrc)) { throw new GLException("wglShareLists(" + toHexString(share) + ", " + toHexString(hglrc) + ") failed: error code 0x" + Integer.toHexString(WGL.GetLastError())); } } GLContextShareSet.contextCreated(this); }
diff --git a/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextLineIndentationFeature.java b/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextLineIndentationFeature.java index 0336e2b8..37567ab0 100644 --- a/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextLineIndentationFeature.java +++ b/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextLineIndentationFeature.java @@ -1,39 +1,39 @@ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.features.FeatureCalculator; /** * * @author Dominika Tkaczyk ([email protected]) */ public class NextLineIndentationFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasNext()) { return 0.0; } int i = 0; BxLine l = line.getNext(); double meanX = 0; while (l.hasNext() && i < 5) { l = l.getNext(); if ((line.getX() < l.getX() && l.getX() < line.getX() + line.getWidth()) || (l.getX() < line.getX() && line.getX() < l.getX() + l.getWidth())) { meanX += l.getX(); i++; } else { break; } } - if (i == 0) { + if (i == 0 || line.getWidth() == 0) { return 0.0; } meanX /= i; return Math.abs(line.getNext().getX() - meanX) / (double) line.getWidth(); } }
true
true
public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasNext()) { return 0.0; } int i = 0; BxLine l = line.getNext(); double meanX = 0; while (l.hasNext() && i < 5) { l = l.getNext(); if ((line.getX() < l.getX() && l.getX() < line.getX() + line.getWidth()) || (l.getX() < line.getX() && line.getX() < l.getX() + l.getWidth())) { meanX += l.getX(); i++; } else { break; } } if (i == 0) { return 0.0; } meanX /= i; return Math.abs(line.getNext().getX() - meanX) / (double) line.getWidth(); }
public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasNext()) { return 0.0; } int i = 0; BxLine l = line.getNext(); double meanX = 0; while (l.hasNext() && i < 5) { l = l.getNext(); if ((line.getX() < l.getX() && l.getX() < line.getX() + line.getWidth()) || (l.getX() < line.getX() && line.getX() < l.getX() + l.getWidth())) { meanX += l.getX(); i++; } else { break; } } if (i == 0 || line.getWidth() == 0) { return 0.0; } meanX /= i; return Math.abs(line.getNext().getX() - meanX) / (double) line.getWidth(); }
diff --git a/gdp-ui/src/main/java/gov/usgs/service/ContactService.java b/gdp-ui/src/main/java/gov/usgs/service/ContactService.java index 4e1344c5..fe944206 100644 --- a/gdp-ui/src/main/java/gov/usgs/service/ContactService.java +++ b/gdp-ui/src/main/java/gov/usgs/service/ContactService.java @@ -1,95 +1,94 @@ package gov.usgs.service; import gov.usgs.cida.gdp.communication.EmailMessage; import java.io.IOException; import java.io.PrintWriter; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ContactService extends HttpServlet { private static final long serialVersionUID = -8308644813099149346L; private final static Logger log = LoggerFactory.getLogger(ContactService.class); private static final String USGS_REMEDY = "[email protected]"; private static final String DEFAULT_SUBJECT = "Geo Data Portal User Comments"; private static final String DEFAULT_GDP_ADDRESS = "[email protected]"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String comments = req.getParameter("comments"); String email = req.getParameter("email"); String emailResponseRequired = req.getParameter("replyrequired"); String emailResponseRequiredText = ("true".equals(emailResponseRequired)) ? "*** User (" + email + ") Requires a Response ***\n\n" : ""; String autoInsertedContent = "This is an auto-generated email from the USGS Geo Data Portal. " + "Below is a copy of the message you (" + email + ") submitted. If you feel you have received this message erroneously, " + "please contact [email protected].\n\n"; log.info("Serving: " + req.getQueryString()); log.info("ContactService Request Email: " + email + " ResponseRequired:" + emailResponseRequired); email = (StringUtils.isBlank(email)) ? DEFAULT_GDP_ADDRESS : email; EmailMessage msg = new EmailMessage(); { msg.setTo(USGS_REMEDY); -// msg.setTo("[email protected]"); msg.setSubject(DEFAULT_SUBJECT); msg.setContent(autoInsertedContent + emailResponseRequiredText + comments); // set the from and reply to address if there is one. try { msg.setFrom(email); msg.setReplyTo(new InternetAddress[]{new InternetAddress(email)}); } catch (AddressException ex) { try { log.error(email + " could not be parsed as a valid reply-to email address. Setting reply-to to " + DEFAULT_GDP_ADDRESS, ex); msg.setReplyTo(new InternetAddress[]{new InternetAddress(DEFAULT_GDP_ADDRESS)}); } catch (AddressException ex1) { log.error("Could not properly set e-mail reply-to field.", ex1); } } } PrintWriter writer = resp.getWriter(); try { msg.send(); log.info("Email sent to GDP"); try { writer.append("{ \"status\" : \"success\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } catch (Exception ex) { log.error("Could not send email message.", ex); try { writer.append("{ \"status\" : \"fail\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String comments = req.getParameter("comments"); String email = req.getParameter("email"); String emailResponseRequired = req.getParameter("replyrequired"); String emailResponseRequiredText = ("true".equals(emailResponseRequired)) ? "*** User (" + email + ") Requires a Response ***\n\n" : ""; String autoInsertedContent = "This is an auto-generated email from the USGS Geo Data Portal. " + "Below is a copy of the message you (" + email + ") submitted. If you feel you have received this message erroneously, " + "please contact [email protected].\n\n"; log.info("Serving: " + req.getQueryString()); log.info("ContactService Request Email: " + email + " ResponseRequired:" + emailResponseRequired); email = (StringUtils.isBlank(email)) ? DEFAULT_GDP_ADDRESS : email; EmailMessage msg = new EmailMessage(); { msg.setTo(USGS_REMEDY); // msg.setTo("[email protected]"); msg.setSubject(DEFAULT_SUBJECT); msg.setContent(autoInsertedContent + emailResponseRequiredText + comments); // set the from and reply to address if there is one. try { msg.setFrom(email); msg.setReplyTo(new InternetAddress[]{new InternetAddress(email)}); } catch (AddressException ex) { try { log.error(email + " could not be parsed as a valid reply-to email address. Setting reply-to to " + DEFAULT_GDP_ADDRESS, ex); msg.setReplyTo(new InternetAddress[]{new InternetAddress(DEFAULT_GDP_ADDRESS)}); } catch (AddressException ex1) { log.error("Could not properly set e-mail reply-to field.", ex1); } } } PrintWriter writer = resp.getWriter(); try { msg.send(); log.info("Email sent to GDP"); try { writer.append("{ \"status\" : \"success\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } catch (Exception ex) { log.error("Could not send email message.", ex); try { writer.append("{ \"status\" : \"fail\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String comments = req.getParameter("comments"); String email = req.getParameter("email"); String emailResponseRequired = req.getParameter("replyrequired"); String emailResponseRequiredText = ("true".equals(emailResponseRequired)) ? "*** User (" + email + ") Requires a Response ***\n\n" : ""; String autoInsertedContent = "This is an auto-generated email from the USGS Geo Data Portal. " + "Below is a copy of the message you (" + email + ") submitted. If you feel you have received this message erroneously, " + "please contact [email protected].\n\n"; log.info("Serving: " + req.getQueryString()); log.info("ContactService Request Email: " + email + " ResponseRequired:" + emailResponseRequired); email = (StringUtils.isBlank(email)) ? DEFAULT_GDP_ADDRESS : email; EmailMessage msg = new EmailMessage(); { msg.setTo(USGS_REMEDY); msg.setSubject(DEFAULT_SUBJECT); msg.setContent(autoInsertedContent + emailResponseRequiredText + comments); // set the from and reply to address if there is one. try { msg.setFrom(email); msg.setReplyTo(new InternetAddress[]{new InternetAddress(email)}); } catch (AddressException ex) { try { log.error(email + " could not be parsed as a valid reply-to email address. Setting reply-to to " + DEFAULT_GDP_ADDRESS, ex); msg.setReplyTo(new InternetAddress[]{new InternetAddress(DEFAULT_GDP_ADDRESS)}); } catch (AddressException ex1) { log.error("Could not properly set e-mail reply-to field.", ex1); } } } PrintWriter writer = resp.getWriter(); try { msg.send(); log.info("Email sent to GDP"); try { writer.append("{ \"status\" : \"success\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } catch (Exception ex) { log.error("Could not send email message.", ex); try { writer.append("{ \"status\" : \"fail\" }"); writer.flush(); } finally { if (writer != null) { writer.flush(); } } } }
diff --git a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SourceService.java b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SourceService.java index 04b74c400..6e08a6fc2 100644 --- a/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SourceService.java +++ b/core/src/main/java/edu/northwestern/bioinformatics/studycalendar/service/SourceService.java @@ -1,134 +1,134 @@ package edu.northwestern.bioinformatics.studycalendar.service; import edu.northwestern.bioinformatics.studycalendar.dao.PlannedActivityDao; import edu.northwestern.bioinformatics.studycalendar.dao.SourceDao; import edu.northwestern.bioinformatics.studycalendar.dao.ActivityDao; import edu.northwestern.bioinformatics.studycalendar.domain.Activity; import edu.northwestern.bioinformatics.studycalendar.domain.PlannedActivity; import edu.northwestern.bioinformatics.studycalendar.domain.Source; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.persistence.Transient; import javax.transaction.Transaction; import java.util.*; /** * @author Saurabh Agrawal */ @Transactional(propagation = Propagation.REQUIRED, readOnly = true) public class SourceService { private SourceDao sourceDao; private ActivityService activityService; public Source getByName(String name) { return sourceDao.getByName(name); } /** * <p> Updates the source. Following is the logic to update a source * <li> * Add any activities that do not already exist. </li> * <li> Update any activities that already exist and still exist in the new representation. Activities should be matched by their natural key -- i.e., the code. </li> * <li>Remove any activities that do not exist in the new representation, so long as they are not used any any existing templates. </li> * </p> * * @param source source * @param targetSource targetSource */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void updateSource(final Source source, final Source targetSource) { BeanUtils.copyProperties(source, targetSource, new String[]{"activities", "id"}); //delete or update the activity removeAndUpdateActivities(targetSource.getActivities(), source.getActivities()); //add new activities targetSource.addNewActivities(source.getActivities()); sourceDao.save(source); } /** * Add, update or remove activities from source. * * @param existingSource * @param activitiesToAddAndRemove */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public void updateSource(final Source existingSource, final List<Activity> activitiesToAddAndRemove) { //delete or update the activity removeAndUpdateActivities(existingSource.getActivities(), activitiesToAddAndRemove); //add new activities existingSource.addNewActivities(activitiesToAddAndRemove); sourceDao.save(existingSource); } /** * <p>Updates and remove activities from source. * <li> Update any activities that already exist and still exist in the new representation. Activities should be matched by their natural key -- i.e., the code. </li> * <li>Remove any activities that do not exist in the new representation, so long as they are not used any any existing templates. </li> * </p> * * @param targetActivities existing activities * @param activitiesToAddAndRemove */ @Transactional(propagation = Propagation.REQUIRED, readOnly = false) private void removeAndUpdateActivities(List<Activity> targetActivities, final List<Activity> activitiesToAddAndRemove) { //delete or update the activity List<Activity> activitiesToRemove = new ArrayList<Activity>(); Map<Activity, Activity> activityToUpdate = new HashMap<Activity,Activity>(); for (Activity existingActivity : targetActivities) { Activity activity = existingActivity.findActivityInCollectionWhichHasSameCode(activitiesToAddAndRemove); if (activity != null) { //for the case when exist A:1 and B:2, and we import A:2 and B:1 - we need to check names Activity activityWithName = existingActivity.findActivityInCollectionWhichHasSameName(activitiesToAddAndRemove); - if (activityWithName == null || (activityWithName!= null && activityWithName.equals(activity))) { + if (activityWithName == null || activityWithName.equals(activity)) { activityToUpdate.put(existingActivity, activity); } else { activitiesToRemove.add(existingActivity); } } else { activitiesToRemove.add(existingActivity); } } targetActivities.removeAll(activitiesToRemove); for (Activity activity : activitiesToRemove) { boolean deleteActivity = activityService.deleteActivity(activity); //remove this activity only if its not used any where if (!deleteActivity) { targetActivities.addAll(activitiesToRemove); throw new StudyCalendarValidationException("Import failed. " + - "Activity " + activity.getName() + " with code " + activity.getCode() + " is referenced withing the study. " + + "Activity " + activity.getName() + " with code " + activity.getCode() + " is referenced within the study. " + "Please remove those references manuall and try to import activity again "); } } Set<Activity> existingActivities = activityToUpdate.keySet(); for (Activity existingActivity : existingActivities) { Activity activity = activityToUpdate.get(existingActivity); existingActivity.updateActivity(activity); } } @Required public void setSourceDao(final SourceDao sourceDao) { this.sourceDao = sourceDao; } public void setActivityService(ActivityService activityService) { this.activityService = activityService; } }
false
true
private void removeAndUpdateActivities(List<Activity> targetActivities, final List<Activity> activitiesToAddAndRemove) { //delete or update the activity List<Activity> activitiesToRemove = new ArrayList<Activity>(); Map<Activity, Activity> activityToUpdate = new HashMap<Activity,Activity>(); for (Activity existingActivity : targetActivities) { Activity activity = existingActivity.findActivityInCollectionWhichHasSameCode(activitiesToAddAndRemove); if (activity != null) { //for the case when exist A:1 and B:2, and we import A:2 and B:1 - we need to check names Activity activityWithName = existingActivity.findActivityInCollectionWhichHasSameName(activitiesToAddAndRemove); if (activityWithName == null || (activityWithName!= null && activityWithName.equals(activity))) { activityToUpdate.put(existingActivity, activity); } else { activitiesToRemove.add(existingActivity); } } else { activitiesToRemove.add(existingActivity); } } targetActivities.removeAll(activitiesToRemove); for (Activity activity : activitiesToRemove) { boolean deleteActivity = activityService.deleteActivity(activity); //remove this activity only if its not used any where if (!deleteActivity) { targetActivities.addAll(activitiesToRemove); throw new StudyCalendarValidationException("Import failed. " + "Activity " + activity.getName() + " with code " + activity.getCode() + " is referenced withing the study. " + "Please remove those references manuall and try to import activity again "); } } Set<Activity> existingActivities = activityToUpdate.keySet(); for (Activity existingActivity : existingActivities) { Activity activity = activityToUpdate.get(existingActivity); existingActivity.updateActivity(activity); } }
private void removeAndUpdateActivities(List<Activity> targetActivities, final List<Activity> activitiesToAddAndRemove) { //delete or update the activity List<Activity> activitiesToRemove = new ArrayList<Activity>(); Map<Activity, Activity> activityToUpdate = new HashMap<Activity,Activity>(); for (Activity existingActivity : targetActivities) { Activity activity = existingActivity.findActivityInCollectionWhichHasSameCode(activitiesToAddAndRemove); if (activity != null) { //for the case when exist A:1 and B:2, and we import A:2 and B:1 - we need to check names Activity activityWithName = existingActivity.findActivityInCollectionWhichHasSameName(activitiesToAddAndRemove); if (activityWithName == null || activityWithName.equals(activity)) { activityToUpdate.put(existingActivity, activity); } else { activitiesToRemove.add(existingActivity); } } else { activitiesToRemove.add(existingActivity); } } targetActivities.removeAll(activitiesToRemove); for (Activity activity : activitiesToRemove) { boolean deleteActivity = activityService.deleteActivity(activity); //remove this activity only if its not used any where if (!deleteActivity) { targetActivities.addAll(activitiesToRemove); throw new StudyCalendarValidationException("Import failed. " + "Activity " + activity.getName() + " with code " + activity.getCode() + " is referenced within the study. " + "Please remove those references manuall and try to import activity again "); } } Set<Activity> existingActivities = activityToUpdate.keySet(); for (Activity existingActivity : existingActivities) { Activity activity = activityToUpdate.get(existingActivity); existingActivity.updateActivity(activity); } }
diff --git a/com/dropoutdesign/ddf/Module.java b/com/dropoutdesign/ddf/Module.java index bd7c8cd..6fd0a8b 100644 --- a/com/dropoutdesign/ddf/Module.java +++ b/com/dropoutdesign/ddf/Module.java @@ -1,96 +1,96 @@ package com.dropoutdesign.ddf; import com.dropoutdesign.ddf.config.*; import com.dropoutdesign.ddf.module.*; import java.util.*; import java.awt.Rectangle; public class Module { public static final int RETRY_INTERVAL_MS = 500; private String address; private Rectangle bounds; private ModuleConnection currentConnection = null; private long lastFailureTime = 0; private boolean badAddress = false; public Module(ModuleConfig config) { address = config.getAddress(); bounds = config.getBounds(); if (bounds.width != 16 || bounds.height != 4) { throw new IllegalArgumentException("Invalid module size: " + bounds.width + "x" + bounds.height); } } public String getAddress() { return address; } public Rectangle getBounds() { return bounds; } public boolean isConnected() { return (currentConnection != null); } public ModuleConnection getConnection() { return currentConnection; } public void connect() throws UnknownConnectionTypeException, ModuleIOException { currentConnection = ModuleConnection.open(address); System.out.println("Connected to module at " + address); /* System.out.println("\tfirmware: " + Integer.toString(currentConnection.firmwareVersion(), 16)); System.out.println("\ti2c: " + Integer.toString(currentConnection.checkI2C(), 16)); */ currentConnection.reset(); // send soft reset command to module } public void disconnect() { currentConnection.close(); currentConnection = null; } public void writeFrame(byte[] frame) throws ModuleIOException { System.out.println("Drawing frame: (" + frame[0] + "," + frame[1] + "," + frame[2] + ") (" + frame[3] + "," + frame[4] + "," + frame[5] + ")"); byte[] cmd = new byte[97]; cmd[0] = 0x10; int curNib = 2; int xm = bounds.x + bounds.width; int ym = bounds.y + bounds.height; for (int y = bounds.y; y < ym; y++) { for (int c = 0; c < 3; c++) { // Component - for (int x = bounds.x; y < xm; x++) { + for (int x = bounds.x; x < xm; x++) { // FIXME: KLUDGE KLUDGE KLUDGE int whichByte = (y * 16 + x) * 3 + c; int nib = ((frame[whichByte] >> 4) & 0xF) ^ 0xF; // flip because 0xF is off if ((curNib % 2) == 0) { cmd[(int)(curNib/2)] = (byte)(nib); } else { cmd[(int)(curNib/2)] |= (byte)(nib << 4); } curNib++; } } } System.out.println("Rendered frame: " + cmd[0] + "," + cmd[1] + "," + cmd[2]); currentConnection.sendCommand(cmd); } }
true
true
public void writeFrame(byte[] frame) throws ModuleIOException { System.out.println("Drawing frame: (" + frame[0] + "," + frame[1] + "," + frame[2] + ") (" + frame[3] + "," + frame[4] + "," + frame[5] + ")"); byte[] cmd = new byte[97]; cmd[0] = 0x10; int curNib = 2; int xm = bounds.x + bounds.width; int ym = bounds.y + bounds.height; for (int y = bounds.y; y < ym; y++) { for (int c = 0; c < 3; c++) { // Component for (int x = bounds.x; y < xm; x++) { // FIXME: KLUDGE KLUDGE KLUDGE int whichByte = (y * 16 + x) * 3 + c; int nib = ((frame[whichByte] >> 4) & 0xF) ^ 0xF; // flip because 0xF is off if ((curNib % 2) == 0) { cmd[(int)(curNib/2)] = (byte)(nib); } else { cmd[(int)(curNib/2)] |= (byte)(nib << 4); } curNib++; } } } System.out.println("Rendered frame: " + cmd[0] + "," + cmd[1] + "," + cmd[2]); currentConnection.sendCommand(cmd); }
public void writeFrame(byte[] frame) throws ModuleIOException { System.out.println("Drawing frame: (" + frame[0] + "," + frame[1] + "," + frame[2] + ") (" + frame[3] + "," + frame[4] + "," + frame[5] + ")"); byte[] cmd = new byte[97]; cmd[0] = 0x10; int curNib = 2; int xm = bounds.x + bounds.width; int ym = bounds.y + bounds.height; for (int y = bounds.y; y < ym; y++) { for (int c = 0; c < 3; c++) { // Component for (int x = bounds.x; x < xm; x++) { // FIXME: KLUDGE KLUDGE KLUDGE int whichByte = (y * 16 + x) * 3 + c; int nib = ((frame[whichByte] >> 4) & 0xF) ^ 0xF; // flip because 0xF is off if ((curNib % 2) == 0) { cmd[(int)(curNib/2)] = (byte)(nib); } else { cmd[(int)(curNib/2)] |= (byte)(nib << 4); } curNib++; } } } System.out.println("Rendered frame: " + cmd[0] + "," + cmd[1] + "," + cmd[2]); currentConnection.sendCommand(cmd); }
diff --git a/src/main/java/com/dianping/wizard/utils/FileUtils.java b/src/main/java/com/dianping/wizard/utils/FileUtils.java index 2080037..a3ae013 100644 --- a/src/main/java/com/dianping/wizard/utils/FileUtils.java +++ b/src/main/java/com/dianping/wizard/utils/FileUtils.java @@ -1,59 +1,59 @@ package com.dianping.wizard.utils; import com.dianping.wizard.exception.WizardExeption; import java.io.*; import java.util.Collection; import java.util.regex.Pattern; /** * @author ltebean */ public class FileUtils { public static String readFileOnClassPath(final String fileName,final String extensions){ - String pattern=".*"+fileName+"."+extensions; + String pattern=".[/\\\\]"+fileName+"."+extensions; try { Collection<String> paths=ResourceList.getResources(Pattern.compile(pattern)); if(paths.size()>1){ throw new WizardExeption("no distinct file: "+pattern); } if(paths.size()==0){ return ""; } String jarPath = JarUtils.jarPath(); if (jarPath == null) { File file = new File(paths.iterator().next()); String result=org.apache.commons.io.FileUtils.readFileToString(file,"UTF-8"); return result; } InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(paths.iterator().next()); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; try { while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); //appende a new line } } catch (IOException e) { e.printStackTrace(); } finally { inputStream.close(); } return builder.toString(); } catch (IOException e) { throw new WizardExeption("reading file error: " + pattern ,e); } } public static String readFileOnClassPath(final String fileName, final String extensions, final String defaultValue){ try { return readFileOnClassPath(fileName,extensions); } catch(Exception e) { return defaultValue; } } }
true
true
public static String readFileOnClassPath(final String fileName,final String extensions){ String pattern=".*"+fileName+"."+extensions; try { Collection<String> paths=ResourceList.getResources(Pattern.compile(pattern)); if(paths.size()>1){ throw new WizardExeption("no distinct file: "+pattern); } if(paths.size()==0){ return ""; } String jarPath = JarUtils.jarPath(); if (jarPath == null) { File file = new File(paths.iterator().next()); String result=org.apache.commons.io.FileUtils.readFileToString(file,"UTF-8"); return result; } InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(paths.iterator().next()); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; try { while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); //appende a new line } } catch (IOException e) { e.printStackTrace(); } finally { inputStream.close(); } return builder.toString(); } catch (IOException e) { throw new WizardExeption("reading file error: " + pattern ,e); } }
public static String readFileOnClassPath(final String fileName,final String extensions){ String pattern=".[/\\\\]"+fileName+"."+extensions; try { Collection<String> paths=ResourceList.getResources(Pattern.compile(pattern)); if(paths.size()>1){ throw new WizardExeption("no distinct file: "+pattern); } if(paths.size()==0){ return ""; } String jarPath = JarUtils.jarPath(); if (jarPath == null) { File file = new File(paths.iterator().next()); String result=org.apache.commons.io.FileUtils.readFileToString(file,"UTF-8"); return result; } InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(paths.iterator().next()); StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; try { while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); //appende a new line } } catch (IOException e) { e.printStackTrace(); } finally { inputStream.close(); } return builder.toString(); } catch (IOException e) { throw new WizardExeption("reading file error: " + pattern ,e); } }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java index 670c3c99c..02cac979b 100755 --- a/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/StatementTransformer.java @@ -1,640 +1,644 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.java.codegen; import static com.sun.tools.javac.code.Flags.FINAL; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.ProducedTypedReference; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.ValueParameter; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AttributeDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CaseClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CaseItem; import com.redhat.ceylon.compiler.typechecker.tree.Tree.CatchClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ElseClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.FinallyClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ForIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.IsCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.KeyValueIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.MatchCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SatisfiesCase; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchCaseList; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SwitchStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Throw; import com.redhat.ceylon.compiler.typechecker.tree.Tree.TryCatchStatement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.TryClause; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueIterator; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Variable; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCBinary; import com.sun.tools.javac.tree.JCTree.JCBlock; import com.sun.tools.javac.tree.JCTree.JCCatch; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Name; /** * This transformer deals with statements only */ public class StatementTransformer extends AbstractTransformer { // Used to hold the name of the variable associated with the fail-block if the innermost for-loop // Is null if we're currently in a while-loop or not in any loop at all private Name currentForFailVariable = null; /** * If false generating plain {@code return;} statements is OK. * If true then generate {@code return null;} statements instead of * expressionless {@code return;}. */ boolean noExpressionlessReturn = false; public static StatementTransformer getInstance(Context context) { StatementTransformer trans = context.get(StatementTransformer.class); if (trans == null) { trans = new StatementTransformer(context); context.put(StatementTransformer.class, trans); } return trans; } private StatementTransformer(Context context) { super(context); } public JCBlock transform(Tree.Block block) { return block == null ? null : at(block).Block(0, transformStmts(block.getStatements())); } @SuppressWarnings("unchecked") List<JCStatement> transformStmts(java.util.List<Tree.Statement> list) { CeylonVisitor v = gen().visitor; final ListBuffer<JCTree> prevDefs = v.defs; final boolean prevInInitializer = v.inInitializer; final ClassDefinitionBuilder prevClassBuilder = v.classBuilder; List<JCStatement> childDefs; try { v.defs = new ListBuffer<JCTree>(); v.inInitializer = false; v.classBuilder = current(); for (Tree.Statement stmt : list) stmt.visit(v); childDefs = (List<JCStatement>)v.getResult().toList(); } finally { v.classBuilder = prevClassBuilder; v.inInitializer = prevInInitializer; v.defs = prevDefs; } return childDefs; } List<JCStatement> transform(Tree.IfStatement stmt) { Tree.Block thenPart = stmt.getIfClause().getBlock(); Tree.Block elsePart = stmt.getElseClause() != null ? stmt.getElseClause().getBlock() : null; return transformCondition(stmt.getIfClause().getCondition(), JCTree.IF, thenPart, elsePart); } List<JCStatement> transform(Tree.WhileStatement stmt) { Name tempForFailVariable = currentForFailVariable; currentForFailVariable = null; Tree.Block thenPart = stmt.getWhileClause().getBlock(); List<JCStatement> res = transformCondition(stmt.getWhileClause().getCondition(), JCTree.WHILELOOP, thenPart, null); currentForFailVariable = tempForFailVariable; return res; } private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); - toType = isdecl.getType().getTypeModel(); + // use the type of the variable, which is more precise than the type we test for + toType = isdecl.getVariable().getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); Naming.SyntheticName tmpVarName = naming.alias(name); final String origVarName = name; Name substVarName = naming.aliasName(name); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, JT_NO_PRIMITIVES | JT_RAW); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = tmpVarName.makeIdent(); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } else if(cond instanceof Tree.IsCondition){ JCExpression castedExpr = at(cond).TypeCast(rawToTypeExpr, tmpVarExpr); if(canUnbox(toType)) tmpVarExpr = unboxType(castedExpr, toType); else tmpVarExpr = castedExpr; tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = naming.addVariableSubst(origVarName, substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution naming.removeVariableSubst(origVarName, prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression firstTimeTestExpr = make().Assign(tmpVarName.makeIdent(), expr); // Test on the tmpVar in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, firstTimeTestExpr, makeNull()); } else if (cond instanceof Tree.NonemptyCondition){ test = makeNonEmptyTest(firstTimeTestExpr, tmpVarName); } else { // is - test = makeTypeTest(firstTimeTestExpr, tmpVarName, toType); + test = makeTypeTest(firstTimeTestExpr, tmpVarName, + // only test the types we're testing for, not the type of + // the variable (which can be more precise) + ((Tree.IsCondition)cond).getType().getTypeModel()); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } } private ProducedType actualType(Tree.TypedDeclaration decl) { return decl.getType().getTypeModel(); } List<JCStatement> transform(Tree.ForStatement stmt) { Name tempForFailVariable = currentForFailVariable; at(stmt); List<JCStatement> outer = List.<JCStatement> nil(); if (stmt.getExits() && stmt.getElseClause() != null) { // boolean $doforelse$X = true; JCVariableDecl failtest_decl = make().VarDef(make().Modifiers(0), naming.aliasName("doforelse"), make().TypeIdent(TypeTags.BOOLEAN), make().Literal(TypeTags.BOOLEAN, 1)); outer = outer.append(failtest_decl); currentForFailVariable = failtest_decl.getName(); } else { currentForFailVariable = null; } // java.lang.Object $elem$X; Naming.SyntheticName elem_name = naming.alias("elem"); JCVariableDecl elem_decl = make().VarDef(make().Modifiers(0), elem_name.asName(), make().Type(syms().objectType), null); outer = outer.append(elem_decl); ForIterator iterDecl = stmt.getForClause().getForIterator(); Variable variable; Variable variable2; if (iterDecl instanceof ValueIterator) { variable = ((ValueIterator) iterDecl).getVariable(); variable2 = null; } else if (iterDecl instanceof KeyValueIterator) { variable = ((KeyValueIterator) iterDecl).getKeyVariable(); variable2 = ((KeyValueIterator) iterDecl).getValueVariable(); } else { throw new RuntimeException("Unknown ForIterator"); } String loop_var_name = variable.getIdentifier().getText(); Expression specifierExpression = iterDecl.getSpecifierExpression().getExpression(); ProducedType sequence_element_type; if(variable2 == null) sequence_element_type = variable.getType().getTypeModel(); else{ // Entry<V1,V2> sequence_element_type = typeFact().getEntryType(variable.getType().getTypeModel(), variable2.getType().getTypeModel()); } ProducedType iter_type = typeFact().getIteratorType(sequence_element_type); JCExpression iter_type_expr = makeJavaType(iter_type, CeylonTransformer.JT_TYPE_ARGUMENT); JCExpression cast_elem = at(stmt).TypeCast(makeJavaType(sequence_element_type, CeylonTransformer.JT_NO_PRIMITIVES), elem_name.makeIdent()); List<JCAnnotation> annots = makeJavaTypeAnnotations(variable.getDeclarationModel()); // ceylon.language.Iterator<T> $V$iter$X = ITERABLE.getIterator(); // We don't need to unerase here as anything remotely a sequence will be erased to Iterable, which has getIterator() JCExpression containment = expressionGen().transformExpression(specifierExpression, BoxingStrategy.BOXED, null); JCExpression getIter = at(stmt).Apply(null, makeSelect(containment, "getIterator"), List.<JCExpression> nil()); getIter = gen().expressionGen().applyErasureAndBoxing(getIter, specifierExpression.getTypeModel(), true, BoxingStrategy.BOXED, iter_type); JCVariableDecl iter_decl = at(stmt).VarDef(make().Modifiers(0), naming.aliasName(loop_var_name + "$iter"), iter_type_expr, getIter); String iter_id = iter_decl.getName().toString(); // final U n = $elem$X; // or // final U n = $elem$X.getKey(); JCExpression loop_var_init; ProducedType loop_var_type; if (variable2 == null) { loop_var_type = sequence_element_type; loop_var_init = cast_elem; } else { loop_var_type = actualType(variable); loop_var_init = at(stmt).Apply(null, makeSelect(cast_elem, Naming.getGetterName("key")), List.<JCExpression> nil()); } JCVariableDecl item_decl = at(stmt).VarDef(make().Modifiers(FINAL, annots), names().fromString(loop_var_name), makeJavaType(loop_var_type), boxUnboxIfNecessary(loop_var_init, true, loop_var_type, CodegenUtil.getBoxingStrategy(variable.getDeclarationModel()))); List<JCStatement> for_loop = List.<JCStatement> of(item_decl); if (variable2 != null) { // final V n = $elem$X.getElement(); ProducedType item_type2 = actualType(variable2); JCExpression item_type_expr2 = makeJavaType(item_type2); JCExpression loop_var_init2 = at(stmt).Apply(null, makeSelect(cast_elem, Naming.getGetterName("item")), List.<JCExpression> nil()); String loop_var_name2 = variable2.getIdentifier().getText(); JCVariableDecl item_decl2 = at(stmt).VarDef(make().Modifiers(FINAL, annots), names().fromString(loop_var_name2), item_type_expr2, boxUnboxIfNecessary(loop_var_init2, true, item_type2, CodegenUtil.getBoxingStrategy(variable2.getDeclarationModel()))); for_loop = for_loop.append(item_decl2); } // The user-supplied contents of the loop for_loop = for_loop.appendList(transformStmts(stmt.getForClause().getBlock().getStatements())); // $elem$X = $V$iter$X.next() JCExpression iter_elem = make().Apply(null, makeSelect(iter_id, "next"), List.<JCExpression> nil()); JCExpression elem_assign = make().Assign(elem_name.makeIdent(), iter_elem); // !(($elem$X = $V$iter$X.next()) instanceof Finished) JCExpression instof = make().TypeTest(elem_assign, make().Type(syms().ceylonFinishedType)); JCExpression cond = make().Unary(JCTree.NOT, instof); // No step necessary List<JCExpressionStatement> step = List.<JCExpressionStatement>nil(); // for (.ceylon.language.Iterator<T> $V$iter$X = ITERABLE.iterator(); !(($elem$X = $V$iter$X.next()) instanceof Finished); ) { outer = outer.append(at(stmt).ForLoop( List.<JCStatement>of(iter_decl), cond, step, at(stmt).Block(0, for_loop))); if (stmt.getElseClause() != null) { // The user-supplied contents of fail block List<JCStatement> failblock = transformStmts(stmt.getElseClause().getBlock().getStatements()); if (stmt.getExits()) { // if ($doforelse$X) ... JCIdent failtest_id = at(stmt).Ident(currentForFailVariable); outer = outer.append(at(stmt).If(failtest_id, at(stmt).Block(0, failblock), null)); } else { outer = outer.appendList(failblock); } } currentForFailVariable = tempForFailVariable; return outer; } // FIXME There is a similar implementation in ClassGen! public List<JCStatement> transform(AttributeDeclaration decl) { // If the attribute is really from a parameter then don't generate a local variable Parameter parameter = CodegenUtil.findParamForDecl(decl); if (parameter == null) { Name atrrName = names().fromString(decl.getIdentifier().getText()); ProducedType t = actualType(decl); JCExpression initialValue = null; if (decl.getSpecifierOrInitializerExpression() != null) { initialValue = expressionGen().transformExpression(decl.getSpecifierOrInitializerExpression().getExpression(), CodegenUtil.getBoxingStrategy(decl.getDeclarationModel()), decl.getDeclarationModel().getType()); } JCExpression type = makeJavaType(t); List<JCAnnotation> annots = makeJavaTypeAnnotations(decl.getDeclarationModel()); int modifiers = transformLocalFieldDeclFlags(decl); return List.<JCStatement> of(at(decl).VarDef(at(decl).Modifiers(modifiers, annots), atrrName, type, initialValue)); } else { return List.<JCStatement> nil(); } } List<JCStatement> transform(Tree.Break stmt) { // break; JCStatement brk = at(stmt).Break(null); if (currentForFailVariable != null) { JCIdent failtest_id = at(stmt).Ident(currentForFailVariable); List<JCStatement> list = List.<JCStatement> of(at(stmt).Exec(at(stmt).Assign(failtest_id, make().Literal(TypeTags.BOOLEAN, 0)))); list = list.append(brk); return list; } else { return List.<JCStatement> of(brk); } } JCStatement transform(Tree.Continue stmt) { // continue; return at(stmt).Continue(null); } JCStatement transform(Tree.Return ret) { Tree.Expression expr = ret.getExpression(); JCExpression returnExpr = null; at(ret); if (expr != null) { boolean prevNoExpressionlessReturn = noExpressionlessReturn; try { noExpressionlessReturn = false; // we can cast to TypedDeclaration here because return with expressions are only in Method or Value TypedDeclaration declaration = (TypedDeclaration)ret.getDeclaration(); // make sure we use the best declaration for boxing and type ProducedTypedReference typedRef = getTypedReference(declaration); ProducedTypedReference nonWideningTypedRef = nonWideningTypeDecl(typedRef); ProducedType nonWideningType = nonWideningType(typedRef, nonWideningTypedRef); returnExpr = expressionGen().transformExpression(expr.getTerm(), CodegenUtil.getBoxingStrategy(nonWideningTypedRef.getDeclaration()), nonWideningType); } finally { noExpressionlessReturn = prevNoExpressionlessReturn; } } else if (noExpressionlessReturn) { returnExpr = makeNull(); } return at(ret).Return(returnExpr); } public JCStatement transform(Throw t) { at(t); Expression expr = t.getExpression(); final JCExpression exception; if (expr == null) {// bare "throw;" stmt exception = make().NewClass(null, null, makeIdent(syms().ceylonExceptionType), List.<JCExpression>of(makeNull(), makeNull()), null); } else { // we must unerase the exception to Throwable ProducedType exceptionType = expr.getTypeModel().getSupertype(t.getUnit().getExceptionDeclaration()); exception = gen().expressionGen().transformExpression(expr, BoxingStrategy.UNBOXED, exceptionType); } return make().Throw(exception); } public JCStatement transform(TryCatchStatement t) { // TODO Support resources -- try(Usage u = ...) { ... TryClause tryClause = t.getTryClause(); at(tryClause); JCBlock tryBlock = transform(tryClause.getBlock()); final ListBuffer<JCCatch> catches = ListBuffer.<JCCatch>lb(); for (CatchClause catchClause : t.getCatchClauses()) { at(catchClause); java.util.List<ProducedType> exceptionTypes; Variable variable = catchClause.getCatchVariable().getVariable(); ProducedType exceptionType = variable.getDeclarationModel().getType(); if (typeFact().isUnion(exceptionType)) { exceptionTypes = exceptionType.getDeclaration().getCaseTypes(); } else { exceptionTypes = List.<ProducedType>of(exceptionType); } for (ProducedType type : exceptionTypes) { // catch blocks for each exception in the union JCVariableDecl param = make().VarDef(make().Modifiers(Flags.FINAL), names().fromString(variable.getIdentifier().getText()), makeJavaType(type, JT_CATCH), null); catches.add(make().Catch(param, transform(catchClause.getBlock()))); } } final JCBlock finallyBlock; FinallyClause finallyClause = t.getFinallyClause(); if (finallyClause != null) { at(finallyClause); finallyBlock = transform(finallyClause.getBlock()); } else { finallyBlock = null; } return at(t).Try(tryBlock, catches.toList(), finallyBlock); } private int transformLocalFieldDeclFlags(Tree.AttributeDeclaration cdecl) { int result = 0; result |= cdecl.getDeclarationModel().isVariable() ? 0 : FINAL; return result; } /** * Transforms a Ceylon switch to a Java {@code if/else if} chain. * @param stmt The Ceylon switch * @return The Java tree */ JCStatement transform(SwitchStatement stmt) { SwitchClause switchClause = stmt.getSwitchClause(); JCExpression selectorExpr = expressionGen().transformExpression(switchClause.getExpression(), BoxingStrategy.BOXED, switchClause.getExpression().getTypeModel()); Naming.SyntheticName selectorAlias = naming.alias("sel"); JCVariableDecl selector = makeVar(selectorAlias, make().Type(syms().objectType), selectorExpr); SwitchCaseList caseList = stmt.getSwitchCaseList(); JCStatement last = null; ElseClause elseClause = caseList.getElseClause(); if (elseClause != null) { last = transform(elseClause.getBlock()); } else { // To avoid possible javac warnings about uninitialized vars we // need to have an 'else' clause, even if the ceylon code doesn't // require one. // This exception could be thrown for example if an enumerated // type is recompiled after having a subclass added, but the // switch is not recompiled. last = make().Throw( make().NewClass(null, List.<JCExpression>nil(), makeIdent(syms().ceylonEnumeratedTypeErrorType), List.<JCExpression>of(make().Literal( "Supposedly exhaustive switch was not exhaustive")), null)); } java.util.List<CaseClause> caseClauses = caseList.getCaseClauses(); for (int ii = caseClauses.size() - 1; ii >= 0; ii--) {// reverse order CaseClause caseClause = caseClauses.get(ii); CaseItem caseItem = caseClause.getCaseItem(); if (caseItem instanceof IsCase) { last = transformCaseIs(selectorAlias, caseClause, (IsCase)caseItem, last); } else if (caseItem instanceof SatisfiesCase) { // TODO Support for 'case (satisfies ...)' is not implemented yet return make().Exec(makeErroneous(caseItem, "switch/satisfies not implemented yet")); } else if (caseItem instanceof MatchCase) { last = transformCaseMatch(selectorAlias, caseClause, (MatchCase)caseItem, last); } else { return make().Exec(makeErroneous(caseItem, "unknown switch case clause: "+caseItem)); } } return at(stmt).Block(0, List.of(selector, last)); } private JCStatement transformCaseMatch(Naming.SyntheticName selectorAlias, CaseClause caseClause, MatchCase matchCase, JCStatement last) { at(matchCase); JCExpression tests = null; java.util.List<Tree.Expression> expressions = matchCase.getExpressionList().getExpressions(); for(Tree.Expression expr : expressions){ JCExpression transformedExpression = expressionGen().transformExpression(expr); JCBinary test = make().Binary(JCTree.EQ, selectorAlias.makeIdent(), transformedExpression); if(tests == null) tests = test; else tests = make().Binary(JCTree.OR, tests, test); } return at(caseClause).If(tests, transform(caseClause.getBlock()), last); } /** * Transform a "case(is ...)" * @param selectorAlias * @param caseClause * @param isCase * @param last * @return */ private JCStatement transformCaseIs(Naming.SyntheticName selectorAlias, CaseClause caseClause, IsCase isCase, JCStatement last) { at(isCase); ProducedType type = isCase.getType().getTypeModel(); JCExpression cond = makeTypeTest(null, selectorAlias, type); JCExpression toTypeExpr = makeJavaType(type); String name = isCase.getVariable().getIdentifier().getText(); Naming.SyntheticName tmpVarName = selectorAlias; Name substVarName = naming.aliasName(name); // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(type, JT_NO_PRIMITIVES | JT_RAW); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = tmpVarName.makeIdent(); tmpVarExpr = unboxType(at(isCase).TypeCast(rawToTypeExpr, tmpVarExpr), type); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(isCase).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = naming.addVariableSubst(name, substVarName.toString()); JCBlock block = transform(caseClause.getBlock()); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(block.getStatements()); block = at(isCase).Block(0, stats); // Deactivate the above variable substitution naming.removeVariableSubst(name, prevSubst); last = make().If(cond, block, last); return last; } }
false
true
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); toType = isdecl.getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); Naming.SyntheticName tmpVarName = naming.alias(name); final String origVarName = name; Name substVarName = naming.aliasName(name); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, JT_NO_PRIMITIVES | JT_RAW); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = tmpVarName.makeIdent(); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } else if(cond instanceof Tree.IsCondition){ JCExpression castedExpr = at(cond).TypeCast(rawToTypeExpr, tmpVarExpr); if(canUnbox(toType)) tmpVarExpr = unboxType(castedExpr, toType); else tmpVarExpr = castedExpr; tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = naming.addVariableSubst(origVarName, substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution naming.removeVariableSubst(origVarName, prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression firstTimeTestExpr = make().Assign(tmpVarName.makeIdent(), expr); // Test on the tmpVar in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, firstTimeTestExpr, makeNull()); } else if (cond instanceof Tree.NonemptyCondition){ test = makeNonEmptyTest(firstTimeTestExpr, tmpVarName); } else { // is test = makeTypeTest(firstTimeTestExpr, tmpVarName, toType); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
private List<JCStatement> transformCondition(Tree.Condition cond, int tag, Tree.Block thenPart, Tree.Block elsePart) { JCExpression test; JCVariableDecl decl = null; JCBlock thenBlock = null; JCBlock elseBlock = null; if ((cond instanceof Tree.IsCondition) || (cond instanceof Tree.NonemptyCondition) || (cond instanceof Tree.ExistsCondition)) { String name; ProducedType toType; Expression specifierExpr; if (cond instanceof Tree.IsCondition) { Tree.IsCondition isdecl = (Tree.IsCondition) cond; name = isdecl.getVariable().getIdentifier().getText(); // use the type of the variable, which is more precise than the type we test for toType = isdecl.getVariable().getType().getTypeModel(); specifierExpr = isdecl.getVariable().getSpecifierExpression().getExpression(); } else if (cond instanceof Tree.NonemptyCondition) { Tree.NonemptyCondition nonempty = (Tree.NonemptyCondition) cond; name = nonempty.getVariable().getIdentifier().getText(); toType = nonempty.getVariable().getType().getTypeModel(); specifierExpr = nonempty.getVariable().getSpecifierExpression().getExpression(); } else { Tree.ExistsCondition exists = (Tree.ExistsCondition) cond; name = exists.getVariable().getIdentifier().getText(); toType = simplifyType(exists.getVariable().getType().getTypeModel()); specifierExpr = exists.getVariable().getSpecifierExpression().getExpression(); } // no need to cast for erasure here JCExpression expr = expressionGen().transformExpression(specifierExpr); // IsCondition with Nothing as ProducedType transformed to " == null" at(cond); if (cond instanceof Tree.IsCondition && isNothing(toType)) { test = make().Binary(JCTree.EQ, expr, makeNull()); } else { JCExpression toTypeExpr = makeJavaType(toType); Naming.SyntheticName tmpVarName = naming.alias(name); final String origVarName = name; Name substVarName = naming.aliasName(name); ProducedType tmpVarType = specifierExpr.getTypeModel(); JCExpression tmpVarTypeExpr; // Want raw type for instanceof since it can't be used with generic types JCExpression rawToTypeExpr = makeJavaType(toType, JT_NO_PRIMITIVES | JT_RAW); // Substitute variable with the correct type to use in the rest of the code block JCExpression tmpVarExpr = tmpVarName.makeIdent(); if (cond instanceof Tree.ExistsCondition) { tmpVarExpr = unboxType(tmpVarExpr, toType); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } else if(cond instanceof Tree.IsCondition){ JCExpression castedExpr = at(cond).TypeCast(rawToTypeExpr, tmpVarExpr); if(canUnbox(toType)) tmpVarExpr = unboxType(castedExpr, toType); else tmpVarExpr = castedExpr; tmpVarTypeExpr = make().Type(syms().objectType); } else { tmpVarExpr = at(cond).TypeCast(toTypeExpr, tmpVarExpr); tmpVarTypeExpr = makeJavaType(tmpVarType, JT_NO_PRIMITIVES); } // Temporary variable holding the result of the expression/variable to test decl = makeVar(tmpVarName, tmpVarTypeExpr, null); // The variable holding the result for the code inside the code block JCVariableDecl decl2 = at(cond).VarDef(make().Modifiers(FINAL), substVarName, toTypeExpr, tmpVarExpr); // Prepare for variable substitution in the following code block String prevSubst = naming.addVariableSubst(origVarName, substVarName.toString()); thenBlock = transform(thenPart); List<JCStatement> stats = List.<JCStatement> of(decl2); stats = stats.appendList(thenBlock.getStatements()); thenBlock = at(cond).Block(0, stats); // Deactivate the above variable substitution naming.removeVariableSubst(origVarName, prevSubst); at(cond); // Assign the expression to test to the temporary variable JCExpression firstTimeTestExpr = make().Assign(tmpVarName.makeIdent(), expr); // Test on the tmpVar in the following condition if (cond instanceof Tree.ExistsCondition) { test = make().Binary(JCTree.NE, firstTimeTestExpr, makeNull()); } else if (cond instanceof Tree.NonemptyCondition){ test = makeNonEmptyTest(firstTimeTestExpr, tmpVarName); } else { // is test = makeTypeTest(firstTimeTestExpr, tmpVarName, // only test the types we're testing for, not the type of // the variable (which can be more precise) ((Tree.IsCondition)cond).getType().getTypeModel()); } } } else if (cond instanceof Tree.BooleanCondition) { Tree.BooleanCondition booleanCondition = (Tree.BooleanCondition) cond; // booleans can't be erased test = expressionGen().transformExpression(booleanCondition.getExpression(), BoxingStrategy.UNBOXED, null); } else { throw new RuntimeException("Not implemented: " + cond.getNodeType()); } at(cond); // Convert the code blocks (if not already done so above) if (thenPart != null && thenBlock == null) { thenBlock = transform(thenPart); } if (elsePart != null && elseBlock == null) { elseBlock = transform(elsePart); } JCStatement cond1; switch (tag) { case JCTree.IF: cond1 = make().If(test, thenBlock, elseBlock); break; case JCTree.WHILELOOP: cond1 = make().WhileLoop(makeLetExpr(make().TypeIdent(TypeTags.BOOLEAN), test), thenBlock); break; default: throw new RuntimeException(); } if (decl != null) { return List.<JCStatement> of(decl, cond1); } else { return List.<JCStatement> of(cond1); } }
diff --git a/src/main/java/de/ailis/jasdoc/types/TypeFactory.java b/src/main/java/de/ailis/jasdoc/types/TypeFactory.java index 0bfd3ff..234101f 100644 --- a/src/main/java/de/ailis/jasdoc/types/TypeFactory.java +++ b/src/main/java/de/ailis/jasdoc/types/TypeFactory.java @@ -1,108 +1,125 @@ /* * Copyright (C) 2012 Klaus Reimer <[email protected]> * See LICENSE.md for licensing information. */ package de.ailis.jasdoc.types; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.ailis.jasdoc.util.JsTypeUtils; /** * Factory for JavaScript types. * * @author Klaus Reimer ([email protected]) */ public class TypeFactory { /** Cached types. */ private final Map<String, AbstractType> cache = new HashMap<String, AbstractType>(); /** * Performs an initial parsing of a type expression. This means top-level * curly braces are removed before starting the real type parsing. This * allows to support type expressions like "number" and "{number}". * * @param expression * The type expression. * @return The concrete type. */ public final AbstractType parseInitial(final String expression) { if (expression.startsWith("{") && expression.endsWith("}")) return valueOf(expression.substring(1, expression.length() - 1)); else return valueOf(expression); } /** * Converts the specified type expression into a concrete type. * * @param expression * The type expression. * @return The concrete type. */ public final AbstractType valueOf(final String expression) { AbstractType type = this.cache.get(expression); if (type != null) return type; type = createType(expression); this.cache.put(expression, type); return type; } /** * Creates the type for the specified expression. * * @param expression * The type expression. * @return The created type. */ private AbstractType createType(final String expression) { final String[] parts = JsTypeUtils.split(expression, '|'); if (parts.length > 1) { final List<AbstractType> types = new ArrayList<AbstractType>(); for (final String part: parts) types.add(valueOf(part)); return new UnionType(types); } if ("*".equals(expression)) return new AnyType(); if ("string".equals(expression)) return new StringType(); if ("number".equals(expression)) return new NumberType(); if ("boolean".equals(expression)) return new BooleanType(); if (expression.startsWith("...")) return new VarArgType(valueOf(expression.substring(3))); if (expression.endsWith("=")) return new OptionalType(valueOf(expression.substring(0, expression.length() - 1))); if (expression.startsWith("!")) return new NonNullType(valueOf(expression.substring(1))); if (expression.startsWith("?")) return new NullableType(valueOf(expression.substring(1))); if (expression.startsWith("Array.<")) return new ArrayType(valueOf(expression.substring( 7, JsTypeUtils.findEnd(expression, 6)))); + if (expression.startsWith("Array<")) + return new ArrayType(valueOf(expression.substring( + 6, JsTypeUtils.findEnd(expression, 5)))); if (expression.startsWith("Object.<")) { final int end = JsTypeUtils.findEnd(expression, 7); final String[] args = JsTypeUtils.split( expression.substring(8, end), ','); if (args.length == 2) return new MapType(valueOf(args[0]), valueOf(args[1])); } + if (expression.startsWith("Object<")) + { + final int end = JsTypeUtils.findEnd(expression, 6); + final String[] args = JsTypeUtils.split( + expression.substring(7, end), ','); + if (args.length == 2) + return new MapType(valueOf(args[0]), valueOf(args[1])); + } + if (expression.contains(".<")) { + return new ClassType(expression.substring(0, expression.indexOf(".<"))); + } + if (expression.contains("<")) { + return new ClassType(expression.substring(0, expression.indexOf('<'))); + } return new ClassType(expression); } }
false
true
private AbstractType createType(final String expression) { final String[] parts = JsTypeUtils.split(expression, '|'); if (parts.length > 1) { final List<AbstractType> types = new ArrayList<AbstractType>(); for (final String part: parts) types.add(valueOf(part)); return new UnionType(types); } if ("*".equals(expression)) return new AnyType(); if ("string".equals(expression)) return new StringType(); if ("number".equals(expression)) return new NumberType(); if ("boolean".equals(expression)) return new BooleanType(); if (expression.startsWith("...")) return new VarArgType(valueOf(expression.substring(3))); if (expression.endsWith("=")) return new OptionalType(valueOf(expression.substring(0, expression.length() - 1))); if (expression.startsWith("!")) return new NonNullType(valueOf(expression.substring(1))); if (expression.startsWith("?")) return new NullableType(valueOf(expression.substring(1))); if (expression.startsWith("Array.<")) return new ArrayType(valueOf(expression.substring( 7, JsTypeUtils.findEnd(expression, 6)))); if (expression.startsWith("Object.<")) { final int end = JsTypeUtils.findEnd(expression, 7); final String[] args = JsTypeUtils.split( expression.substring(8, end), ','); if (args.length == 2) return new MapType(valueOf(args[0]), valueOf(args[1])); } return new ClassType(expression); }
private AbstractType createType(final String expression) { final String[] parts = JsTypeUtils.split(expression, '|'); if (parts.length > 1) { final List<AbstractType> types = new ArrayList<AbstractType>(); for (final String part: parts) types.add(valueOf(part)); return new UnionType(types); } if ("*".equals(expression)) return new AnyType(); if ("string".equals(expression)) return new StringType(); if ("number".equals(expression)) return new NumberType(); if ("boolean".equals(expression)) return new BooleanType(); if (expression.startsWith("...")) return new VarArgType(valueOf(expression.substring(3))); if (expression.endsWith("=")) return new OptionalType(valueOf(expression.substring(0, expression.length() - 1))); if (expression.startsWith("!")) return new NonNullType(valueOf(expression.substring(1))); if (expression.startsWith("?")) return new NullableType(valueOf(expression.substring(1))); if (expression.startsWith("Array.<")) return new ArrayType(valueOf(expression.substring( 7, JsTypeUtils.findEnd(expression, 6)))); if (expression.startsWith("Array<")) return new ArrayType(valueOf(expression.substring( 6, JsTypeUtils.findEnd(expression, 5)))); if (expression.startsWith("Object.<")) { final int end = JsTypeUtils.findEnd(expression, 7); final String[] args = JsTypeUtils.split( expression.substring(8, end), ','); if (args.length == 2) return new MapType(valueOf(args[0]), valueOf(args[1])); } if (expression.startsWith("Object<")) { final int end = JsTypeUtils.findEnd(expression, 6); final String[] args = JsTypeUtils.split( expression.substring(7, end), ','); if (args.length == 2) return new MapType(valueOf(args[0]), valueOf(args[1])); } if (expression.contains(".<")) { return new ClassType(expression.substring(0, expression.indexOf(".<"))); } if (expression.contains("<")) { return new ClassType(expression.substring(0, expression.indexOf('<'))); } return new ClassType(expression); }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java index a570a7336..e07d32fd6 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/AnnotateView.java @@ -1,382 +1,382 @@ /******************************************************************************* * Copyright (c) 2000, 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.ui; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.*; import org.eclipse.jface.viewers.*; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.*; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.team.internal.ui.history.GenericHistoryView; import org.eclipse.team.ui.history.IHistoryPage; import org.eclipse.team.ui.history.IHistoryView; import org.eclipse.ui.*; import org.eclipse.ui.internal.ide.IDEWorkbenchPlugin; import org.eclipse.ui.internal.registry.EditorDescriptor; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; /** * A view showing the results of the CVS Annotate Command. A linked * combination of a View of annotations, a source editor and the * Resource History View */ public class AnnotateView extends ViewPart implements ISelectionChangedListener { ITextEditor editor; GenericHistoryView historyView; IWorkbenchPage page; ListViewer viewer; IDocument document; Collection cvsAnnotateBlocks; ICVSResource cvsResource; InputStream contents; IStructuredSelection previousListSelection; ITextSelection previousTextSelection; boolean lastSelectionWasText = false; public static final String VIEW_ID = "org.eclipse.team.ccvs.ui.AnnotateView"; //$NON-NLS-1$ private Composite top; private IPartListener partListener = new IPartListener() { public void partActivated(IWorkbenchPart part) { } public void partBroughtToTop(IWorkbenchPart part) { } public void partClosed(IWorkbenchPart part) { if (editor != null && part == editor) { disconnect(); } } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; public AnnotateView() { super(); } public void createPartControl(Composite parent) { this.top = parent; // Create default contents Label label = new Label(top, SWT.WRAP); label.setText(CVSUIMessages.CVSAnnotateView_viewInstructions); top.layout(); PlatformUI.getWorkbench().getHelpSystem().setHelp(label, IHelpContextIds.ANNOTATE_VIEW); } /** * Show the annotation view. * @param cvsResource * @param cvsAnnotateBlocks * @param contents * @throws PartInitException, CVSException */ public void showAnnotations(ICVSResource cvsResource, Collection cvsAnnotateBlocks, InputStream contents) throws PartInitException, CVSException { showAnnotations(cvsResource, cvsAnnotateBlocks, contents, true); } /** * Show the annotation view. * @param cvsResource * @param cvsAnnotateBlocks * @param contents * @param useHistoryView * @throws PartInitException, CVSException */ public void showAnnotations(ICVSResource cvsResource, Collection cvsAnnotateBlocks, InputStream contents, boolean useHistoryView) throws PartInitException, CVSException { // Disconnect from old annotation editor disconnect(); // Remove old viewer Control[] oldChildren = top.getChildren(); if (oldChildren != null) { for (int i = 0; i < oldChildren.length; i++) { oldChildren[i].dispose(); } } viewer = new ListViewer(top, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL); viewer.setContentProvider(new ArrayContentProvider()); viewer.setLabelProvider(new LabelProvider()); viewer.addSelectionChangedListener(this); viewer.getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); PlatformUI.getWorkbench().getHelpSystem().setHelp(viewer.getControl(), IHelpContextIds.ANNOTATE_VIEW); top.layout(); this.cvsResource = cvsResource; this.contents = contents; this.cvsAnnotateBlocks = cvsAnnotateBlocks; page = CVSUIPlugin.getActivePage(); viewer.setInput(cvsAnnotateBlocks); editor = (ITextEditor) openEditor(); IDocumentProvider provider = editor.getDocumentProvider(); document = provider.getDocument(editor.getEditorInput()); setPartName(NLS.bind(CVSUIMessages.CVSAnnotateView_showFileAnnotation, (new Object[] {cvsResource.getName()}))); IResource localResource = cvsResource.getIResource(); if (localResource != null) { setTitleToolTip(localResource.getFullPath().toString()); } else { setTitleToolTip(cvsResource.getName()); } if (!useHistoryView) { return; } // Get hook to the HistoryView historyView = (GenericHistoryView) page.showView(IHistoryView.VIEW_ID); historyView.showHistoryFor((ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(cvsResource)); } protected void disconnect() { if(editor != null) { if (editor.getSelectionProvider() instanceof IPostSelectionProvider) { ((IPostSelectionProvider) editor.getSelectionProvider()).removePostSelectionChangedListener(this); } editor.getSite().getPage().removePartListener(partListener); editor = null; document = null; } } /** * Makes the view visible in the active perspective. If there * isn't a view registered <code>null</code> is returned. * Otherwise the opened view part is returned. */ public static AnnotateView openInActivePerspective() throws PartInitException { return (AnnotateView) CVSUIPlugin.getActivePage().showView(VIEW_ID); } /** * Selection changed in either the Annotate List View or the * Source editor. */ public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection() instanceof IStructuredSelection) { listSelectionChanged((IStructuredSelection) event.getSelection()); } else if (event.getSelection() instanceof ITextSelection) { textSelectionChanged((ITextSelection) event.getSelection()); } } /* (non-Javadoc) * @see org.eclipse.ui.IWorkbenchPart#dispose() */ public void dispose() { disconnect(); } /** * A selection event in the Annotate Source Editor * @param event */ private void textSelectionChanged(ITextSelection selection) { // Track where the last selection event came from to avoid // a selection event loop. lastSelectionWasText = true; // Locate the annotate block containing the selected line number. CVSAnnotateBlock match = null; for (Iterator iterator = cvsAnnotateBlocks.iterator(); iterator.hasNext();) { CVSAnnotateBlock block = (CVSAnnotateBlock) iterator.next(); if (block.contains(selection.getStartLine())) { match = block; break; } } // Select the annotate block in the List View. if (match == null) { return; } StructuredSelection listSelection = new StructuredSelection(match); viewer.setSelection(listSelection, true); } /** * A selection event in the Annotate List View * @param selection */ private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); if (textSelection == null) return; - if (!(selection instanceof CVSAnnotateBlock)) + if (selection.size() == 1 && !(selection.getFirstElement() instanceof CVSAnnotateBlock)) return; CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); if (listSelection == null) return; /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { IHistoryPage historyPage = historyView.getHistoryPage(); if (historyPage instanceof CVSHistoryPage){ ((CVSHistoryPage) historyPage).selectRevision(listSelection.getRevision()); lastSelectionWasText = false; } } } /** * Try and open the correct registered editor type for the file. * @throws CVSException, PartInitException */ private IEditorPart openEditor() throws CVSException, PartInitException { ICVSRemoteFile file = (ICVSRemoteFile) CVSWorkspaceRoot.getRemoteResourceFor(cvsResource); // Determine if the registered editor is an ITextEditor. // There is currently no support from UI to determine this information. This // problem has been logged in: https://bugs.eclipse.org/bugs/show_bug.cgi?id=47362 // For now, use internal classes. String id = getEditorId(file); ITextEditor editor = getEditor(id, file); // Hook Editor post selection listener. if (editor.getSelectionProvider() instanceof IPostSelectionProvider) { ((IPostSelectionProvider) editor.getSelectionProvider()).addPostSelectionChangedListener(this); } editor.getSite().getPage().addPartListener(partListener); return editor; } private ITextEditor getEditor(String id, ICVSRemoteFile file) throws PartInitException { // Either reuse an existing editor or open a new editor of the correct type. if (editor != null && editor instanceof IReusableEditor && page.isPartVisible(editor) && editor.getSite().getId().equals(id)) { // We can reuse the editor ((IReusableEditor) editor).setInput(new RemoteAnnotationEditorInput(file, contents)); return editor; } else { // We can not reuse the editor so close the existing one and open a new one. if (editor != null) { page.closeEditor(editor, false); editor = null; } IEditorPart part = page.openEditor(new RemoteAnnotationEditorInput(file, contents), id); if (part instanceof ITextEditor) { return (ITextEditor)part; } else { // We asked for a text editor but didn't get one // so open a vanilla text editor page.closeEditor(part, false); part = page.openEditor(new RemoteAnnotationEditorInput(file, contents), IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID); if (part instanceof ITextEditor) { return (ITextEditor)part; } else { // There is something really wrong so just bail throw new PartInitException(CVSUIMessages.AnnotateView_0); } } } } private String getEditorId(ICVSRemoteFile file) { String id; IEditorRegistry registry = CVSUIPlugin.getPlugin().getWorkbench().getEditorRegistry(); IEditorDescriptor descriptor = registry.getDefaultEditor(file.getName()); if (descriptor == null || !(descriptor instanceof EditorDescriptor) || !(((EditorDescriptor)descriptor).isInternal())) { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; } else { try { Object obj = IDEWorkbenchPlugin.createExtension(((EditorDescriptor) descriptor).getConfigurationElement(), "class"); //$NON-NLS-1$ if (obj instanceof ITextEditor) { id = descriptor.getId(); } else { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; } } catch (CoreException e) { id = IDEWorkbenchPlugin.DEFAULT_TEXT_EDITOR_ID; } } return id; } // This method implemented to be an ISelectionChangeListener but we // don't really care when the List or Editor get focus. public void setFocus() { return; } }
true
true
private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); if (textSelection == null) return; if (!(selection instanceof CVSAnnotateBlock)) return; CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); if (listSelection == null) return; /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { IHistoryPage historyPage = historyView.getHistoryPage(); if (historyPage instanceof CVSHistoryPage){ ((CVSHistoryPage) historyPage).selectRevision(listSelection.getRevision()); lastSelectionWasText = false; } } }
private void listSelectionChanged(IStructuredSelection selection) { // If the editor was closed, reopen it. if (editor == null || editor.getSelectionProvider() == null) { try { contents.reset(); showAnnotations(cvsResource, cvsAnnotateBlocks, contents, false); } catch (CVSException e) { return; } catch (PartInitException e) { return; } catch (IOException e) { return; } } ISelectionProvider selectionProvider = editor.getSelectionProvider(); if (selectionProvider == null) { // Failed to open the editor but what else can we do. return; } ITextSelection textSelection = (ITextSelection) selectionProvider.getSelection(); if (textSelection == null) return; if (selection.size() == 1 && !(selection.getFirstElement() instanceof CVSAnnotateBlock)) return; CVSAnnotateBlock listSelection = (CVSAnnotateBlock) selection.getFirstElement(); if (listSelection == null) return; /** * Ignore event if the current text selection is already equal to the corresponding * list selection. Nothing to do. This prevents infinite event looping. * * Extra check to handle single line deltas */ if (textSelection.getStartLine() == listSelection.getStartLine() && textSelection.getEndLine() == listSelection.getEndLine() && selection.equals(previousListSelection)) { return; } // If the last selection was a text selection then bale to prevent a selection loop. if (!lastSelectionWasText) { try { int start = document.getLineOffset(listSelection.getStartLine()); int end = document.getLineOffset(listSelection.getEndLine() + 1); editor.selectAndReveal(start, end - start); if (editor != null && !page.isPartVisible(editor)) { page.activate(editor); } } catch (BadLocationException e) { // Ignore - nothing we can do. } } // Select the revision in the history view. if(historyView != null) { IHistoryPage historyPage = historyView.getHistoryPage(); if (historyPage instanceof CVSHistoryPage){ ((CVSHistoryPage) historyPage).selectRevision(listSelection.getRevision()); lastSelectionWasText = false; } } }
diff --git a/src/MusicStore/RegisterEvents.java b/src/MusicStore/RegisterEvents.java index 7a98a1b..3c02ecc 100644 --- a/src/MusicStore/RegisterEvents.java +++ b/src/MusicStore/RegisterEvents.java @@ -1,128 +1,127 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package MusicStore; import BackEnd.*; import Gui.*; import java.awt.Color; import javax.swing.JOptionPane; /** * * @author Jonathan Maderic */ public class RegisterEvents implements Gui.EventImplementation { public GuiObject MainFrame; private User newUser; private TextBox username; private TextBox password; private TextBox name; private TextBox address; private TextBox credit; public final void MakeElements() { Color ColorScheme = Driver.ColorScheme; MainFrame = new Frame("Register", new DPair(0, 0, 0, 0), new DPair(1, 0, 1, 0), ColorExtension.Lighten(ColorScheme, 1), null); Frame leftPanel = new Frame("LeftPanel", new DPair(0, 0, 0, 0), new DPair(0, 150, 1, 0), Color.WHITE, MainFrame); Frame LoginPanel = new Frame("RegisterPanel", new DPair(0.5, -300, 0.5, -225), new DPair(0, 600, 0, 450), Driver.ColorScheme, MainFrame); new TextLabel("UserRegistion", new DPair(0, 215, 0, 40), new DPair(.33, 0, .09, 0), ColorScheme, LoginPanel, "User Registration", 24); new TextLabel("Username", new DPair(0, 150, 0, 100), new DPair(.15, 0, .09, 0), ColorScheme, LoginPanel, "User Name:", 14); username = new TextBox("Username", new DPair(0, 250, 0, 100), new DPair(.4, 0, 0.09, 0), Color.WHITE, LoginPanel, "Username", 14, new Color(0, 0, 0)); new TextLabel("Password", new DPair(0, 150, 0, 150), new DPair(.15, 0, .09, 0), ColorScheme, LoginPanel, "Password:", 14); password = new TextBox("Password", new DPair(0, 250, 0, 150), new DPair(.4, 0, 0.09, 0), Color.WHITE, LoginPanel, "Password", 14, new Color(0, 0, 0)); new TextLabel("Name", new DPair(0, 150, 0, 200), new DPair(.15, 0, .09, 0), ColorScheme, LoginPanel, "Name:", 14); name = new TextBox("Name", new DPair(0, 250, 0, 200), new DPair(.4, 0, 0.09, 0), Color.WHITE, LoginPanel, "Name", 14, new Color(0, 0, 0)); new TextLabel("Address", new DPair(0, 150, 0, 250), new DPair(.15, 0, .09, 0), ColorScheme, LoginPanel, "Address:", 14); address = new TextBox("Address", new DPair(0, 250, 0, 250), new DPair(.4, 0, 0.09, 0), Color.WHITE, LoginPanel, "Address", 14, new Color(0, 0, 0)); new TextLabel("Credit", new DPair(0, 150, 0, 300), new DPair(.15, 0, .09, 0), ColorScheme, LoginPanel, "Credit ($):", 14); credit = new TextBox("Credit", new DPair(0, 250, 0, 300), new DPair(.4, 0, 0.09, 0), Color.WHITE, LoginPanel, "Credit", 14, new Color(0, 0, 0)); new TextButton("Back", new DPair(0, 5, 0, 400), new DPair(.07, 0, 0.05, 0), Driver.ColorScheme, LoginPanel, "Back", 16); new TextButton("Enter", new DPair(0, 550, 0, 400), new DPair(.07, 0, .05, 0), Driver.ColorScheme, LoginPanel, "Enter", 16); } public RegisterEvents() { MakeElements(); } @Override public void ButtonClicked(GuiObject button, int x, int y) { switch (button.GetName()) { case "Username": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox box = (TextBox) button; if (box.GetText().equals("Username")) { box.SetText(""); } break; case "Password": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox passwordBox = (TextBox) button; if (passwordBox.GetText().equals("Password")) { passwordBox.SetText(""); } break; case "Name": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox nameBox = (TextBox) button; if (nameBox.GetText().equals("Name")) { nameBox.SetText(""); } break; case "Address": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox addressBox = (TextBox) button; if (addressBox.GetText().equals("Address")) { addressBox.SetText(""); } break; case "Credit": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox creditBox = (TextBox) button; if (creditBox.GetText().equals("Credit")) { creditBox.SetText(""); } break; case "Back": Driver.SetFrame("Login"); break; case "Enter": System.out.println("1" + username.GetText() + "1"); if (username.GetText().equals("Username") || password.GetText().equals("Password") || name.GetText().equals("Name") || address.GetText().equals("Address") || credit.GetText().equals("Credit") || username.GetText().equals("") || password.GetText().equals("") || name.GetText().equals("") || address.GetText().equals("") || credit.GetText().equals("")) { JOptionPane.showMessageDialog(null, "Please enter valid values", "invaild value entered", JOptionPane.WARNING_MESSAGE); } else { newUser = new User(username.GetText(), password.GetText(), name.GetText(), address.GetText(), Double.parseDouble(credit.GetText()), false); if (DataLoader.addUserToList(newUser)) { - DataLoader.saveToFile(); Driver.SetFrame("Login"); } else { JOptionPane.showMessageDialog(null, "This user already exists - Please enter a new user", "User Exists", JOptionPane.WARNING_MESSAGE); username.SetText(""); password.SetText(""); name.SetText(""); address.SetText(""); credit.SetText(""); } } break; default: System.out.println("Unidentified item (" + button.getClass().getName() + ") clicked: " + button.GetName()); } } @Override public void MouseDown(GuiObject button, int x, int y) { } @Override public void MouseUp(GuiObject button, int x, int y) { } @Override public void MouseMove(GuiObject button, int x, int y) { } }
true
true
public void ButtonClicked(GuiObject button, int x, int y) { switch (button.GetName()) { case "Username": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox box = (TextBox) button; if (box.GetText().equals("Username")) { box.SetText(""); } break; case "Password": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox passwordBox = (TextBox) button; if (passwordBox.GetText().equals("Password")) { passwordBox.SetText(""); } break; case "Name": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox nameBox = (TextBox) button; if (nameBox.GetText().equals("Name")) { nameBox.SetText(""); } break; case "Address": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox addressBox = (TextBox) button; if (addressBox.GetText().equals("Address")) { addressBox.SetText(""); } break; case "Credit": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox creditBox = (TextBox) button; if (creditBox.GetText().equals("Credit")) { creditBox.SetText(""); } break; case "Back": Driver.SetFrame("Login"); break; case "Enter": System.out.println("1" + username.GetText() + "1"); if (username.GetText().equals("Username") || password.GetText().equals("Password") || name.GetText().equals("Name") || address.GetText().equals("Address") || credit.GetText().equals("Credit") || username.GetText().equals("") || password.GetText().equals("") || name.GetText().equals("") || address.GetText().equals("") || credit.GetText().equals("")) { JOptionPane.showMessageDialog(null, "Please enter valid values", "invaild value entered", JOptionPane.WARNING_MESSAGE); } else { newUser = new User(username.GetText(), password.GetText(), name.GetText(), address.GetText(), Double.parseDouble(credit.GetText()), false); if (DataLoader.addUserToList(newUser)) { DataLoader.saveToFile(); Driver.SetFrame("Login"); } else { JOptionPane.showMessageDialog(null, "This user already exists - Please enter a new user", "User Exists", JOptionPane.WARNING_MESSAGE); username.SetText(""); password.SetText(""); name.SetText(""); address.SetText(""); credit.SetText(""); } } break; default: System.out.println("Unidentified item (" + button.getClass().getName() + ") clicked: " + button.GetName()); } }
public void ButtonClicked(GuiObject button, int x, int y) { switch (button.GetName()) { case "Username": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox box = (TextBox) button; if (box.GetText().equals("Username")) { box.SetText(""); } break; case "Password": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox passwordBox = (TextBox) button; if (passwordBox.GetText().equals("Password")) { passwordBox.SetText(""); } break; case "Name": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox nameBox = (TextBox) button; if (nameBox.GetText().equals("Name")) { nameBox.SetText(""); } break; case "Address": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox addressBox = (TextBox) button; if (addressBox.GetText().equals("Address")) { addressBox.SetText(""); } break; case "Credit": // If the text in the Username text box is "Username" (default), change it when the user clicks. TextBox creditBox = (TextBox) button; if (creditBox.GetText().equals("Credit")) { creditBox.SetText(""); } break; case "Back": Driver.SetFrame("Login"); break; case "Enter": System.out.println("1" + username.GetText() + "1"); if (username.GetText().equals("Username") || password.GetText().equals("Password") || name.GetText().equals("Name") || address.GetText().equals("Address") || credit.GetText().equals("Credit") || username.GetText().equals("") || password.GetText().equals("") || name.GetText().equals("") || address.GetText().equals("") || credit.GetText().equals("")) { JOptionPane.showMessageDialog(null, "Please enter valid values", "invaild value entered", JOptionPane.WARNING_MESSAGE); } else { newUser = new User(username.GetText(), password.GetText(), name.GetText(), address.GetText(), Double.parseDouble(credit.GetText()), false); if (DataLoader.addUserToList(newUser)) { Driver.SetFrame("Login"); } else { JOptionPane.showMessageDialog(null, "This user already exists - Please enter a new user", "User Exists", JOptionPane.WARNING_MESSAGE); username.SetText(""); password.SetText(""); name.SetText(""); address.SetText(""); credit.SetText(""); } } break; default: System.out.println("Unidentified item (" + button.getClass().getName() + ") clicked: " + button.GetName()); } }
diff --git a/src/main/java/hudson/plugins/dimensionsscm/DimensionsSCM.java b/src/main/java/hudson/plugins/dimensionsscm/DimensionsSCM.java index afd76eb..273b252 100644 --- a/src/main/java/hudson/plugins/dimensionsscm/DimensionsSCM.java +++ b/src/main/java/hudson/plugins/dimensionsscm/DimensionsSCM.java @@ -1,1192 +1,1197 @@ /* =========================================================================== * Copyright (c) 2007 Serena Software. All rights reserved. * * Use of the Sample Code provided by Serena is governed by the following * terms and conditions. By using the Sample Code, you agree to be bound by * the terms contained herein. If you do not agree to the terms herein, do * not install, copy, or use the Sample Code. * * 1. GRANT OF LICENSE. Subject to the terms and conditions herein, you * shall have the nonexclusive, nontransferable right to use the Sample Code * for the sole purpose of developing applications for use solely with the * Serena software product(s) that you have licensed separately from Serena. * Such applications shall be for your internal use only. You further agree * that you will not: (a) sell, market, or distribute any copies of the * Sample Code or any derivatives or components thereof; (b) use the Sample * Code or any derivatives thereof for any commercial purpose; or (c) assign * or transfer rights to the Sample Code or any derivatives thereof. * * 2. DISCLAIMER OF WARRANTIES. TO THE MAXIMUM EXTENT PERMITTED BY * APPLICABLE LAW, SERENA PROVIDES THE SAMPLE CODE AS IS AND WITH ALL * FAULTS, AND HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EITHER * EXPRESSED, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY * IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A * PARTICULAR PURPOSE, OF LACK OF VIRUSES, OF RESULTS, AND OF LACK OF * NEGLIGENCE OR LACK OF WORKMANLIKE EFFORT, CONDITION OF TITLE, QUIET * ENJOYMENT, OR NON-INFRINGEMENT. THE ENTIRE RISK AS TO THE QUALITY OF * OR ARISING OUT OF USE OR PERFORMANCE OF THE SAMPLE CODE, IF ANY, * REMAINS WITH YOU. * * 3. EXCLUSION OF DAMAGES. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE * LAW, YOU AGREE THAT IN CONSIDERATION FOR RECEIVING THE SAMPLE CODE AT NO * CHARGE TO YOU, SERENA SHALL NOT BE LIABLE FOR ANY DAMAGES WHATSOEVER, * INCLUDING BUT NOT LIMITED TO DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, DAMAGES FOR LOSS OF * PROFITS OR CONFIDENTIAL OR OTHER INFORMATION, FOR BUSINESS INTERRUPTION, * FOR PERSONAL INJURY, FOR LOSS OF PRIVACY, FOR NEGLIGENCE, AND FOR ANY * OTHER LOSS WHATSOEVER) ARISING OUT OF OR IN ANY WAY RELATED TO THE USE * OF OR INABILITY TO USE THE SAMPLE CODE, EVEN IN THE EVENT OF THE FAULT, * TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR BREACH OF CONTRACT, * EVEN IF SERENA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE * FOREGOING LIMITATIONS, EXCLUSIONS AND DISCLAIMERS SHALL APPLY TO THE * MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW. NOTWITHSTANDING THE ABOVE, * IN NO EVENT SHALL SERENA'S LIABILITY UNDER THIS AGREEMENT OR WITH RESPECT * TO YOUR USE OF THE SAMPLE CODE AND DERIVATIVES THEREOF EXCEED US$10.00. * * 4. INDEMNIFICATION. You hereby agree to defend, indemnify and hold * harmless Serena from and against any and all liability, loss or claim * arising from this agreement or from (i) your license of, use of or * reliance upon the Sample Code or any related documentation or materials, * or (ii) your development, use or reliance upon any application or * derivative work created from the Sample Code. * * 5. TERMINATION OF THE LICENSE. This agreement and the underlying * license granted hereby shall terminate if and when your license to the * applicable Serena software product terminates or if you breach any terms * and conditions of this agreement. * * 6. CONFIDENTIALITY. The Sample Code and all information relating to the * Sample Code (collectively "Confidential Information") are the * confidential information of Serena. You agree to maintain the * Confidential Information in strict confidence for Serena. You agree not * to disclose or duplicate, nor allow to be disclosed or duplicated, any * Confidential Information, in whole or in part, except as permitted in * this Agreement. You shall take all reasonable steps necessary to ensure * that the Confidential Information is not made available or disclosed by * you or by your employees to any other person, firm, or corporation. You * agree that all authorized persons having access to the Confidential * Information shall observe and perform under this nondisclosure covenant. * You agree to immediately notify Serena of any unauthorized access to or * possession of the Confidential Information. * * 7. AFFILIATES. Serena as used herein shall refer to Serena Software, * Inc. and its affiliates. An entity shall be considered to be an * affiliate of Serena if it is an entity that controls, is controlled by, * or is under common control with Serena. * * 8. GENERAL. Title and full ownership rights to the Sample Code, * including any derivative works shall remain with Serena. If a court of * competent jurisdiction holds any provision of this agreement illegal or * otherwise unenforceable, that provision shall be severed and the * remainder of the agreement shall remain in full force and effect. * =========================================================================== */ /* * This experimental plugin extends Hudson support for Dimensions SCM repositories * * @author Tim Payne * */ // Package name package hudson.plugins.dimensionsscm; // Dimensions imports import hudson.plugins.dimensionsscm.DimensionsAPI; import hudson.plugins.dimensionsscm.DimensionsSCMRepositoryBrowser; import hudson.plugins.dimensionsscm.Logger; import hudson.plugins.dimensionsscm.DimensionsChangeLogParser; import hudson.plugins.dimensionsscm.DimensionsBuildWrapper; import hudson.plugins.dimensionsscm.DimensionsBuildNotifier; import hudson.plugins.dimensionsscm.DimensionsChecker; // Hudson imports import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.model.Hudson; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.model.ModelObject; import hudson.model.Run; import hudson.model.TaskListener; import hudson.scm.ChangeLogParser; import hudson.scm.RepositoryBrowsers; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.util.FormFieldValidator; import hudson.util.Scrambler; import hudson.util.VariableResolver; // General imports import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.net.URLDecoder; import java.util.Calendar; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.Iterator; import java.util.ArrayList; import java.util.Arrays; import java.util.Vector; import javax.servlet.ServletException; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.apache.commons.lang.StringUtils; /* * Hudson requires the following functions to be implemented * * public boolean checkout(AbstractBuild build, Launcher launcher, FilePath workspace, BuildListener listener, File changelogFile) * throws IOException, InterruptedException; * public boolean pollChanges(AbstractProject project, Launcher launcher, FilePath workspace, TaskListener listener) * throws IOException, InterruptedException; * public ChangeLogParser createChangeLogParser(); * public SCMDescriptor<?> getDescriptor(); * * For this experimental plugin, only the main ones will be implemented * */ /* * Main Dimensions SCM class which creates the plugin logic */ public class DimensionsSCM extends SCM implements Serializable { // Hudson details private String project; private String directory; private String workarea; private String jobUserName; private String jobPasswd; private String jobServer; private String jobDatabase; private String[] folders = new String[0]; private String jobTimeZone; private String jobWebUrl; private boolean canJobUpdate; private boolean canJobDelete; private boolean canJobForce; private boolean canJobRevert; DimensionsAPI dmSCM; DimensionsSCMRepositoryBrowser browser; public DimensionsSCM getSCM() { return this; } public DimensionsAPI getAPI() { return this.dmSCM; } /* * Gets the project ID for the connection. * @return the project ID */ public String getProject() { return this.project; } /* * Gets the project path. * @return the project path */ public String getDirectory() { return this.directory; } /* * Gets the project paths. * @return the project paths */ public String[] getFolders() { return this.folders; } /* * Gets the workarea path. * @return the workarea path */ public String getWorkarea() { return this.workarea; } /* * Gets the job user ID for the connection. * @return the job user ID */ public String getJobUserName() { return this.jobUserName; } /* * Gets the job passwd for the connection. * @return the project ID */ public String getJobPasswd() { return Scrambler.descramble(jobPasswd); } /* * Gets the server ID for the connection. * @return the server ID */ public String getJobServer() { return this.jobServer; } /* * Gets the job database ID for the connection. * @return the job database ID */ public String getJobDatabase() { return this.jobDatabase; } /* * Gets the job timezone for the connection. * @return the job timezone */ public String getJobTimeZone() { return this.jobTimeZone; } /* * Gets the job weburl ID for the connection. * @return the job weburl */ public String getJobWebUrl() { return this.jobWebUrl; } /* * Gets the update . * @return the update */ public boolean isCanJobUpdate() { return this.canJobUpdate; } /* * Gets the delete . * @return the delete */ public boolean isCanJobDelete() { return this.canJobDelete; } /* * Gets the force . * @return the force */ public boolean isCanJobForce() { return this.canJobForce; } /* * Gets the revert . * @return the force */ public boolean isCanJobRevert() { return this.canJobRevert; } @Extension public static final DescriptorImpl DM_DESCRIPTOR = new DescriptorImpl(); /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * requiresWorkspaceForPolling * Description: * Does this SCM plugin require a workspace for polling? * Parameters: * Return: * @return boolean *----------------------------------------------------------------- */ @Override public boolean requiresWorkspaceForPolling() { return false; } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * supportsPolling * Description: * Does this SCM plugin support polling? * Parameters: * Return: * @return boolean *----------------------------------------------------------------- */ @Override public boolean supportsPolling() { return true; } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * buildEnvVars * Description: * Build up environment variables for build support * Parameters: * Return: *----------------------------------------------------------------- */ @Override public void buildEnvVars(AbstractBuild build, Map<String, String> env) { // To be implemented when build support put in super.buildEnvVars(build, env); return; } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * Constructor * Description: * Default constructor for the plugin * Parameters: * @param String project * @param String workspaceName * @param String workarea * @param String jobServer * @param String jobUserName * @param String jobPasswd * @param String jobDatabase * Return: * @return void *----------------------------------------------------------------- */ public DimensionsSCM(String project, String directory, String workarea, boolean canJobDelete, boolean canJobForce, boolean canJobRevert, String jobUserName, String jobPasswd, String jobServer, String jobDatabase, boolean canJobUpdate, String jobTimeZone, String jobWebUrl) { this(project,null,workarea,canJobDelete, canJobForce,canJobRevert, jobUserName,jobPasswd, jobServer,jobDatabase, canJobUpdate,jobTimeZone, jobWebUrl,directory); } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * Constructor * Description: * Default constructor for the plugin * Parameters: * @param String project * @param String[] folderNames * @param String workspaceName * @param String workarea * @param String jobServer * @param String jobUserName * @param String jobPasswd * @param String jobDatabase * @param String directory * Return: * @return void *----------------------------------------------------------------- */ @DataBoundConstructor public DimensionsSCM(String project, String[] folders, String workarea, boolean canJobDelete, boolean canJobForce, boolean canJobRevert, String jobUserName, String jobPasswd, String jobServer, String jobDatabase, boolean canJobUpdate, String jobTimeZone, String jobWebUrl, String directory) { // Check the folders specified have data specified if (folders != null) { Logger.Debug("Folders are populated"); Vector<String> x = new Vector<String>(); for(int t=0;t<folders.length;t++) { if (StringUtils.isNotEmpty(folders[t])) x.add(folders[t]); } this.folders = (String[])x.toArray(new String[1]); } else { if (directory != null) this.folders[0] = directory; } // If nothing specified, then default to '/' if (this.folders.length < 2) { if (this.folders[0] == null || this.folders[0].length() < 1) this.folders[0] = "/"; } // Copying arguments to fields this.project = (Util.fixEmptyAndTrim(project) == null ? "${JOB_NAME}" : project); this.workarea = (Util.fixEmptyAndTrim(workarea) == null ? null : workarea); this.directory = (Util.fixEmptyAndTrim(directory) == null ? null : directory); this.jobServer = (Util.fixEmptyAndTrim(jobServer) == null ? getDescriptor().getServer() : jobServer); this.jobUserName = (Util.fixEmptyAndTrim(jobUserName) == null ? getDescriptor().getUserName() : jobUserName); this.jobDatabase = (Util.fixEmptyAndTrim(jobDatabase) == null ? getDescriptor().getDatabase() : jobDatabase); String passwd = (Util.fixEmptyAndTrim(jobPasswd) == null ? getDescriptor().getPasswd() : jobPasswd); this.jobPasswd = Scrambler.scramble(passwd); this.canJobUpdate = canJobUpdate; this.canJobDelete = canJobDelete; this.canJobForce = canJobForce; this.canJobRevert = canJobRevert; this.jobTimeZone = (Util.fixEmptyAndTrim(jobTimeZone) == null ? getDescriptor().getTimeZone() : jobTimeZone); this.jobWebUrl = (Util.fixEmptyAndTrim(jobWebUrl) == null ? getDescriptor().getWebUrl() : jobWebUrl); String dmS = this.jobServer + "-" + this.jobUserName + ":" + this.jobDatabase; Logger.Debug("Starting job for project '" + this.project + "' ('" + this.folders.length + "')" + ", connecting to " + dmS); } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * checkout * Description: * Checkout method for the plugin * Parameters: * @param AbstractBuild build * @param Launcher launcher * @param FilePath workspace * @param BuildListener listener * @param File changelogFile * Return: * @return boolean *----------------------------------------------------------------- */ @Override public boolean checkout(final AbstractBuild build, final Launcher launcher, final FilePath workspace, final BuildListener listener, final File changelogFile) throws IOException, InterruptedException { if (!isCanJobUpdate()) { Logger.Debug("Skipping checkout - " + this.getClass().getName()); return true; } Logger.Debug("Invoking checkout - " + this.getClass().getName()); boolean bFreshBuild = (build.getPreviousBuild() == null); boolean bRet = true; try { // Load other Dimensions plugins if set DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildWrapper.class); DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildNotifier.class); if (DimensionsChecker.isValidPluginCombination(build)) { Logger.Debug("Plugins are ok"); } else { listener.fatalError("\n[DIMENSIONS] If you intend to tag this build, then you must set the\n[DIMENSIONS] 'Lock Dimensions project while the build is in progress' option"); return false; } // When are we building files for? // Looking for the last successful build and then going forward from there - could use the last build as well // // Calendar lastBuildCal = (build.getPreviousBuild() != null) ? build.getPreviousBuild().getTimestamp() : null; Calendar lastBuildCal = (build.getPreviousNotFailedBuild() != null) ? build.getPreviousNotFailedBuild().getTimestamp() : null; Calendar nowDateCal = Calendar.getInstance(); TimeZone tz = (getJobTimeZone() != null && getJobTimeZone().length() > 0) ? TimeZone.getTimeZone(getJobTimeZone()) : TimeZone.getDefault(); if (getJobTimeZone() != null && getJobTimeZone().length() > 0) Logger.Debug("Job timezone setting is " + getJobTimeZone()); Logger.Debug("Checkout updates between " + ((lastBuildCal != null) ? DateUtils.getStrDate(lastBuildCal,tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal,tz) + " (" + tz.getID() + ")"); if (dmSCM == null) { Logger.Debug("Creating new API interface object"); dmSCM = new DimensionsAPI(); } // Connect to Dimensions... if (dmSCM.login(jobUserName, getJobPasswd(), jobDatabase, jobServer)) { + Logger.Debug("Login worked."); StringBuffer cmdOutput = new StringBuffer(); FilePath wa = null; if (workarea != null) { File waN = new File(workarea); wa = new FilePath(waN); } else wa = workspace; // Emulate SVN plugin // - if workspace exists and it is not managed by this project, blow it away // if (bFreshBuild) { if (listener.getLogger() != null) { listener.getLogger().println("[DIMENSIONS] Checking out a fresh workspace because this project has not been built before..."); listener.getLogger().flush(); } } if (wa.exists() && (canJobDelete || bFreshBuild)) { Logger.Debug("Deleting '" + wa.toURI() + "'..."); listener.getLogger().println("[DIMENSIONS] Removing '" + wa.toURI() + "'..."); listener.getLogger().flush(); wa.deleteRecursive(); } VariableResolver<String> myResolver = build.getBuildVariableResolver(); String baseline = myResolver.resolve("DM_BASELINE"); String requests = myResolver.resolve("DM_REQUEST"); - baseline = baseline.trim(); - baseline = baseline.toUpperCase(); - requests = requests.replaceAll(" ",""); - requests = requests.toUpperCase(); + if (baseline != null) { + baseline = baseline.trim(); + baseline = baseline.toUpperCase(); + } + if (requests != null) { + requests = requests.replaceAll(" ",""); + requests = requests.toUpperCase(); + } Logger.Debug("Extra parameters - " + baseline + " " + requests); String[] folders = getFolders(); String cmdLog = null; if (baseline != null && baseline.length() == 0) baseline = null; if (requests != null && requests.length() == 0) requests = null; if (listener.getLogger() != null) { if (requests != null) listener.getLogger().println("[DIMENSIONS] Checking out request(s) \"" + requests + "\" - ignoring project folders..."); else if (baseline != null) listener.getLogger().println("[DIMENSIONS] Checking out baseline \"" + baseline + "\"..."); else listener.getLogger().println("[DIMENSIONS] Checking out project \"" + getProject() + "\"..."); listener.getLogger().flush(); } // Iterate through the project folders and process them in Dimensions for (int ii=0;ii<folders.length; ii++) { if (!bRet) break; String folderN = folders[ii]; File fileName = new File(folderN); FilePath dname = new FilePath(fileName); Logger.Debug("Checking out '" + folderN + "'..."); // Checkout the folder bRet = dmSCM.checkout(getProject(),dname,wa, lastBuildCal,nowDateCal, changelogFile, tz, cmdOutput,jobWebUrl, baseline,requests, true,canJobRevert); Logger.Debug("SCM checkout returned " + bRet); if (!bRet && canJobForce) bRet = true; if (cmdLog==null) cmdLog = "\n"; cmdLog += cmdOutput; cmdOutput.setLength(0); cmdLog += "\n"; } if (cmdLog.length() > 0 && listener.getLogger() != null) { Logger.Debug("Found command output to log to the build logger"); listener.getLogger().println("[DIMENSIONS] (Note: Dimensions command output was - "); cmdLog = cmdLog.replaceAll("\n\n","\n"); listener.getLogger().println(cmdLog.replaceAll("\n","\n[DIMENSIONS] ") + ")"); listener.getLogger().flush(); } if (!bRet) { listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().println("[DIMENSIONS] The Dimensions checkout command returned a failure status."); listener.getLogger().println("[DIMENSIONS] Please review the command output and correct any issues"); listener.getLogger().println("[DIMENSIONS] that may have been detected."); listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().flush(); } } } catch(Exception e) { listener.fatalError("Unable to run checkout callout - " + e.getMessage()); // e.printStackTrace(); //throw new IOException("Unable to run checkout callout - " + e.getMessage()); bRet = false; } finally { dmSCM.logout(); } return bRet; } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * pollChanges * Description: * Has the repository had any changes? * Parameters: * @param AbstractProject project * @param Launcher launcher * @param FilePath workspace * @param TaskListener listener * Return: * @return boolean *----------------------------------------------------------------- */ @Override public boolean pollChanges(final AbstractProject project, final Launcher launcher, final FilePath workspace, final TaskListener listener) throws IOException, InterruptedException { boolean bChanged = false; Logger.Debug("Invoking pollChanges - " + this.getClass().getName() ); Logger.Debug("Checking job - " + project.getName()); if (getProject() == null || getProject().length() == 0) return false; if (project.getLastBuild() == null) return true; try { Calendar lastBuildCal = null; if (project.getLastSuccessfulBuild() != null && project.getLastSuccessfulBuild().getTimestamp() != null) lastBuildCal = project.getLastSuccessfulBuild().getTimestamp(); else lastBuildCal = project.getLastBuild().getTimestamp(); Calendar nowDateCal = Calendar.getInstance(); TimeZone tz = (getJobTimeZone() != null && getJobTimeZone().length() > 0) ? TimeZone.getTimeZone(getJobTimeZone()) : TimeZone.getDefault(); if (getJobTimeZone() != null && getJobTimeZone().length() > 0) Logger.Debug("Job timezone setting is " + getJobTimeZone()); Logger.Debug("Checking for any updates between " + ((lastBuildCal != null) ? DateUtils.getStrDate(lastBuildCal,tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal,tz) + " (" + tz.getID() + ")"); if (dmSCM == null) { Logger.Debug("Creating new API interface object"); dmSCM = new DimensionsAPI(); } // Connect to Dimensions... if (dmSCM.login(jobUserName, getJobPasswd(), jobDatabase, jobServer)) { String[] folders = getFolders(); // Iterate through the project folders and process them in Dimensions for (int ii=0;ii<folders.length; ii++) { if (bChanged) break; String folderN = folders[ii]; File fileName = new File(folderN); FilePath dname = new FilePath(fileName); Logger.Debug("Polling '" + folderN + "'..."); bChanged = dmSCM.hasRepositoryBeenUpdated(getProject(), dname,lastBuildCal, nowDateCal, tz); } } } catch(Exception e) { listener.fatalError("Unable to run pollChanges callout - " + e.getMessage()); // e.printStackTrace(); //throw new IOException("Unable to run pollChanges callout - " + e.getMessage()); bChanged = false; } finally { dmSCM.logout(); } return bChanged; } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * createChangeLogParser * Description: * Create a log parser object * Parameters: * Return: * @return ChangeLogParser *----------------------------------------------------------------- */ @Override public ChangeLogParser createChangeLogParser() { Logger.Debug("Invoking createChangeLogParser - " + this.getClass().getName()); return new DimensionsChangeLogParser(); } /* *----------------------------------------------------------------- * FUNCTION SPECIFICATION * Name: * SCMDescriptor * Description: * Return an SCM descriptor * Parameters: * Return: * @return DescriptorImpl *----------------------------------------------------------------- */ @Override public DescriptorImpl getDescriptor() { return DM_DESCRIPTOR; } /* * Implementation class for Dimensions plugin */ public static class DescriptorImpl extends SCMDescriptor<DimensionsSCM> implements ModelObject { DimensionsAPI connectionCheck = null; private String server; private String userName; private String passwd; private String database; private String timeZone; private String webUrl; private boolean canUpdate; /* * Loads the SCM descriptor */ public DescriptorImpl() { super(DimensionsSCM.class, DimensionsSCMRepositoryBrowser.class); load(); Logger.Debug("Loading " + this.getClass().getName()); } public String getDisplayName() { return "Dimensions"; } /* * Save the SCM descriptor configuration */ @Override public boolean configure(StaplerRequest req, JSONObject jobj) throws FormException { // Get the values and check them userName = req.getParameter("dimensionsscm.userName"); passwd = req.getParameter("dimensionsscm.passwd"); server = req.getParameter("dimensionsscm.server"); database = req.getParameter("dimensionsscm.database"); timeZone = req.getParameter("dimensionsscm.timeZone"); webUrl = req.getParameter("dimensionsscm.webUrl"); if (userName != null) userName = Util.fixNull(req.getParameter("dimensionsscm.userName").trim()); if (passwd != null) passwd = Util.fixNull(req.getParameter("dimensionsscm.passwd").trim()); if (server != null) server = Util.fixNull(req.getParameter("dimensionsscm.server").trim()); if (database != null) database = Util.fixNull(req.getParameter("dimensionsscm.database").trim()); if (timeZone != null) timeZone = Util.fixNull(req.getParameter("dimensionsscm.timeZone").trim()); if (webUrl != null) webUrl = Util.fixNull(req.getParameter("dimensionsscm.webUrl").trim()); req.bindJSON(DM_DESCRIPTOR, jobj); this.save(); return super.configure(req, jobj); } @Override public SCM newInstance(StaplerRequest req, JSONObject formData) throws FormException { // Get variables and then construct a new object String[] folders = req.getParameterValues("dimensionsscm.folders"); String project = req.getParameter("dimensionsscm.project"); String directory = req.getParameter("dimensionsscm.directory"); String workarea = req.getParameter("dimensionsscm.workarea"); Boolean canJobDelete = Boolean.valueOf("on".equalsIgnoreCase(req.getParameter("dimensionsscm.canJobDelete"))); Boolean canJobForce = Boolean.valueOf("on".equalsIgnoreCase(req.getParameter("dimensionsscm.canJobForce"))); Boolean canJobRevert = Boolean.valueOf("on".equalsIgnoreCase(req.getParameter("dimensionsscm.canJobRevert"))); Boolean canJobUpdate = Boolean.valueOf("on".equalsIgnoreCase(req.getParameter("dimensionsscm.canJobUpdate"))); String jobUserName = req.getParameter("dimensionsscm.jobUserName"); String jobPasswd = req.getParameter("dimensionsscm.jobPasswd"); String jobServer = req.getParameter("dimensionsscm.jobServer"); String jobDatabase = req.getParameter("dimensionsscm.jobDatabase"); String jobTimeZone = req.getParameter("dimensionsscm.jobTimeZone"); String jobWebUrl = req.getParameter("dimensionsscm.jobWebUrl"); DimensionsSCM scm = new DimensionsSCM(project,folders,workarea,canJobDelete, canJobForce,canJobRevert, jobUserName,jobPasswd, jobServer,jobDatabase, canJobUpdate,jobTimeZone, jobWebUrl,directory); scm.browser = RepositoryBrowsers.createInstance(DimensionsSCMRepositoryBrowser.class,req,formData,"browser"); if (scm.dmSCM == null) scm.dmSCM = new DimensionsAPI(); return scm; } /* * Gets the timezone for the connection. * @return the timezone */ public String getTimeZone() { return this.timeZone; } /* * Gets the weburl ID for the connection. * @return the weburl */ public String getWebUrl() { return this.webUrl; } /* * Gets the user ID for the connection. * @return the user ID of the user as whom to connect */ public String getUserName() { return this.userName; } /* * Gets the base database for the connection (as "NAME@CONNECTION"). * @return the name of the base database to connect to */ public String getDatabase() { return this.database; } /* * Gets the server for the connection. * @return the name of the server to connect to */ public String getServer() { return this.server; } /* * Gets the password . * @return the password */ public String getPasswd() { return Scrambler.descramble(passwd); } /* * Gets the update . * @return the update */ public boolean isCanUpdate() { return this.canUpdate; } /* * Sets the update . */ public void setCanUpdate(boolean x) { this.canUpdate = x; } /* * Sets the user ID for the connection. */ public void setUserName(String userName) { this.userName = userName; } /* * Sets the base database for the connection (as "NAME@CONNECTION"). */ public void setDatabase(String database) { this.database = database; } /* * Sets the server for the connection. */ public void setServer(String server) { this.server = server; } /* * Sets the password . */ public void setPasswd(String password) { this.passwd = Scrambler.scramble(password); } /* * Sets the timezone for the connection. */ public void setTimeZone(String x) { this.timeZone = x; } /* * Sets the weburl ID for the connection. */ public void setWebUrl(String x) { this.webUrl = x; } private void doCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req, rsp, false) { @Override protected void check() throws IOException, ServletException { String value = Util.fixEmpty(request.getParameter("value")); String nullText = null; if (value == null) { if (nullText == null) ok(); else error(nullText); return; } else { ok(); return; } } }.process(); } public void domanadatoryFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req, rsp, false) { @Override protected void check() throws IOException, ServletException { String value = Util.fixEmpty(request.getParameter("value")); String errorTxt = "This value is manadatory."; if (value == null) { error(errorTxt); return; } else { // Some processing ok(); return; } } }.process(); } public void domanadatoryJobFieldCheck(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { new FormFieldValidator(req, rsp, false) { @Override protected void check() throws IOException, ServletException { String value = Util.fixEmpty(request.getParameter("value")); String errorTxt = "This value is manadatory."; // Some processing in the future ok(); return; } }.process(); } /* * Check if the specified Dimensions server is valid */ public void docheckTz(StaplerRequest req, StaplerResponse rsp, @QueryParameter("dimensionsscm.timeZone") final String timezone, @QueryParameter("dimensionsscm.jobTimeZone") final String jobtimezone) throws IOException, ServletException { new FormFieldValidator(req, rsp, false) { @Override protected void check() throws IOException, ServletException { try { String xtz = (jobtimezone != null) ? jobtimezone : timezone; Logger.Debug("Invoking docheckTz - " + xtz); TimeZone ctz = TimeZone.getTimeZone(xtz); String lmt = ctz.getID(); if (lmt.equalsIgnoreCase("GMT") && !(xtz.equalsIgnoreCase("GMT") || xtz.equalsIgnoreCase("Greenwich Mean Time") || xtz.equalsIgnoreCase("UTC") || xtz.equalsIgnoreCase("Coordinated Universal Time"))) error("Timezone specified is not valid."); else ok("Timezone test succeeded!"); return; } catch (Exception e) { error("timezone check error:" + e.getMessage()); } } }.process(); } /* * Check if the specified Dimensions server is valid */ public void docheckServer(StaplerRequest req, StaplerResponse rsp, @QueryParameter("dimensionsscm.userName") final String user, @QueryParameter("dimensionsscm.passwd") final String passwd, @QueryParameter("dimensionsscm.server") final String server, @QueryParameter("dimensionsscm.database") final String database, @QueryParameter("dimensionsscm.jobUserName") final String jobuser, @QueryParameter("dimensionsscm.jobPasswd") final String jobPasswd, @QueryParameter("dimensionsscm.jobServer") final String jobServer, @QueryParameter("dimensionsscm.jobDatabase") final String jobDatabase) throws IOException, ServletException { new FormFieldValidator(req, rsp, false) { @Override protected void check() throws IOException, ServletException { if (connectionCheck == null) connectionCheck = new DimensionsAPI(); try { String xserver = (jobServer != null) ? jobServer : server; String xuser = (jobuser != null) ? jobuser : user; String xpasswd = (jobPasswd != null) ? jobPasswd : passwd; String xdatabase = (jobDatabase != null) ? jobDatabase : database; String dmS = xserver + "-" + xuser + ":" + xdatabase; Logger.Debug("Invoking serverCheck - " + dmS); if (!connectionCheck.login(xuser, xpasswd, xdatabase, xserver)) { error("Connection test failed"); } else { ok("Connection test succeeded!"); connectionCheck.logout(); } return; } catch (Exception e) { error("Server connection error:" + e.getMessage()); } } }.process(); } } }
false
true
public boolean checkout(final AbstractBuild build, final Launcher launcher, final FilePath workspace, final BuildListener listener, final File changelogFile) throws IOException, InterruptedException { if (!isCanJobUpdate()) { Logger.Debug("Skipping checkout - " + this.getClass().getName()); return true; } Logger.Debug("Invoking checkout - " + this.getClass().getName()); boolean bFreshBuild = (build.getPreviousBuild() == null); boolean bRet = true; try { // Load other Dimensions plugins if set DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildWrapper.class); DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildNotifier.class); if (DimensionsChecker.isValidPluginCombination(build)) { Logger.Debug("Plugins are ok"); } else { listener.fatalError("\n[DIMENSIONS] If you intend to tag this build, then you must set the\n[DIMENSIONS] 'Lock Dimensions project while the build is in progress' option"); return false; } // When are we building files for? // Looking for the last successful build and then going forward from there - could use the last build as well // // Calendar lastBuildCal = (build.getPreviousBuild() != null) ? build.getPreviousBuild().getTimestamp() : null; Calendar lastBuildCal = (build.getPreviousNotFailedBuild() != null) ? build.getPreviousNotFailedBuild().getTimestamp() : null; Calendar nowDateCal = Calendar.getInstance(); TimeZone tz = (getJobTimeZone() != null && getJobTimeZone().length() > 0) ? TimeZone.getTimeZone(getJobTimeZone()) : TimeZone.getDefault(); if (getJobTimeZone() != null && getJobTimeZone().length() > 0) Logger.Debug("Job timezone setting is " + getJobTimeZone()); Logger.Debug("Checkout updates between " + ((lastBuildCal != null) ? DateUtils.getStrDate(lastBuildCal,tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal,tz) + " (" + tz.getID() + ")"); if (dmSCM == null) { Logger.Debug("Creating new API interface object"); dmSCM = new DimensionsAPI(); } // Connect to Dimensions... if (dmSCM.login(jobUserName, getJobPasswd(), jobDatabase, jobServer)) { StringBuffer cmdOutput = new StringBuffer(); FilePath wa = null; if (workarea != null) { File waN = new File(workarea); wa = new FilePath(waN); } else wa = workspace; // Emulate SVN plugin // - if workspace exists and it is not managed by this project, blow it away // if (bFreshBuild) { if (listener.getLogger() != null) { listener.getLogger().println("[DIMENSIONS] Checking out a fresh workspace because this project has not been built before..."); listener.getLogger().flush(); } } if (wa.exists() && (canJobDelete || bFreshBuild)) { Logger.Debug("Deleting '" + wa.toURI() + "'..."); listener.getLogger().println("[DIMENSIONS] Removing '" + wa.toURI() + "'..."); listener.getLogger().flush(); wa.deleteRecursive(); } VariableResolver<String> myResolver = build.getBuildVariableResolver(); String baseline = myResolver.resolve("DM_BASELINE"); String requests = myResolver.resolve("DM_REQUEST"); baseline = baseline.trim(); baseline = baseline.toUpperCase(); requests = requests.replaceAll(" ",""); requests = requests.toUpperCase(); Logger.Debug("Extra parameters - " + baseline + " " + requests); String[] folders = getFolders(); String cmdLog = null; if (baseline != null && baseline.length() == 0) baseline = null; if (requests != null && requests.length() == 0) requests = null; if (listener.getLogger() != null) { if (requests != null) listener.getLogger().println("[DIMENSIONS] Checking out request(s) \"" + requests + "\" - ignoring project folders..."); else if (baseline != null) listener.getLogger().println("[DIMENSIONS] Checking out baseline \"" + baseline + "\"..."); else listener.getLogger().println("[DIMENSIONS] Checking out project \"" + getProject() + "\"..."); listener.getLogger().flush(); } // Iterate through the project folders and process them in Dimensions for (int ii=0;ii<folders.length; ii++) { if (!bRet) break; String folderN = folders[ii]; File fileName = new File(folderN); FilePath dname = new FilePath(fileName); Logger.Debug("Checking out '" + folderN + "'..."); // Checkout the folder bRet = dmSCM.checkout(getProject(),dname,wa, lastBuildCal,nowDateCal, changelogFile, tz, cmdOutput,jobWebUrl, baseline,requests, true,canJobRevert); Logger.Debug("SCM checkout returned " + bRet); if (!bRet && canJobForce) bRet = true; if (cmdLog==null) cmdLog = "\n"; cmdLog += cmdOutput; cmdOutput.setLength(0); cmdLog += "\n"; } if (cmdLog.length() > 0 && listener.getLogger() != null) { Logger.Debug("Found command output to log to the build logger"); listener.getLogger().println("[DIMENSIONS] (Note: Dimensions command output was - "); cmdLog = cmdLog.replaceAll("\n\n","\n"); listener.getLogger().println(cmdLog.replaceAll("\n","\n[DIMENSIONS] ") + ")"); listener.getLogger().flush(); } if (!bRet) { listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().println("[DIMENSIONS] The Dimensions checkout command returned a failure status."); listener.getLogger().println("[DIMENSIONS] Please review the command output and correct any issues"); listener.getLogger().println("[DIMENSIONS] that may have been detected."); listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().flush(); } } } catch(Exception e) { listener.fatalError("Unable to run checkout callout - " + e.getMessage()); // e.printStackTrace(); //throw new IOException("Unable to run checkout callout - " + e.getMessage()); bRet = false; } finally { dmSCM.logout(); } return bRet; }
public boolean checkout(final AbstractBuild build, final Launcher launcher, final FilePath workspace, final BuildListener listener, final File changelogFile) throws IOException, InterruptedException { if (!isCanJobUpdate()) { Logger.Debug("Skipping checkout - " + this.getClass().getName()); return true; } Logger.Debug("Invoking checkout - " + this.getClass().getName()); boolean bFreshBuild = (build.getPreviousBuild() == null); boolean bRet = true; try { // Load other Dimensions plugins if set DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildWrapper.class); DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl) Hudson.getInstance().getDescriptor(DimensionsBuildNotifier.class); if (DimensionsChecker.isValidPluginCombination(build)) { Logger.Debug("Plugins are ok"); } else { listener.fatalError("\n[DIMENSIONS] If you intend to tag this build, then you must set the\n[DIMENSIONS] 'Lock Dimensions project while the build is in progress' option"); return false; } // When are we building files for? // Looking for the last successful build and then going forward from there - could use the last build as well // // Calendar lastBuildCal = (build.getPreviousBuild() != null) ? build.getPreviousBuild().getTimestamp() : null; Calendar lastBuildCal = (build.getPreviousNotFailedBuild() != null) ? build.getPreviousNotFailedBuild().getTimestamp() : null; Calendar nowDateCal = Calendar.getInstance(); TimeZone tz = (getJobTimeZone() != null && getJobTimeZone().length() > 0) ? TimeZone.getTimeZone(getJobTimeZone()) : TimeZone.getDefault(); if (getJobTimeZone() != null && getJobTimeZone().length() > 0) Logger.Debug("Job timezone setting is " + getJobTimeZone()); Logger.Debug("Checkout updates between " + ((lastBuildCal != null) ? DateUtils.getStrDate(lastBuildCal,tz) : "0") + " -> " + DateUtils.getStrDate(nowDateCal,tz) + " (" + tz.getID() + ")"); if (dmSCM == null) { Logger.Debug("Creating new API interface object"); dmSCM = new DimensionsAPI(); } // Connect to Dimensions... if (dmSCM.login(jobUserName, getJobPasswd(), jobDatabase, jobServer)) { Logger.Debug("Login worked."); StringBuffer cmdOutput = new StringBuffer(); FilePath wa = null; if (workarea != null) { File waN = new File(workarea); wa = new FilePath(waN); } else wa = workspace; // Emulate SVN plugin // - if workspace exists and it is not managed by this project, blow it away // if (bFreshBuild) { if (listener.getLogger() != null) { listener.getLogger().println("[DIMENSIONS] Checking out a fresh workspace because this project has not been built before..."); listener.getLogger().flush(); } } if (wa.exists() && (canJobDelete || bFreshBuild)) { Logger.Debug("Deleting '" + wa.toURI() + "'..."); listener.getLogger().println("[DIMENSIONS] Removing '" + wa.toURI() + "'..."); listener.getLogger().flush(); wa.deleteRecursive(); } VariableResolver<String> myResolver = build.getBuildVariableResolver(); String baseline = myResolver.resolve("DM_BASELINE"); String requests = myResolver.resolve("DM_REQUEST"); if (baseline != null) { baseline = baseline.trim(); baseline = baseline.toUpperCase(); } if (requests != null) { requests = requests.replaceAll(" ",""); requests = requests.toUpperCase(); } Logger.Debug("Extra parameters - " + baseline + " " + requests); String[] folders = getFolders(); String cmdLog = null; if (baseline != null && baseline.length() == 0) baseline = null; if (requests != null && requests.length() == 0) requests = null; if (listener.getLogger() != null) { if (requests != null) listener.getLogger().println("[DIMENSIONS] Checking out request(s) \"" + requests + "\" - ignoring project folders..."); else if (baseline != null) listener.getLogger().println("[DIMENSIONS] Checking out baseline \"" + baseline + "\"..."); else listener.getLogger().println("[DIMENSIONS] Checking out project \"" + getProject() + "\"..."); listener.getLogger().flush(); } // Iterate through the project folders and process them in Dimensions for (int ii=0;ii<folders.length; ii++) { if (!bRet) break; String folderN = folders[ii]; File fileName = new File(folderN); FilePath dname = new FilePath(fileName); Logger.Debug("Checking out '" + folderN + "'..."); // Checkout the folder bRet = dmSCM.checkout(getProject(),dname,wa, lastBuildCal,nowDateCal, changelogFile, tz, cmdOutput,jobWebUrl, baseline,requests, true,canJobRevert); Logger.Debug("SCM checkout returned " + bRet); if (!bRet && canJobForce) bRet = true; if (cmdLog==null) cmdLog = "\n"; cmdLog += cmdOutput; cmdOutput.setLength(0); cmdLog += "\n"; } if (cmdLog.length() > 0 && listener.getLogger() != null) { Logger.Debug("Found command output to log to the build logger"); listener.getLogger().println("[DIMENSIONS] (Note: Dimensions command output was - "); cmdLog = cmdLog.replaceAll("\n\n","\n"); listener.getLogger().println(cmdLog.replaceAll("\n","\n[DIMENSIONS] ") + ")"); listener.getLogger().flush(); } if (!bRet) { listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().println("[DIMENSIONS] The Dimensions checkout command returned a failure status."); listener.getLogger().println("[DIMENSIONS] Please review the command output and correct any issues"); listener.getLogger().println("[DIMENSIONS] that may have been detected."); listener.getLogger().println("[DIMENSIONS] =========================================================="); listener.getLogger().flush(); } } } catch(Exception e) { listener.fatalError("Unable to run checkout callout - " + e.getMessage()); // e.printStackTrace(); //throw new IOException("Unable to run checkout callout - " + e.getMessage()); bRet = false; } finally { dmSCM.logout(); } return bRet; }
diff --git a/src/com/edinarobotics/zed/commands/SetCollectorCommand.java b/src/com/edinarobotics/zed/commands/SetCollectorCommand.java index cb1baa4..08a4775 100644 --- a/src/com/edinarobotics/zed/commands/SetCollectorCommand.java +++ b/src/com/edinarobotics/zed/commands/SetCollectorCommand.java @@ -1,53 +1,53 @@ package com.edinarobotics.zed.commands; import com.edinarobotics.zed.Components; import com.edinarobotics.zed.subsystems.Collector; import edu.wpi.first.wpilibj.command.Command; public class SetCollectorCommand extends Command { private Collector collector; private Collector.CollectorDirection collectorDirection; private Collector.CollectorLiftDirection collectorLiftDirection; public SetCollectorCommand(Collector.CollectorDirection collectorDirection, Collector.CollectorLiftDirection collectorLiftDirection) { super("SetCollector"); this.collector = Components.getInstance().collector; this.collectorDirection = collectorDirection; this.collectorLiftDirection = collectorLiftDirection; requires(collector); } public SetCollectorCommand(Collector.CollectorDirection collectorDirection){ this(collectorDirection, null); } public SetCollectorCommand(Collector.CollectorLiftDirection collectorLiftDirection){ this(null, collectorLiftDirection); } protected void initialize() { if(collectorDirection != null){ collector.setCollectorDirection(collectorDirection); } - if(collectorDirection != null){ + if(collectorLiftDirection != null){ collector.setCollectorLiftDirection(collectorLiftDirection); } } protected void execute() { } protected boolean isFinished() { return true; } protected void end() { } protected void interrupted() { } }
true
true
protected void initialize() { if(collectorDirection != null){ collector.setCollectorDirection(collectorDirection); } if(collectorDirection != null){ collector.setCollectorLiftDirection(collectorLiftDirection); } }
protected void initialize() { if(collectorDirection != null){ collector.setCollectorDirection(collectorDirection); } if(collectorLiftDirection != null){ collector.setCollectorLiftDirection(collectorLiftDirection); } }
diff --git a/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java b/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java index 60d618205..97ca98d0c 100644 --- a/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java +++ b/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java @@ -1,455 +1,456 @@ /* * 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.servlet.mvc; import groovy.lang.Closure; import groovy.lang.GroovyObject; import groovy.lang.MissingPropertyException; import groovy.lang.ProxyMetaClass; import groovy.util.Proxy; import org.apache.commons.beanutils.BeanMap; import org.apache.commons.collections.map.CompositeMap; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.WordUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsControllerClass; import org.codehaus.groovy.grails.commons.GrailsClassUtils; import org.codehaus.groovy.grails.commons.metaclass.GenericDynamicProperty; import org.codehaus.groovy.grails.scaffolding.GrailsScaffolder; import org.codehaus.groovy.grails.web.metaclass.ChainDynamicMethod; import org.codehaus.groovy.grails.web.metaclass.ControllerDynamicMethods; import org.codehaus.groovy.grails.web.metaclass.GetParamsDynamicProperty; import org.codehaus.groovy.grails.web.servlet.*; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoClosurePropertyForURIException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoViewNameDefinedException; import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.UnknownControllerException; import org.springframework.context.ApplicationContext; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.beans.IntrospectionException; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A helper class for handling controller requests * * @author Graeme Rocher * @since 0.1 * * Created: 12-Jan-2006 */ public class SimpleGrailsControllerHelper implements GrailsControllerHelper { private static final String SCAFFOLDER = "Scaffolder"; private GrailsApplication application; private ApplicationContext applicationContext; private Map chainModel = Collections.EMPTY_MAP; private GrailsScaffolder scaffolder; private ServletContext servletContext; private GrailsApplicationAttributes grailsAttributes; private Pattern uriPattern = Pattern.compile("/(\\w+)/?(\\w*)/?(\\w*)/?(.*)"); private GrailsWebRequest webRequest; private static final Log LOG = LogFactory.getLog(SimpleGrailsControllerHelper.class); private static final String DISPATCH_ACTION_PARAMETER = "_action"; private static final String ID_PARAMETER = "id"; private String id; private String controllerName; private String actionName; private Map extraParams; public SimpleGrailsControllerHelper(GrailsApplication application, ApplicationContext context, ServletContext servletContext) { super(); this.application = application; this.applicationContext = context; this.servletContext = servletContext; this.grailsAttributes = new DefaultGrailsApplicationAttributes(this.servletContext); } public ServletContext getServletContext() { return this.servletContext; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByName(java.lang.String) */ public GrailsControllerClass getControllerClassByName(String name) { return this.application.getController(name); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByURI(java.lang.String) */ public GrailsControllerClass getControllerClassByURI(String uri) { return this.application.getControllerByURI(uri); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerInstance(org.codehaus.groovy.grails.commons.GrailsControllerClass) */ public GroovyObject getControllerInstance(GrailsControllerClass controllerClass) { return (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName()); } /** * If in Proxy's are used in the Groovy context, unproxy (is that a word?) them by setting * the adaptee as the value in the map so that they can be used in non-groovy view technologies * * @param model The model as a map */ private void removeProxiesFromModelObjects(Map model) { for (Iterator keyIter = model.keySet().iterator(); keyIter.hasNext();) { Object current = keyIter.next(); Object modelObject = model.get(current); if(modelObject instanceof Proxy) { model.put( current, ((Proxy)modelObject).getAdaptee() ); } } } public ModelAndView handleURI(String uri, GrailsWebRequest webRequest) { return handleURI(uri, webRequest, Collections.EMPTY_MAP); } /* (non-Javadoc) * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleURI(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.Map) */ public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) { if(uri == null) throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!"); this.webRequest = webRequest; uri = configureStateForUri(uri); GrailsHttpServletRequest request = webRequest.getCurrentRequest(); GrailsHttpServletResponse response = webRequest.getCurrentResponse(); // if the action name is blank check its included as dispatch parameter if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) { actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER)); uri = '/' + controllerName + '/' + actionName; } if(uri.endsWith("/")) uri = uri.substring(0,uri.length() - 1); // if the id is blank check if its a request parameter if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) { id = request.getParameter(ID_PARAMETER); } if(LOG.isDebugEnabled()) { LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]"); } if(LOG.isTraceEnabled()) { LOG.trace("Extra params from uri ["+extraParams+"] "); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = getControllerClassByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } // parse the uri in its individual tokens controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = getControllerInstance(controllerClass); if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) { try { response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 403 error",e); } } request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller ); // Step 3: if scaffolding retrieve scaffolder if(controllerClass.isScaffolding()) { this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER ); if(this.scaffolder == null) throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!"); } // Step 4: get closure property name for URI. if(StringUtils.isBlank(actionName)) actionName = controllerClass.getClosurePropertyName(uri); if (StringUtils.isBlank(actionName)) { // Step 4a: Check if scaffolding if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName)) throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 4a: Set the action and controller name of the web request webRequest.setActionName(actionName); webRequest.setControllerName(controllerName); // populate additional params from url Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME); request.setControllerParams(controllerParams); if(!StringUtils.isBlank(id)) { controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id); } if(!extraParams.isEmpty()) { for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) { String name = (String) i.next(); controllerParams.put(name,extraParams.get(name)); } } // set the flash scope instance to its next state and set on controller FlashScope fs = this.grailsAttributes.getFlashScope(request); fs.next(); // Step 4b: Set grails attributes in request scope request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes); // Step 5: get the view name for this URI. String viewName = controllerClass.getViewByURI(uri); // Step 5a: Check if there is a before interceptor if there is execute it boolean executeAction = true; if(controllerClass.isInterceptedBefore(controller,actionName)) { Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller); if(beforeInterceptor!= null) { Object interceptorResult = beforeInterceptor.call(); if(interceptorResult instanceof Boolean) { executeAction = ((Boolean)interceptorResult).booleanValue(); } } } // if the interceptor returned false don't execute the action if(!executeAction) return null; // Step 6: get closure from closure property Closure action; try { action = (Closure)controller.getProperty(actionName); // Step 7: process the action Object returnValue = handleAction( controller,action,request,response,params ); // Step 8: determine return value type and handle accordingly initChainModel(controller); if(response.isRedirected()) { return null; } ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName); // Step 9: Check if there is after interceptor if(controllerClass.isInterceptedAfter(controller,actionName)) { Closure afterInterceptor = controllerClass.getAfterInterceptor(controller); - afterInterceptor.call(new Object[]{ mv.getModel() }); + Map model = mv.getModel() != null ? mv.getModel() : Collections.EMPTY_MAP; + afterInterceptor.call(new Object[]{ model }); } return mv; } catch(MissingPropertyException mpe) { if(controllerClass.isScaffolding()) throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!"); else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 404 error",e); } } } } private String configureStateForUri(String uri) { // step 1: process the uri if (uri.indexOf("?") > -1) { uri = uri.substring(0, uri.indexOf("?")); } if(uri.indexOf('\\') > -1) { uri = uri.replaceAll("\\\\", "/"); } if(!uri.startsWith("/")) uri = '/' + uri; if(uri.endsWith("/")) uri = uri.substring(0,uri.length() - 1); id = null; controllerName = null; actionName = null; extraParams = Collections.EMPTY_MAP; Matcher m = uriPattern.matcher(uri); if(m.find()) { controllerName = m.group(1); actionName = m.group(2); uri = '/' + controllerName + '/' + actionName; id = m.group(3); String extraParamsString = m.group(4); if(extraParamsString != null && extraParamsString.indexOf('/') > - 1) { String[] tokens = extraParamsString.split("/"); extraParams = new HashMap(); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if(i == 0 || ((i % 2) == 0)) { if((i + 1) < tokens.length) { extraParams.put(token, tokens[i + 1]); } } } } } return uri; } public GrailsApplicationAttributes getGrailsAttributes() { return this.grailsAttributes; } public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response) { return handleAction(controller,action,request,response,Collections.EMPTY_MAP); } public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response, Map params) { // if there are additional params add them to the params dynamic property if(params != null && !params.isEmpty()) { GrailsParameterMap paramsMap = (GrailsParameterMap)controller.getProperty("params"); paramsMap.putAll( params ); } // Step 7: determine argument count and execute. Object returnValue = action.call(); // Step 8: add any errors to the request request.setAttribute( GrailsApplicationAttributes.ERRORS, controller.getProperty(ControllerDynamicMethods.ERRORS_PROPERTY) ); return returnValue; } /* (non-Javadoc) * @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleActionResponse(org.codehaus.groovy.grails.commons.GrailsControllerClass, java.lang.Object, java.lang.String, java.lang.String) */ public ModelAndView handleActionResponse( GroovyObject controller,Object returnValue,String closurePropertyName, String viewName) { boolean viewNameBlank = (viewName == null || viewName.length() == 0); // reset the metaclass ModelAndView explicityModelAndView = (ModelAndView)controller.getProperty(ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY); if(!webRequest.isRenderView()) { return null; } else if(explicityModelAndView != null) { return explicityModelAndView; } else if (returnValue == null) { if (viewNameBlank) { return null; } else { Map model; if(!this.chainModel.isEmpty()) { model = new CompositeMap(this.chainModel, new BeanMap(controller)); } else { model = new BeanMap(controller); } return new ModelAndView(viewName, model); } } else if (returnValue instanceof Map) { // remove any Proxy wrappers and set the adaptee as the value Map returnModel = (Map)returnValue; removeProxiesFromModelObjects(returnModel); if(!this.chainModel.isEmpty()) { returnModel.putAll(this.chainModel); } return new ModelAndView(viewName, returnModel); } else if (returnValue instanceof ModelAndView) { ModelAndView modelAndView = (ModelAndView)returnValue; // remove any Proxy wrappers and set the adaptee as the value Map modelMap = modelAndView.getModel(); removeProxiesFromModelObjects(modelMap); if(!this.chainModel.isEmpty()) { modelAndView.addAllObjects(this.chainModel); } if (modelAndView.getView() == null && modelAndView.getViewName() == null) { if (viewNameBlank) { throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controller.getClass() + "]!"); } else { modelAndView.setViewName(viewName); } } return modelAndView; } else { Map model; if(!this.chainModel.isEmpty()) { model = new CompositeMap(this.chainModel, new BeanMap(controller)); } else { model = new BeanMap(controller); } return new ModelAndView(viewName, model); } } private void initChainModel(GroovyObject controller) { FlashScope fs = this.grailsAttributes.getFlashScope((HttpServletRequest)controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY)); if(fs.containsKey(ChainDynamicMethod.PROPERTY_CHAIN_MODEL)) { this.chainModel = (Map)fs.get(ChainDynamicMethod.PROPERTY_CHAIN_MODEL); if(this.chainModel == null) this.chainModel = Collections.EMPTY_MAP; } } }
true
true
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) { if(uri == null) throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!"); this.webRequest = webRequest; uri = configureStateForUri(uri); GrailsHttpServletRequest request = webRequest.getCurrentRequest(); GrailsHttpServletResponse response = webRequest.getCurrentResponse(); // if the action name is blank check its included as dispatch parameter if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) { actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER)); uri = '/' + controllerName + '/' + actionName; } if(uri.endsWith("/")) uri = uri.substring(0,uri.length() - 1); // if the id is blank check if its a request parameter if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) { id = request.getParameter(ID_PARAMETER); } if(LOG.isDebugEnabled()) { LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]"); } if(LOG.isTraceEnabled()) { LOG.trace("Extra params from uri ["+extraParams+"] "); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = getControllerClassByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } // parse the uri in its individual tokens controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = getControllerInstance(controllerClass); if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) { try { response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 403 error",e); } } request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller ); // Step 3: if scaffolding retrieve scaffolder if(controllerClass.isScaffolding()) { this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER ); if(this.scaffolder == null) throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!"); } // Step 4: get closure property name for URI. if(StringUtils.isBlank(actionName)) actionName = controllerClass.getClosurePropertyName(uri); if (StringUtils.isBlank(actionName)) { // Step 4a: Check if scaffolding if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName)) throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 4a: Set the action and controller name of the web request webRequest.setActionName(actionName); webRequest.setControllerName(controllerName); // populate additional params from url Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME); request.setControllerParams(controllerParams); if(!StringUtils.isBlank(id)) { controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id); } if(!extraParams.isEmpty()) { for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) { String name = (String) i.next(); controllerParams.put(name,extraParams.get(name)); } } // set the flash scope instance to its next state and set on controller FlashScope fs = this.grailsAttributes.getFlashScope(request); fs.next(); // Step 4b: Set grails attributes in request scope request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes); // Step 5: get the view name for this URI. String viewName = controllerClass.getViewByURI(uri); // Step 5a: Check if there is a before interceptor if there is execute it boolean executeAction = true; if(controllerClass.isInterceptedBefore(controller,actionName)) { Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller); if(beforeInterceptor!= null) { Object interceptorResult = beforeInterceptor.call(); if(interceptorResult instanceof Boolean) { executeAction = ((Boolean)interceptorResult).booleanValue(); } } } // if the interceptor returned false don't execute the action if(!executeAction) return null; // Step 6: get closure from closure property Closure action; try { action = (Closure)controller.getProperty(actionName); // Step 7: process the action Object returnValue = handleAction( controller,action,request,response,params ); // Step 8: determine return value type and handle accordingly initChainModel(controller); if(response.isRedirected()) { return null; } ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName); // Step 9: Check if there is after interceptor if(controllerClass.isInterceptedAfter(controller,actionName)) { Closure afterInterceptor = controllerClass.getAfterInterceptor(controller); afterInterceptor.call(new Object[]{ mv.getModel() }); } return mv; } catch(MissingPropertyException mpe) { if(controllerClass.isScaffolding()) throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!"); else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 404 error",e); } } } }
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) { if(uri == null) throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!"); this.webRequest = webRequest; uri = configureStateForUri(uri); GrailsHttpServletRequest request = webRequest.getCurrentRequest(); GrailsHttpServletResponse response = webRequest.getCurrentResponse(); // if the action name is blank check its included as dispatch parameter if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) { actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER)); uri = '/' + controllerName + '/' + actionName; } if(uri.endsWith("/")) uri = uri.substring(0,uri.length() - 1); // if the id is blank check if its a request parameter if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) { id = request.getParameter(ID_PARAMETER); } if(LOG.isDebugEnabled()) { LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]"); } if(LOG.isTraceEnabled()) { LOG.trace("Extra params from uri ["+extraParams+"] "); } // Step 2: lookup the controller in the application. GrailsControllerClass controllerClass = getControllerClassByURI(uri); if (controllerClass == null) { throw new UnknownControllerException("No controller found for URI [" + uri + "]!"); } // parse the uri in its individual tokens controllerName = WordUtils.uncapitalize(controllerClass.getName()); // Step 3: load controller from application context. GroovyObject controller = getControllerInstance(controllerClass); if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) { try { response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 403 error",e); } } request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller ); // Step 3: if scaffolding retrieve scaffolder if(controllerClass.isScaffolding()) { this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER ); if(this.scaffolder == null) throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!"); } // Step 4: get closure property name for URI. if(StringUtils.isBlank(actionName)) actionName = controllerClass.getClosurePropertyName(uri); if (StringUtils.isBlank(actionName)) { // Step 4a: Check if scaffolding if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName)) throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!"); } // Step 4a: Set the action and controller name of the web request webRequest.setActionName(actionName); webRequest.setControllerName(controllerName); // populate additional params from url Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME); request.setControllerParams(controllerParams); if(!StringUtils.isBlank(id)) { controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id); } if(!extraParams.isEmpty()) { for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) { String name = (String) i.next(); controllerParams.put(name,extraParams.get(name)); } } // set the flash scope instance to its next state and set on controller FlashScope fs = this.grailsAttributes.getFlashScope(request); fs.next(); // Step 4b: Set grails attributes in request scope request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes); // Step 5: get the view name for this URI. String viewName = controllerClass.getViewByURI(uri); // Step 5a: Check if there is a before interceptor if there is execute it boolean executeAction = true; if(controllerClass.isInterceptedBefore(controller,actionName)) { Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller); if(beforeInterceptor!= null) { Object interceptorResult = beforeInterceptor.call(); if(interceptorResult instanceof Boolean) { executeAction = ((Boolean)interceptorResult).booleanValue(); } } } // if the interceptor returned false don't execute the action if(!executeAction) return null; // Step 6: get closure from closure property Closure action; try { action = (Closure)controller.getProperty(actionName); // Step 7: process the action Object returnValue = handleAction( controller,action,request,response,params ); // Step 8: determine return value type and handle accordingly initChainModel(controller); if(response.isRedirected()) { return null; } ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName); // Step 9: Check if there is after interceptor if(controllerClass.isInterceptedAfter(controller,actionName)) { Closure afterInterceptor = controllerClass.getAfterInterceptor(controller); Map model = mv.getModel() != null ? mv.getModel() : Collections.EMPTY_MAP; afterInterceptor.call(new Object[]{ model }); } return mv; } catch(MissingPropertyException mpe) { if(controllerClass.isScaffolding()) throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!"); else { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; } catch (IOException e) { throw new ControllerExecutionException("I/O error sending 404 error",e); } } } }
diff --git a/cat-home/src/main/java/com/dianping/cat/system/page/login/Handler.java b/cat-home/src/main/java/com/dianping/cat/system/page/login/Handler.java index 6ecbe330..de787e06 100644 --- a/cat-home/src/main/java/com/dianping/cat/system/page/login/Handler.java +++ b/cat-home/src/main/java/com/dianping/cat/system/page/login/Handler.java @@ -1,168 +1,168 @@ package com.dianping.cat.system.page.login; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.unidal.lookup.annotation.Inject; import org.unidal.web.jsp.function.CodecFunction; import org.unidal.web.mvc.ActionContext; import org.unidal.web.mvc.ErrorObject; import org.unidal.web.mvc.PageHandler; import org.unidal.web.mvc.annotation.InboundActionMeta; import org.unidal.web.mvc.annotation.OutboundActionMeta; import org.unidal.web.mvc.annotation.PayloadMeta; import com.dainping.cat.home.dal.user.DpAdminLogin; import com.dianping.cat.system.SystemContext; import com.dianping.cat.system.SystemPage; import com.dianping.cat.system.page.login.service.Credential; import com.dianping.cat.system.page.login.service.Session; import com.dianping.cat.system.page.login.service.SigninContext; import com.dianping.cat.system.page.login.service.SigninService; public class Handler implements PageHandler<Context> { @Inject private JspViewer m_jspViewer; @Inject private SigninService m_signinService; private SigninContext createSigninContext(Context ctx) { return new SigninContext(ctx.getHttpServletRequest(), ctx.getHttpServletResponse()); } @Override @PayloadMeta(Payload.class) @InboundActionMeta(name = "login") public void handleInbound(Context ctx) throws ServletException, IOException { Payload payload = ctx.getPayload(); Action action = payload.getAction(); if (payload.isSubmit() && action == Action.LOGIN) { String account = payload.getAccount(); String password = payload.getPassword(); if (account != null && account.length() != 0 && password != null) { SigninContext sc = createSigninContext(ctx); Credential credential = new Credential(account, password); Session session = m_signinService.signin(sc, credential); if (session == null) { ctx.addError(new ErrorObject("biz.login")); } else { redirect(ctx, payload); return; } } else { - ctx.addError(new ErrorObject("biz.login.input").setArguments("account", account, "password", password)); + ctx.addError(new ErrorObject("biz.login.input").addArgument("account", account).addArgument("password", password)); } } else if (action == Action.LOGOUT) { SigninContext sc = createSigninContext(ctx); m_signinService.signout(sc); redirect(ctx, payload); return; } else { SigninContext sc = createSigninContext(ctx); Session session = m_signinService.validate(sc); if (session != null) { ActionContext<?> parent = ctx.getParent(); if (parent instanceof SystemContext) { SystemContext<?> context = (SystemContext<?>) parent; DpAdminLogin member = session.getMember(); context.setSigninMember(member); logAccess(ctx, member); return; } else if (parent != null) { throw new RuntimeException(String.format("%s should extend %s!", ctx.getClass(), SystemContext.class)); } } } // skip actual action, show sign-in form ctx.skipAction(); } private void redirect(Context ctx, Payload payload) { String url = payload.getRtnUrl(); String loginUrl = ctx.getRequestContext().getActionUri(SystemPage.LOGIN.getName()); if (url == null || url.length() == 0 || url.equals(loginUrl)) { url = ctx.getRequestContext().getActionUri(""); } ctx.redirect(url); ctx.stopProcess(); } @Override @OutboundActionMeta(name = "login") public void handleOutbound(Context ctx) throws ServletException, IOException { Model model = new Model(ctx); Payload payload = ctx.getPayload(); model.setPage(SystemPage.LOGIN); model.setAction(Action.LOGIN); if (ctx.getParent() != null && (payload.getRtnUrl() == null || payload.getRtnUrl().length() == 0)) { HttpServletRequest request = ctx.getHttpServletRequest(); String qs = request.getQueryString(); String requestURI = request.getRequestURI(); if (qs != null) { payload.setRtnUrl(requestURI + "?" + qs); } else { payload.setRtnUrl(requestURI); } } m_jspViewer.view(ctx, model); } @SuppressWarnings("unchecked") private void logAccess(Context ctx, DpAdminLogin member) { StringBuilder sb = new StringBuilder(256); SimpleDateFormat dateFormat = new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]"); HttpServletRequest request = ctx.getHttpServletRequest(); String actionUri = ctx.getRequestContext().getActionUri(); sb.append(dateFormat.format(new Date())); sb.append(" ").append(member.getLoginName()).append('/').append(member.getLoginId()).append(' '); if (request.getMethod().equalsIgnoreCase("post")) { Enumeration<String> names = request.getParameterNames(); boolean hasQuestion = actionUri.indexOf('?') >= 0; sb.append(actionUri); while (names.hasMoreElements()) { String name = names.nextElement(); String[] attributes = request.getParameterValues(name); for (String attribute : attributes) { if (attribute.length() > 0) { if (!hasQuestion) { sb.append('?'); hasQuestion = true; } else { sb.append('&'); } sb.append(name).append('=').append(CodecFunction.urlEncode(attribute)); } } } } else { sb.append(actionUri); } // m_logger.info(sb.toString()); } }
true
true
public void handleInbound(Context ctx) throws ServletException, IOException { Payload payload = ctx.getPayload(); Action action = payload.getAction(); if (payload.isSubmit() && action == Action.LOGIN) { String account = payload.getAccount(); String password = payload.getPassword(); if (account != null && account.length() != 0 && password != null) { SigninContext sc = createSigninContext(ctx); Credential credential = new Credential(account, password); Session session = m_signinService.signin(sc, credential); if (session == null) { ctx.addError(new ErrorObject("biz.login")); } else { redirect(ctx, payload); return; } } else { ctx.addError(new ErrorObject("biz.login.input").setArguments("account", account, "password", password)); } } else if (action == Action.LOGOUT) { SigninContext sc = createSigninContext(ctx); m_signinService.signout(sc); redirect(ctx, payload); return; } else { SigninContext sc = createSigninContext(ctx); Session session = m_signinService.validate(sc); if (session != null) { ActionContext<?> parent = ctx.getParent(); if (parent instanceof SystemContext) { SystemContext<?> context = (SystemContext<?>) parent; DpAdminLogin member = session.getMember(); context.setSigninMember(member); logAccess(ctx, member); return; } else if (parent != null) { throw new RuntimeException(String.format("%s should extend %s!", ctx.getClass(), SystemContext.class)); } } } // skip actual action, show sign-in form ctx.skipAction(); }
public void handleInbound(Context ctx) throws ServletException, IOException { Payload payload = ctx.getPayload(); Action action = payload.getAction(); if (payload.isSubmit() && action == Action.LOGIN) { String account = payload.getAccount(); String password = payload.getPassword(); if (account != null && account.length() != 0 && password != null) { SigninContext sc = createSigninContext(ctx); Credential credential = new Credential(account, password); Session session = m_signinService.signin(sc, credential); if (session == null) { ctx.addError(new ErrorObject("biz.login")); } else { redirect(ctx, payload); return; } } else { ctx.addError(new ErrorObject("biz.login.input").addArgument("account", account).addArgument("password", password)); } } else if (action == Action.LOGOUT) { SigninContext sc = createSigninContext(ctx); m_signinService.signout(sc); redirect(ctx, payload); return; } else { SigninContext sc = createSigninContext(ctx); Session session = m_signinService.validate(sc); if (session != null) { ActionContext<?> parent = ctx.getParent(); if (parent instanceof SystemContext) { SystemContext<?> context = (SystemContext<?>) parent; DpAdminLogin member = session.getMember(); context.setSigninMember(member); logAccess(ctx, member); return; } else if (parent != null) { throw new RuntimeException(String.format("%s should extend %s!", ctx.getClass(), SystemContext.class)); } } } // skip actual action, show sign-in form ctx.skipAction(); }
diff --git a/src/com/wra/bukkit/ItemSound/ItemSoundCommand.java b/src/com/wra/bukkit/ItemSound/ItemSoundCommand.java index 0f1a874..114e0e7 100644 --- a/src/com/wra/bukkit/ItemSound/ItemSoundCommand.java +++ b/src/com/wra/bukkit/ItemSound/ItemSoundCommand.java @@ -1,51 +1,52 @@ package com.wra.bukkit.ItemSound; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.config.ConfigurationNode; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.gui.InGameHUD; import org.getspout.spoutapi.gui.Screen; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: raptors * Date: 8/6/11 * Time: 5:26 AM * To change this template use File | Settings | File Templates. */ public class ItemSoundCommand implements CommandExecutor { private ItemSound plugin; public ItemSoundCommand(ItemSound plugin) { super(); this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { if(!sender.hasPermission("itemsound.config")) { sender.sendMessage("No permission to modify item sounds"); return true; } if(split.length == 1) { String[] ts = new String[2]; ts[0] = split[0]; ts[1] = ""; split = ts; } if(split.length != 2) { sender.sendMessage("Incorrect number of parameters"); return false; } plugin.config.setProperty("effect."+split[0].toUpperCase(), split[1]); + plugin.config.save(); sender.sendMessage("Set item pickup "+split[0].toUpperCase()+" to "+ split[1]); return true; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { if(!sender.hasPermission("itemsound.config")) { sender.sendMessage("No permission to modify item sounds"); return true; } if(split.length == 1) { String[] ts = new String[2]; ts[0] = split[0]; ts[1] = ""; split = ts; } if(split.length != 2) { sender.sendMessage("Incorrect number of parameters"); return false; } plugin.config.setProperty("effect."+split[0].toUpperCase(), split[1]); sender.sendMessage("Set item pickup "+split[0].toUpperCase()+" to "+ split[1]); return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { if(!sender.hasPermission("itemsound.config")) { sender.sendMessage("No permission to modify item sounds"); return true; } if(split.length == 1) { String[] ts = new String[2]; ts[0] = split[0]; ts[1] = ""; split = ts; } if(split.length != 2) { sender.sendMessage("Incorrect number of parameters"); return false; } plugin.config.setProperty("effect."+split[0].toUpperCase(), split[1]); plugin.config.save(); sender.sendMessage("Set item pickup "+split[0].toUpperCase()+" to "+ split[1]); return true; }
diff --git a/nifty-controls/src/main/java/de/lessvoid/nifty/controls/textfield/TextFieldControl.java b/nifty-controls/src/main/java/de/lessvoid/nifty/controls/textfield/TextFieldControl.java index d98c9a4d..52b770fb 100644 --- a/nifty-controls/src/main/java/de/lessvoid/nifty/controls/textfield/TextFieldControl.java +++ b/nifty-controls/src/main/java/de/lessvoid/nifty/controls/textfield/TextFieldControl.java @@ -1,540 +1,543 @@ package de.lessvoid.nifty.controls.textfield; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.*; import de.lessvoid.nifty.controls.textfield.filter.delete.TextFieldDeleteFilter; import de.lessvoid.nifty.controls.textfield.filter.input.*; import de.lessvoid.nifty.controls.textfield.format.FormatPassword; import de.lessvoid.nifty.controls.textfield.format.TextFieldDisplayFormat; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.elements.render.TextRenderer; import de.lessvoid.nifty.elements.tools.FontHelper; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.input.NiftyStandardInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.spi.render.RenderFont; import de.lessvoid.nifty.tools.SizeValue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.logging.Logger; /** * A TextFieldControl. * * @author void * @author Martin Karing &lt;[email protected]&gt; * @deprecated Please use {@link TextField} when accessing NiftyControls. */ @Deprecated public class TextFieldControl extends AbstractController implements TextField, TextFieldView { @Nonnull private static final Logger log = Logger.getLogger(TextFieldControl.class.getName()); @Nullable private Nifty nifty; @Nullable private Screen screen; @Nullable private Element textElement; @Nullable private Element fieldElement; @Nullable private Element cursorElement; @Nullable private TextFieldLogic textField; private int firstVisibleCharacterIndex; private int lastVisibleCharacterIndex; private int fieldWidth; private int fromClickCursorPos; private int toClickCursorPos; @Nullable private FocusHandler focusHandler; @Override public void bind( @Nonnull final Nifty niftyParam, @Nonnull final Screen screenParam, @Nonnull final Element newElement, @Nonnull final Parameters properties) { bind(newElement); nifty = niftyParam; screen = screenParam; fromClickCursorPos = -1; toClickCursorPos = -1; final String initText = properties.get("text"); //NON-NLS if ((initText == null) || initText.isEmpty()) { textField = new TextFieldLogic(nifty.getClipboard(), this); textField.toFirstPosition(); } else { textField = new TextFieldLogic(initText, nifty.getClipboard(), this); } textElement = newElement.findElementById("#text"); //NON-NLS fieldElement = newElement.findElementById("#field"); //NON-NLS cursorElement = newElement.findElementById("#cursor"); //NON-NLS if (textElement == null) { log.warning("Locating the text element of the text field failed. Looked for: #text"); } if (fieldElement == null) { log.warning("Locating the field element of the text field failed. Looked for: #field"); } if (cursorElement == null) { log.warning("Locating the cursor element of the text field failed. Looked for: #cursor"); } if (properties.isSet("passwordChar")) { //NON-NLS //noinspection ConstantConditions textField.setFormat(new FormatPassword(properties.get("passwordChar").charAt(0))); //NON-NLS } setMaxLength(properties.getAsInteger("maxLength", UNLIMITED_LENGTH)); activateFilter(properties.getWithDefault("filter", "all")); } /** * Apply a filter in regards to the filter property that was set for this text field control. * * @param filter the value of the filter property */ private void activateFilter(@Nonnull final String filter) { if ("all".equals(filter)) { //NON-NLS disableInputFilter(); } else if ("digits".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptDigits()); } else if ("negative digits".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptNegativeDigits()); } else if ("float".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptFloat()); } else if ("letters".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptLetters()); } else if ("upper case".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptUpperCase()); } else if ("lower case".equals(filter)) { //NON-NLS enableInputFilter(new FilterAcceptLowerCase()); } else { enableInputFilter(new FilterAcceptRegex(filter)); } } @Override public void init(@Nonnull final Parameters parameter) { super.init(parameter); if (screen == null) { log.severe("Screen instance not set. Binding failed or did not run yet."); return; } focusHandler = screen.getFocusHandler(); if (textField == null) { log.severe("Field logic not available. Binding failed or did not run yet."); return; } layoutCallback(); CharSequence displayedText = textField.getDisplayedText(); firstVisibleCharacterIndex = 0; lastVisibleCharacterIndex = displayedText.length(); if (textElement != null) { final TextRenderer textRenderer = textElement.getRenderer(TextRenderer.class); if (textRenderer == null) { log.warning("Text element does not contain a text renderer"); } else { RenderFont font = textRenderer.getFont(); if (font == null) { log.warning("No font applied to text element."); } else { lastVisibleCharacterIndex = FontHelper.getVisibleCharactersFromStart(font, displayedText, fieldWidth, 1.0f); } } } updateCursor(); } @Override public void onStartScreen() { } @Override public void layoutCallback() { if (fieldElement != null && cursorElement != null) { fieldWidth = fieldElement.getWidth() - cursorElement.getWidth(); } else { fieldWidth = 0; } } @Nonnull private CharSequence getVisibleText() { if (textField == null) { return ""; } if (lastVisibleCharacterIndex == UNLIMITED_LENGTH) { final CharSequence text = textField.getDisplayedText(); return text.subSequence(firstVisibleCharacterIndex, text.length()); } return textField.getDisplayedText().subSequence(firstVisibleCharacterIndex, lastVisibleCharacterIndex); } public void onClick(final int mouseX, final int mouseY) { final CharSequence visibleString = getVisibleText(); final int indexFromPixel = getCursorPosFromMouse(mouseX, visibleString); if (indexFromPixel != -1) { fromClickCursorPos = firstVisibleCharacterIndex + indexFromPixel; } if (textField != null) { textField.resetSelection(); textField.setCursorPosition(fromClickCursorPos); } updateCursor(); } public void onClickMouseMove(final int mouseX, final int mouseY) { final CharSequence visibleString = getVisibleText(); final int indexFromPixel = getCursorPosFromMouse(mouseX, visibleString); if (indexFromPixel != -1) { toClickCursorPos = firstVisibleCharacterIndex + indexFromPixel; } if (textField != null) { textField.setCursorPosition(fromClickCursorPos); textField.startSelecting(); textField.setCursorPosition(toClickCursorPos); textField.endSelecting(); } updateCursor(); } private int getCursorPosFromMouse(final int mouseX, @Nonnull final CharSequence visibleString) { if (textElement == null || fieldElement == null) { return 0; } final TextRenderer textRenderer = textElement.getRenderer(TextRenderer.class); if (textRenderer == null) { return 0; } final RenderFont font = textRenderer.getFont(); if (font == null) { return 0; } return FontHelper.getCharacterIndexFromPixelPosition(font, visibleString, mouseX - fieldElement.getX(), 1.0f); } @Override public boolean inputEvent(@Nonnull final NiftyInputEvent inputEvent) { if (inputEvent instanceof NiftyStandardInputEvent) { final NiftyStandardInputEvent standardInputEvent = (NiftyStandardInputEvent) inputEvent; if (textField != null) { switch (standardInputEvent) { case MoveCursorLeft: textField.cursorLeft(); break; case MoveCursorRight: textField.cursorRight(); break; case Delete: textField.delete(); break; case Backspace: textField.backspace(); break; case MoveCursorToLastPosition: textField.toLastPosition(); break; case MoveCursorToFirstPosition: textField.toFirstPosition(); break; case SelectionStart: textField.startSelecting(); break; case SelectionEnd: textField.endSelecting(); break; case Cut: textField.cut(); break; case Copy: textField.copy(); break; case Paste: textField.put(); break; case SelectAll: textField.selectAll(); break; case Character: textField.insert(standardInputEvent.getCharacter()); break; - } - } - if (fieldElement != null && focusHandler != null) { - switch (standardInputEvent) { case NextInputElement: - focusHandler.getNext(fieldElement).setFocus(); + if (focusHandler != null && fieldElement != null) { + focusHandler.getNext(fieldElement).setFocus(); + } break; case PrevInputElement: - focusHandler.getPrev(fieldElement).setFocus(); + if (focusHandler != null && fieldElement != null) { + focusHandler.getPrev(fieldElement).setFocus(); + } break; + default: + updateCursor(); + return false; } } } updateCursor(); return true; } private void updateCursor() { if (cursorElement == null || textElement == null || textField == null) { return; } final TextRenderer textRenderer = textElement.getRenderer(TextRenderer.class); if (textRenderer == null) { return; } final String text = textField.getDisplayedText().toString(); checkBounds(text, textRenderer); calcLastVisibleIndex(textRenderer); textRenderer.setText(text); textRenderer.setSelection(textField.getSelectionStart(), textField.getSelectionEnd()); // calc cursor position final int cursorPos = textField.getCursorPosition(); // outside, move window to fit cursorPos inside [first,last] calcFirstVisibleIndex(cursorPos); calcLastVisibleIndex(textRenderer); RenderFont font = textRenderer.getFont(); final int d; if (font != null) { final String substring2 = text.substring(0, firstVisibleCharacterIndex); d = font.getWidth(substring2); } else { d = 0; } textRenderer.setxOffsetHack(-d); final String substring = text.substring(0, cursorPos); final int textWidth = textRenderer.getFont().getWidth(substring); final int cursorPixelPos = textWidth - d; final Element element = getElement(); if (element == null) { return; } cursorElement.setConstraintX(SizeValue.px(cursorPixelPos)); cursorElement.setConstraintY(SizeValue.px((getElement().getHeight() - cursorElement.getHeight()) / 2)); cursorElement.startEffect(EffectEventId.onActive, null); element.getParent().layoutElements(); } private void calcFirstVisibleIndex(final int cursorPos) { if (cursorPos > lastVisibleCharacterIndex) { final int cursorPosDelta = cursorPos - lastVisibleCharacterIndex; firstVisibleCharacterIndex += cursorPosDelta; } else if (cursorPos < firstVisibleCharacterIndex) { final int cursorPosDelta = firstVisibleCharacterIndex - cursorPos; firstVisibleCharacterIndex -= cursorPosDelta; } } private void checkBounds(@Nonnull final CharSequence text, @Nonnull final TextRenderer textRenderer) { final int textLen = text.length(); if (firstVisibleCharacterIndex > textLen) { // re position so that we show at much possible text lastVisibleCharacterIndex = textLen; RenderFont font = textRenderer.getFont(); if (font == null) { firstVisibleCharacterIndex = 0; } else { firstVisibleCharacterIndex = FontHelper.getVisibleCharactersFromEnd(font, text, fieldWidth, 1.0f); } } } private void calcLastVisibleIndex(@Nonnull final TextRenderer textRenderer) { if (textField == null) { return; } final CharSequence currentText = textField.getDisplayedText(); final RenderFont font = textRenderer.getFont(); final int textLength = currentText.length(); if (font == null) { lastVisibleCharacterIndex = textLength; } else { if (firstVisibleCharacterIndex < textLength) { final CharSequence textToCheck = currentText.subSequence(firstVisibleCharacterIndex, textLength); final int lengthFitting = FontHelper.getVisibleCharactersFromStart(font, textToCheck, fieldWidth, 1.0f); lastVisibleCharacterIndex = lengthFitting + firstVisibleCharacterIndex; } else { lastVisibleCharacterIndex = firstVisibleCharacterIndex; } } } @Override public void onFocus(final boolean getFocus) { if (cursorElement != null) { super.onFocus(getFocus); if (getFocus) { cursorElement.startEffect(EffectEventId.onCustom); } else { cursorElement.stopEffect(EffectEventId.onCustom); } updateCursor(); } } @Nonnull @Override public String getText() { return getRealText(); } @Nonnull @Override public String getRealText() { if (textField == null) { return ""; } else { return textField.getRealText().toString(); } } @Nonnull @Override public String getDisplayedText() { if (textField == null) { return ""; } else { return textField.getDisplayedText().toString(); } } @Override public void setText(@Nonnull final CharSequence text) { final CharSequence realText; if (nifty == null) { log.warning("Nifty instance is not set, binding did not run yet. Special value replacing skipped."); realText = text; } else { realText = nifty.specialValuesReplace(text.toString()); } if (textField != null) { textField.setText(realText); } updateCursor(); } @Override public void setMaxLength(final int maxLength) { if (textField != null) { textField.setMaxLength(maxLength); } updateCursor(); } @Override public void setCursorPosition(final int position) { if (textField != null) { textField.setCursorPosition(position); } updateCursor(); } @Override public void enableInputFilter(@Nullable final TextFieldInputFilter filter) { if (textField != null) { textField.setInputFilterSingle(filter); textField.setInputFilterSequence(filter); } } @Override public void enableInputFilter(@Nullable final TextFieldInputCharFilter filter) { if (filter == null) { enableInputFilter(null); } else { if (textField != null) { textField.setInputFilterSingle(filter); textField.setInputFilterSequence(new InputCharFilterWrapper(filter)); } } } @Override public void enableInputFilter(@Nullable final TextFieldInputCharSequenceFilter filter) { if (filter == null) { enableInputFilter(null); } else { if (textField != null) { textField.setInputFilterSingle(new InputCharSequenceFilterWrapper(filter)); textField.setInputFilterSequence(filter); } } } @Override public void disableInputFilter() { enableInputFilter(null); } @Override public void enableDeleteFilter(@Nullable final TextFieldDeleteFilter filter) { if (textField != null) { textField.setDeleteFilter(filter); } } @Override public void disableDeleteFilter() { enableDeleteFilter(null); } @Override public void setFormat(@Nullable final TextFieldDisplayFormat format) { if (textField != null) { textField.setFormat(format); } } @Override public void textChangeEvent(@Nonnull final String newText) { if (nifty == null) { log.warning("Binding not done yet. Can't publish events without reference to Nifty."); } else { final Element element = getElement(); if (element != null) { String id = getElement().getId(); if (id != null) { nifty.publishEvent(id, new TextFieldChangedEvent(this, newText)); } } } } @Override public void enablePasswordChar(final char passwordChar) { setFormat(new FormatPassword(passwordChar)); updateCursor(); } @Override public void disablePasswordChar() { setFormat(null); updateCursor(); } @Override public boolean isPasswordCharEnabled() { return (textField != null ? textField.getFormat() : null) instanceof FormatPassword; } }
false
true
public boolean inputEvent(@Nonnull final NiftyInputEvent inputEvent) { if (inputEvent instanceof NiftyStandardInputEvent) { final NiftyStandardInputEvent standardInputEvent = (NiftyStandardInputEvent) inputEvent; if (textField != null) { switch (standardInputEvent) { case MoveCursorLeft: textField.cursorLeft(); break; case MoveCursorRight: textField.cursorRight(); break; case Delete: textField.delete(); break; case Backspace: textField.backspace(); break; case MoveCursorToLastPosition: textField.toLastPosition(); break; case MoveCursorToFirstPosition: textField.toFirstPosition(); break; case SelectionStart: textField.startSelecting(); break; case SelectionEnd: textField.endSelecting(); break; case Cut: textField.cut(); break; case Copy: textField.copy(); break; case Paste: textField.put(); break; case SelectAll: textField.selectAll(); break; case Character: textField.insert(standardInputEvent.getCharacter()); break; } } if (fieldElement != null && focusHandler != null) { switch (standardInputEvent) { case NextInputElement: focusHandler.getNext(fieldElement).setFocus(); break; case PrevInputElement: focusHandler.getPrev(fieldElement).setFocus(); break; } } } updateCursor(); return true; }
public boolean inputEvent(@Nonnull final NiftyInputEvent inputEvent) { if (inputEvent instanceof NiftyStandardInputEvent) { final NiftyStandardInputEvent standardInputEvent = (NiftyStandardInputEvent) inputEvent; if (textField != null) { switch (standardInputEvent) { case MoveCursorLeft: textField.cursorLeft(); break; case MoveCursorRight: textField.cursorRight(); break; case Delete: textField.delete(); break; case Backspace: textField.backspace(); break; case MoveCursorToLastPosition: textField.toLastPosition(); break; case MoveCursorToFirstPosition: textField.toFirstPosition(); break; case SelectionStart: textField.startSelecting(); break; case SelectionEnd: textField.endSelecting(); break; case Cut: textField.cut(); break; case Copy: textField.copy(); break; case Paste: textField.put(); break; case SelectAll: textField.selectAll(); break; case Character: textField.insert(standardInputEvent.getCharacter()); break; case NextInputElement: if (focusHandler != null && fieldElement != null) { focusHandler.getNext(fieldElement).setFocus(); } break; case PrevInputElement: if (focusHandler != null && fieldElement != null) { focusHandler.getPrev(fieldElement).setFocus(); } break; default: updateCursor(); return false; } } } updateCursor(); return true; }
diff --git a/sqo-oss/prototype/src/eu/sqooss/plugin/wordcount/WCParser.java b/sqo-oss/prototype/src/eu/sqooss/plugin/wordcount/WCParser.java index e52bf196..b749578c 100644 --- a/sqo-oss/prototype/src/eu/sqooss/plugin/wordcount/WCParser.java +++ b/sqo-oss/prototype/src/eu/sqooss/plugin/wordcount/WCParser.java @@ -1,39 +1,39 @@ package eu.sqooss.plugin.wordcount; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import eu.sqooss.plugin.OutputParser; /** * Parsing method for the word count plugin */ public class WCParser implements OutputParser { public HashMap<String, String> parse(InputStream is) { try { HashMap<String,String> result = new HashMap<String,String>(); BufferedReader b = new BufferedReader( - new InputStreamReader(p.getInputStream())); + new InputStreamReader(is)); String output = b.readLine(); b.close(); Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(output); if(matcher.find()) { // This is hard coded, but this plugin returns only this metric :) result.put("WC", matcher.group()); } return result; } catch (IOException e) { // TODO error logging here return null; } } }
true
true
public HashMap<String, String> parse(InputStream is) { try { HashMap<String,String> result = new HashMap<String,String>(); BufferedReader b = new BufferedReader( new InputStreamReader(p.getInputStream())); String output = b.readLine(); b.close(); Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(output); if(matcher.find()) { // This is hard coded, but this plugin returns only this metric :) result.put("WC", matcher.group()); } return result; } catch (IOException e) { // TODO error logging here return null; } }
public HashMap<String, String> parse(InputStream is) { try { HashMap<String,String> result = new HashMap<String,String>(); BufferedReader b = new BufferedReader( new InputStreamReader(is)); String output = b.readLine(); b.close(); Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(output); if(matcher.find()) { // This is hard coded, but this plugin returns only this metric :) result.put("WC", matcher.group()); } return result; } catch (IOException e) { // TODO error logging here return null; } }
diff --git a/src/main/java/com/cluedoassist/CluedoSmart.java b/src/main/java/com/cluedoassist/CluedoSmart.java index 659b6f4..8a1d4ce 100644 --- a/src/main/java/com/cluedoassist/CluedoSmart.java +++ b/src/main/java/com/cluedoassist/CluedoSmart.java @@ -1,588 +1,602 @@ /* * Copyright 2013 Victor Denisov * * This file is part of Cluedo Assistant. * * Cluedo Assistant is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Cluedo Assistant 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 Cluedo Assistant. If not, see <http://www.gnu.org/licenses/>. */ package com.cluedoassist; import java.util.*; import java.io.Serializable; import java.util.Collections; public class CluedoSmart extends CluedoDumb { static final long serialVersionUID = 1L; private Resolution[][] backupTable; private ArrayList<LogEntry> backupLog; public CluedoSmart(CardSet cs, List<String> players) { super(cs, players); try { solvePlayerHasAllCards(OUT_COL); } catch (ContradictionException e) { // no contradiction is possible in this case } } public void setCard(String asker, Card card) throws UnknownPlayerException , UnknownCardException , ContradictionException { beginTransaction(); try { super.setCard(asker, card); inferenceCycle(); } catch (UnknownPlayerException upe) { rollBackTransaction(); throw upe; } catch (UnknownCardException uce) { rollBackTransaction(); throw uce; } catch (ContradictionException ce) { rollBackTransaction(); throw ce; } commitTransaction(); } public void makeTurn(Suggestion l) throws UnknownPlayerException , UnknownCardException , ContradictionException { beginTransaction(); try { super.makeTurn(l); inferenceCycle(); } catch (UnknownPlayerException upe) { rollBackTransaction(); throw upe; } catch (UnknownCardException uce) { rollBackTransaction(); throw uce; } catch (ContradictionException ce) { rollBackTransaction(); throw ce; } commitTransaction(); } public void makeAccusation(Accusation a) throws UnknownPlayerException , UnknownCardException , ContradictionException { beginTransaction(); try { super.makeAccusation(a); inferenceCycle(); } catch (UnknownPlayerException upe) { rollBackTransaction(); throw upe; } catch (UnknownCardException uce) { rollBackTransaction(); throw uce; } catch (ContradictionException ce) { rollBackTransaction(); throw ce; } commitTransaction(); } public List<CardReply> possibleCardReplies( String replier , Card[] askedCards ) throws UnknownPlayerException , UnknownCardException { int playerNumber = playerOrd(replier); ArrayList<CardReply> result = new ArrayList<CardReply>(); if (hasNoneOf(playerNumber, askedCards)) { result.add(CardReply.NoCard()); } if (hasNonNegativeOf(playerNumber, askedCards)) { result.add(CardReply.UnknownCard()); } for (Card c : askedCards) { if (table[cardSet.ordinal(c)][playerNumber] != Resolution.Minus) { result.add(CardReply.ActualCard(c)); } } return Collections.unmodifiableList(result); } private boolean hasNoneOf(int playerNumber, Card[] cards) throws UnknownCardException { for (Card c : cards) { if (table[cardSet.ordinal(c)][playerNumber] == Resolution.Plus) { return false; } } return true; } private boolean hasNonNegativeOf(int playerNumber, Card[] cards) throws UnknownCardException { for (Card c : cards) { if (table[cardSet.ordinal(c)][playerNumber] != Resolution.Minus) { return true; } } return false; } private void beginTransaction() { backupTable = new Resolution[table.length][]; for (int i = 0; i < table.length; ++i) { backupTable[i] = new Resolution[table[i].length]; for (int j = 0; j < table[i].length; ++j) { backupTable[i][j] = table[i][j]; } } backupLog = new ArrayList<LogEntry>(log); } private void commitTransaction() { backupTable = null; backupLog = null; } private void rollBackTransaction() { table = new Resolution[backupTable.length][]; for (int i = 0; i < backupTable.length; ++i) { table[i] = new Resolution[backupTable[i].length]; for (int j = 0; j < backupTable[i].length; ++j) { table[i][j] = backupTable[i][j]; } } backupTable = null; log = new ArrayList<LogEntry>(backupLog); backupLog = null; } private boolean setPlus(int cardNumber, int playerNumber) throws ContradictionException { if (table[cardNumber][playerNumber] == Resolution.Minus) { Card card = cardSet.cards.get(cardNumber); String player = getCompartments().get(playerNumber); throw new ContradictionException("Card : " + card + ", Player : " + player + ". Expected Unknown or Plus, " + "encountered Minus."); } boolean tableModified = false; if (table[cardNumber][playerNumber] == Resolution.Unknown) { tableModified = true; } table[cardNumber][playerNumber] = Resolution.Plus; for (int i = 0; i < table[cardNumber].length; ++i) { if (i != playerNumber) { boolean setMinusValue = setMinus(cardNumber, i); tableModified = tableModified || setMinusValue; } } return tableModified; } private boolean setMinus(int cardNumber, int playerNumber) throws ContradictionException { if (table[cardNumber][playerNumber] == Resolution.Plus) { Card card = cardSet.cards.get(cardNumber); String player = getCompartments().get(playerNumber); throw new ContradictionException("Card : " + card + ", Player : " + player + ". Expected Unknown or Minus, " + "encountered Plus."); } boolean tableModified = false; if (table[cardNumber][playerNumber] == Resolution.Unknown) { tableModified = true; } table[cardNumber][playerNumber] = Resolution.Minus; return tableModified; } private boolean processLog() throws UnknownPlayerException , UnknownCardException , ContradictionException { boolean tableModified = false; for (LogEntry logEntry : log) { if (logEntry instanceof Accusation) { boolean doAccusation = solveAskerHasNoCardsFromAccusation((Accusation)logEntry); boolean solveAccusationValue = solveUnsuccessfulAccusation((Accusation)logEntry); tableModified = tableModified || solveAccusationValue; tableModified = tableModified || doAccusation; } else if (logEntry instanceof SetCard) { SetCard s = (SetCard) logEntry; int playerNumber = playerOrd(s.player); int cardNumber = cardSet.ordinal(s.card); setPlus(cardNumber, playerNumber); } else { Suggestion suggestion = (Suggestion) logEntry; boolean solveRepliersHaveValue = solveRepliersHave(suggestion); boolean solveReplierHasNoCardsValue = solveReplierHasNoCards(suggestion); boolean solveOnlyOneUnknownValue = solveOnlyOneUnknown(suggestion); boolean solveThreeCardsReplied = solveThreeCardsReplied(suggestion); tableModified = tableModified || solveRepliersHaveValue; tableModified = tableModified || solveReplierHasNoCardsValue; tableModified = tableModified || solveOnlyOneUnknownValue; tableModified = tableModified || solveThreeCardsReplied; } } return tableModified; } private boolean rectifyTable() throws ContradictionException { boolean tableModified = false; for (int i = 0; i < table[0].length; ++i) { boolean solvePlayerHasAllCardsValue = solvePlayerHasAllCards(i); tableModified = tableModified || solvePlayerHasAllCardsValue; } for (int i = 0; i < table[0].length; ++i) { boolean solveCountOfNonnegativeEqualsCardCountValue = solveCountOfNonnegativeEqualsCardCount(i); tableModified = tableModified || solveCountOfNonnegativeEqualsCardCountValue; } for (int i = 0; i < table.length; ++i) { boolean solveLineOneNonNegativeValue = solveLineOneNonNegative(i); tableModified = tableModified || solveLineOneNonNegativeValue; } boolean solveEnvHasOneUnknownCardInGroup06Value = - solveEnvHasOneUnknownCardInGroup(0, 6); + solveEnvHasOneUnknownCardInGroup + ( 0 + , cardSet.suspectCount); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup06Value; boolean solveEnvHasOneUnknownCardInGroup612Value = - solveEnvHasOneUnknownCardInGroup(6, 12); + solveEnvHasOneUnknownCardInGroup + ( cardSet.suspectCount + , cardSet.suspectCount + + cardSet.weaponCount); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup612Value; boolean solveEnvHasOneUnknownCardInGroup12LengthValue = - solveEnvHasOneUnknownCardInGroup(12, table.length); + solveEnvHasOneUnknownCardInGroup + ( cardSet.suspectCount + + cardSet.weaponCount + , table.length); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup12LengthValue; - boolean solvePlusInGroup06Value = solvePlusInGroup(0, 6); + boolean solvePlusInGroup06Value = solvePlusInGroup( 0 + , cardSet.suspectCount); tableModified = tableModified || solvePlusInGroup06Value; - boolean solvePlusInGroup612Value = solvePlusInGroup(6, 12); + boolean solvePlusInGroup612Value = solvePlusInGroup( cardSet.suspectCount + , cardSet.suspectCount + + cardSet.weaponCount); tableModified = tableModified || solvePlusInGroup612Value; - boolean solvePlusInGroup12LengthValue = solvePlusInGroup(12, table.length); + boolean solvePlusInGroup12LengthValue = solvePlusInGroup + ( cardSet.suspectCount + + cardSet.weaponCount + , table.length); tableModified = tableModified || solvePlusInGroup12LengthValue; return tableModified; } private boolean solveAskerHasNoCardsFromAccusation(Accusation a) throws UnknownPlayerException , UnknownCardException , ContradictionException { int playerNumber = playerOrd(a.asker); boolean tableModified = false; for (Card c : a.cards) { int cardNumber = cardSet.ordinal(c); boolean result = setMinus(cardNumber, playerNumber); tableModified = tableModified || result; } return tableModified; } private boolean solveUnsuccessfulAccusation(Accusation a) throws UnknownCardException , ContradictionException { if (plusCountOfPlayer(ENV_COL) == 2) { for (Card c : a.cards) { int cardNumber = cardSet.ordinal(c); if (table[cardNumber][ENV_COL] == Resolution.Unknown) { setMinus(cardNumber, ENV_COL); return true; } } } return false; } private void inferenceCycle() throws UnknownPlayerException , UnknownCardException , ContradictionException { for (;;) { boolean tableModified = false; boolean processLogValue = processLog(); tableModified = tableModified || processLogValue; boolean rectifyTableValue = rectifyTable(); verifyEveryLineHasQuestionOrPlus(); tableModified = tableModified || rectifyTableValue; if (!tableModified) { break; } } } private void verifyEveryLineHasQuestionOrPlus() throws ContradictionException { for (int i = 0; i < table.length; ++i) { verifyLineHasQuestionOrPlus(i); } } private void verifyLineHasQuestionOrPlus(int lineNum) throws ContradictionException { for (int i = 0; i < table[lineNum].length; ++i) { if (table[lineNum][i] != Resolution.Minus) { return; } } throw new ContradictionException("Line has minuses only"); } public void replaceLog(List<LogEntry> l) throws UnknownPlayerException , UnknownCardException , ContradictionException { beginTransaction(); try { super.replaceLog(l); inferenceCycle(); } catch (UnknownPlayerException upe) { rollBackTransaction(); throw upe; } catch (UnknownCardException uce) { rollBackTransaction(); throw uce; } catch (ContradictionException ce) { rollBackTransaction(); throw ce; } commitTransaction(); } /* Processes the situation when replier shows known card. */ private boolean solveRepliersHave(Suggestion le) throws UnknownPlayerException , UnknownCardException , ContradictionException { boolean tableModified = false; for (Reply r : le.replies) { int playerNumber = playerOrd(r.replier); int cardNumber = r.cardReply.ordinal(cardSet); if (cardNumber < 0) { continue; } boolean setPlusValue = setPlus(cardNumber, playerNumber); tableModified = tableModified || setPlusValue; } return tableModified; } /* Processes the situation when replier shows no cards. */ private boolean solveReplierHasNoCards(Suggestion le) throws UnknownPlayerException , UnknownCardException , ContradictionException { boolean tableModified = false; for (Reply r : le.replies) { int playerNumber = playerOrd(r.replier); if (r.cardReply.isNoCard()) { for (Card c : le.askedCards) { int cardNumber = cardSet.ordinal(c); boolean setMinusValue = setMinus(cardNumber, playerNumber); tableModified = tableModified || setMinusValue; } } } return tableModified; } private boolean solveOnlyOneUnknown(Suggestion le) throws UnknownPlayerException , UnknownCardException , ContradictionException { boolean tableModified = false; for (Reply r : le.replies) { int playerNumber = playerOrd(r.replier); if (r.cardReply.isUnknown()) { List<Card> s = allPlusCards(playerNumber); s.addAll(allUnknownCards(playerNumber)); s.retainAll(le.askedCards); if (s.size() == 1) { int cardNumber = cardSet.ordinal(s.get(0)); boolean setPlusValue = setPlus(cardNumber, playerNumber); tableModified = tableModified || setPlusValue; } } } return tableModified; } private boolean solveThreeCardsReplied(Suggestion le) throws UnknownPlayerException , UnknownCardException , ContradictionException { boolean tableModified = false; int countCardReplies = 0; for (Reply r : le.replies) { if (!r.cardReply.isNoCard()) { ++countCardReplies; } } if (countCardReplies == 3) { for (Card c : le.askedCards) { int cardNumber = cardSet.ordinal(c); boolean value = setMinus(cardNumber, ENV_COL); tableModified = tableModified || value; } } return tableModified; } private int plusCountOfPlayer(int playerNumber) { int count = 0; for (int i = 0; i < cardSet.cardCount; ++i) { if (table[i][playerNumber] == Resolution.Plus) { ++count; } } return count; } private int nonNegativeCountOfCard(int cardNumber) { int nonNegativeCount = 0; for (int i = 0; i < table[cardNumber].length; ++i) { if (table[cardNumber][i] != Resolution.Minus) { ++nonNegativeCount; } } return nonNegativeCount; } private int nonNegativeCountOfPlayer(int playerNumber) { int nonNegativeCount = 0; for (int i = 0; i < table.length; ++i) { if (table[i][playerNumber] != Resolution.Minus) { ++nonNegativeCount; } } return nonNegativeCount; } private boolean solveLineOneNonNegative(int cardNumber) throws ContradictionException { boolean tableModified = false; if (nonNegativeCountOfCard(cardNumber) == 1) { for (int i = 0; i < table[cardNumber].length; ++i) { if (table[cardNumber][i] == Resolution.Unknown) { boolean setPlusValue = setPlus(cardNumber, i); tableModified = tableModified || setPlusValue; } } } return tableModified; } private boolean solveCountOfNonnegativeEqualsCardCount(int playerNumber) throws ContradictionException { boolean tableModified = false; if (nonNegativeCountOfPlayer(playerNumber) == cardCountPerPlayer[playerNumber]) { for (int i = 0; i < table.length; ++i) { if (table[i][playerNumber] == Resolution.Unknown) { setPlus(i, playerNumber); tableModified = true; } } } return tableModified; } private boolean solvePlusInGroup(int l, int r) throws ContradictionException { boolean tableModified = false; int pluses = 0; for (int i = l; i < r; ++i) { if (table[i][ENV_COL] == Resolution.Plus) { ++pluses; } } if (pluses == 1) { for (int i = l; i < r; ++i) { if (table[i][ENV_COL] != Resolution.Plus) { boolean setMinusValue = setMinus(i, ENV_COL); tableModified = tableModified || setMinusValue; } } } return tableModified; } private boolean solveEnvHasOneUnknownCardInGroup(int l, int r) throws ContradictionException { boolean tableModified = false; int minuses = 0; for (int i = l; i < r; ++i) { if (table[i][ENV_COL] == Resolution.Minus) { ++minuses; } } if (minuses == (r - l - 1)) { for (int i = l; i < r; ++i) { if (table[i][ENV_COL] != Resolution.Minus) { boolean setPlusValue = setPlus(i, ENV_COL); tableModified = tableModified || setPlusValue; } } } return tableModified; } private boolean solvePlayerHasAllCards(int playerNumber) throws ContradictionException { boolean tableModified = false; if (plusCountOfPlayer(playerNumber) == cardCountPerPlayer[playerNumber]) { for (int i = 0; i < cardSet.cardCount; ++i) { if (table[i][playerNumber] == Resolution.Unknown) { tableModified = true; setMinus(i, playerNumber); } } } return tableModified; } private List<Card> allPlusCards(int playerNumber) { ArrayList<Card> result = new ArrayList<Card>(); for (int i = 0; i < cardSet.cardCount; ++i) { if (table[i][playerNumber] == Resolution.Plus) { result.add(cardSet.cards.get(i)); } } return result; } private List<Card> allUnknownCards(int playerNumber) { ArrayList<Card> result = new ArrayList<Card>(); for (int i = 0; i < cardSet.cardCount; ++i) { if (table[i][playerNumber] == Resolution.Unknown) { result.add(cardSet.cards.get(i)); } } return result; } }
false
true
private boolean rectifyTable() throws ContradictionException { boolean tableModified = false; for (int i = 0; i < table[0].length; ++i) { boolean solvePlayerHasAllCardsValue = solvePlayerHasAllCards(i); tableModified = tableModified || solvePlayerHasAllCardsValue; } for (int i = 0; i < table[0].length; ++i) { boolean solveCountOfNonnegativeEqualsCardCountValue = solveCountOfNonnegativeEqualsCardCount(i); tableModified = tableModified || solveCountOfNonnegativeEqualsCardCountValue; } for (int i = 0; i < table.length; ++i) { boolean solveLineOneNonNegativeValue = solveLineOneNonNegative(i); tableModified = tableModified || solveLineOneNonNegativeValue; } boolean solveEnvHasOneUnknownCardInGroup06Value = solveEnvHasOneUnknownCardInGroup(0, 6); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup06Value; boolean solveEnvHasOneUnknownCardInGroup612Value = solveEnvHasOneUnknownCardInGroup(6, 12); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup612Value; boolean solveEnvHasOneUnknownCardInGroup12LengthValue = solveEnvHasOneUnknownCardInGroup(12, table.length); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup12LengthValue; boolean solvePlusInGroup06Value = solvePlusInGroup(0, 6); tableModified = tableModified || solvePlusInGroup06Value; boolean solvePlusInGroup612Value = solvePlusInGroup(6, 12); tableModified = tableModified || solvePlusInGroup612Value; boolean solvePlusInGroup12LengthValue = solvePlusInGroup(12, table.length); tableModified = tableModified || solvePlusInGroup12LengthValue; return tableModified; }
private boolean rectifyTable() throws ContradictionException { boolean tableModified = false; for (int i = 0; i < table[0].length; ++i) { boolean solvePlayerHasAllCardsValue = solvePlayerHasAllCards(i); tableModified = tableModified || solvePlayerHasAllCardsValue; } for (int i = 0; i < table[0].length; ++i) { boolean solveCountOfNonnegativeEqualsCardCountValue = solveCountOfNonnegativeEqualsCardCount(i); tableModified = tableModified || solveCountOfNonnegativeEqualsCardCountValue; } for (int i = 0; i < table.length; ++i) { boolean solveLineOneNonNegativeValue = solveLineOneNonNegative(i); tableModified = tableModified || solveLineOneNonNegativeValue; } boolean solveEnvHasOneUnknownCardInGroup06Value = solveEnvHasOneUnknownCardInGroup ( 0 , cardSet.suspectCount); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup06Value; boolean solveEnvHasOneUnknownCardInGroup612Value = solveEnvHasOneUnknownCardInGroup ( cardSet.suspectCount , cardSet.suspectCount + cardSet.weaponCount); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup612Value; boolean solveEnvHasOneUnknownCardInGroup12LengthValue = solveEnvHasOneUnknownCardInGroup ( cardSet.suspectCount + cardSet.weaponCount , table.length); tableModified = tableModified || solveEnvHasOneUnknownCardInGroup12LengthValue; boolean solvePlusInGroup06Value = solvePlusInGroup( 0 , cardSet.suspectCount); tableModified = tableModified || solvePlusInGroup06Value; boolean solvePlusInGroup612Value = solvePlusInGroup( cardSet.suspectCount , cardSet.suspectCount + cardSet.weaponCount); tableModified = tableModified || solvePlusInGroup612Value; boolean solvePlusInGroup12LengthValue = solvePlusInGroup ( cardSet.suspectCount + cardSet.weaponCount , table.length); tableModified = tableModified || solvePlusInGroup12LengthValue; return tableModified; }
diff --git a/src/com/pokebros/android/pokemononline/NetworkService.java b/src/com/pokebros/android/pokemononline/NetworkService.java index 6cdce1ba..8011ff90 100644 --- a/src/com/pokebros/android/pokemononline/NetworkService.java +++ b/src/com/pokebros/android/pokemononline/NetworkService.java @@ -1,1041 +1,1041 @@ package com.pokebros.android.pokemononline; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.ParseException; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.media.MediaPlayer; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import android.text.Html; import android.util.Log; import android.widget.Toast; import com.pokebros.android.pokemononline.battle.Battle; import com.pokebros.android.pokemononline.battle.BattleConf; import com.pokebros.android.pokemononline.battle.BattleDesc; import com.pokebros.android.pokemononline.battle.SpectatingBattle; import com.pokebros.android.pokemononline.player.FullPlayerInfo; import com.pokebros.android.pokemononline.player.PlayerInfo; import com.pokebros.android.pokemononline.pms.PrivateMessageActivity; import com.pokebros.android.pokemononline.pms.PrivateMessageList; import com.pokebros.android.pokemononline.poke.ShallowBattlePoke; import com.pokebros.android.utilities.StringUtilities; public class NetworkService extends Service { static final String TAG = "Network Service"; final static String pkgName = "com.pokebros.android.pokemononline"; private final IBinder binder = new LocalBinder(); //public Channel currentChannel = null; public LinkedList<Channel> joinedChannels = new LinkedList<Channel>(); Thread sThread, rThread; PokeClientSocket socket = null; boolean findingBattle = false; public ChatActivity chatActivity = null; public LinkedList<IncomingChallenge> challenges = new LinkedList<IncomingChallenge>(); public boolean askedForPass = false; private String salt = null; public boolean failedConnect = false; public DataBaseHelper db; public String serverName = "Not Connected"; public final ProtocolVersion version = new ProtocolVersion(); public boolean serverSupportsZipCompression = false; @SuppressWarnings("unused") private byte []reconnectSecret; /** * Are we engaged in a battle? * @return True if we are at least in one battle */ public boolean isBattling() { return !activeBattles.isEmpty(); } /** * Are we engaged in a battle with that particular battle ID? * @param battleId the battle ID * @return true if we are a player of the battle with the battle ID */ public boolean isBattling(int battleId) { return activeBattles.containsKey(battleId); } private Battle activeBattle(int battleId) { return activeBattles.get(battleId); } private FullPlayerInfo meLoginPlayer; public PlayerInfo mePlayer; public Hashtable<Integer, Battle> activeBattles = new Hashtable<Integer, Battle>(); public Hashtable<Integer, SpectatingBattle> spectatedBattles = new Hashtable<Integer, SpectatingBattle>(); Tier superTier = new Tier(); public int myid = -1; public PlayerInfo me = new PlayerInfo(); protected Hashtable<Integer, Channel> channels = new Hashtable<Integer, Channel>(); public Hashtable<Integer, PlayerInfo> players = new Hashtable<Integer, PlayerInfo>(); public Hashtable<Integer, BattleDesc> battles = new Hashtable<Integer, BattleDesc>(); static public HashSet<Integer> pmedPlayers = new HashSet<Integer>(); public PrivateMessageList pms = new PrivateMessageList(me); public class LocalBinder extends Binder { public NetworkService getService() { return NetworkService.this; } } /** * Is the player in any of the same channels as us? * @param pid the id of the player we are interested in * @return true if the player shares a channel with us, false otherwise */ public boolean isOnAnyChannel(int pid) { for (Channel c: channels.values()) { if (c.players.contains(pid)) { return true; } } return false; } /** * Called by a channel when a player leaves. If the player is not on any channel * and there's no special circumstances (as in PM), the player will get removed * @param pid The id of the player that left */ public void onPlayerLeaveChannel(int pid) { if (!isOnAnyChannel(pid) && !pmedPlayers.contains(pid)) { removePlayer(pid); } } public void addBattle(int battleid, BattleDesc desc) { battles.put(battleid, desc); if (players.containsKey(desc.p1)) { players.get(desc.p1).addBattle(battleid); } if (players.containsKey(desc.p2)) { players.get(desc.p2).addBattle(battleid); } } /** * Removes a battle from memory * @param battleID the battle id of the battle to remove */ private void removeBattle(int battleID) { if (!battles.containsKey(battleID)) { return; } BattleDesc battle = battles.get(battleID); if (hasPlayer(battle.p1)) { players.get(battle.p1).removeBattle(battleID); } if (hasPlayer(battle.p2)) { players.get(battle.p2).removeBattle(battleID); } } /** * Returns a list of all the battles fought or spectated * @return the battles fought/spectated */ public Collection<SpectatingBattle> getBattles() { LinkedList<SpectatingBattle> ret = new LinkedList<SpectatingBattle>(); ret.addAll(activeBattles.values()); ret.addAll(spectatedBattles.values()); return ret; } /** * Checks all battles spectated or fought and removes/destroys the ones * that are finished */ public void checkBattlesToEnd() { for (SpectatingBattle battle: getBattles()) { if (battle.gotEnd) { closeBattle(battle.bID); } } } /** * Removes a battle spectated/fought from memory and destroys it * @param bID The id of the battle to remove */ public void closeBattle(int bID) { if (isBattling(bID)) { activeBattles.remove(bID).destroy(); } if (spectatedBattles.containsKey(bID)) { spectatedBattles.remove(bID).destroy(); } /* Remove the battle notification */ NotificationManager mNotificationManager = getNotificationManager(); mNotificationManager.cancel("battle", bID); } /** * Does the player exist in memory * @param pid the id of the player we're interested in * @return true if the player is in memory, or false */ public boolean hasPlayer(int pid) { return players.containsKey(pid); } /** * Checks if the players of the battle are online, and remove the battle from memory if not * @param battleid the id of the battle to check */ private void testRemoveBattle(Integer battleid) { BattleDesc battle = battles.get(battleid); if (battle != null) { if (!players.containsKey(battle.p1) && !players.containsKey(battle.p2)) { battles.remove(battle); } } } /** * Gets the name of a player or "???" if the player couldn't be found * @param playerId id of the player we're interested in * @return name of the player or "???" if not found */ public String playerName(int playerId) { PlayerInfo player = players.get(playerId); if (player == null) { return "???"; } else { return player.nick(); } } /** * Removes a player from memory * @param pid The id of the player to remove */ public void removePlayer(int pid) { PlayerInfo player = players.remove(pid); if (pmedPlayers.contains(pid)) { //TODO: close the PM? pmedPlayers.remove(pid); } if (player != null) { for(Integer battleid: player.battles) { testRemoveBattle(battleid); } } } @Override // This is *NOT* called every time someone binds to us, I don't really know why // but onServiceConnected is correctly called in the activity sooo.... public IBinder onBind(Intent intent) { return binder; } @Override // This is called once public void onCreate() { db = new DataBaseHelper(NetworkService.this); super.onCreate(); } @Override public void onDestroy() { // XXX TODO be more graceful Log.d(TAG, "NETWORK SERVICE DESTROYED; EXPECT BAD THINGS TO HAPPEN"); for(SpectatingBattle battle : getBattles()) { closeBattle(battle.bID); } } public void connect(final String ip, final int port) { // XXX This should probably have a timeout new Thread(new Runnable() { public void run() { try { socket = new PokeClientSocket(ip, port); } catch (IOException e) { failedConnect = true; if(chatActivity != null) { chatActivity.notifyFailedConnection(); } return; } //socket.sendMessage(meLoginPlayer.serializeBytes(), Command.Login); Baos loginCmd = new Baos(); loginCmd.putBaos(version); //Protocol version /* Network Flags: hasClientType, hasVersionNumber, hasReconnect, hasDefaultChannel, hasAdditionalChannels, hasColor, hasTrainerInfo, hasNewTeam, hasEventSpecification, hasPluginList. */ loginCmd.putFlags(new boolean []{true,true}); //Network flags loginCmd.putString("android"); short versionCode; try { versionCode = (short)getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; } catch (NameNotFoundException e1) { versionCode = 0; } loginCmd.putShort(versionCode); loginCmd.putString(meLoginPlayer.nick()); /* Data Flags: supportsZipCompression, isLadderEnabled, wantsIdsWithMessages, isIdle */ loginCmd.putFlags(new boolean []{false,true,true}); socket.sendMessage(loginCmd, Command.Login); while(socket.isConnected()) { try { // Get some data from the wire socket.recvMessagePoll(); } catch (IOException e) { // Disconnected break; } catch (ParseException e) { // Got message that overflowed length from server. // No way to recover. // TODO die completely break; } Baos tmp; // Handle any messages that completed while ((tmp = socket.getMsg()) != null) { Bais msg = new Bais(tmp.toByteArray()); handleMsg(msg); } /* Do not use too much CPU */ try { Thread.sleep(50); } catch (InterruptedException e) { // Do nothing } } } }).start(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); Bundle bundle = null; if (intent != null) // Intent can be null if service restarts after being killed // XXX We probably don't handle such restarts very gracefully bundle = intent.getExtras(); if (bundle != null && bundle.containsKey("loginPlayer")) { meLoginPlayer = new FullPlayerInfo(new Bais(bundle.getByteArray("loginPlayer"))); me.setTo(new PlayerInfo (meLoginPlayer)); } if (bundle != null && bundle.containsKey("ip")) connect(bundle.getString("ip"), bundle.getShort("port")); return START_STICKY; } public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; Log.d(TAG, "Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel:{ Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } serverName = msg.readString(); if (chatActivity != null) { chatActivity.updateTitle(); } break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } me.setTo(new PlayerInfo(msg)); myid = me.id; int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(myid, me); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); PlayerInfo oldPlayer = players.get(p.id); players.put(p.id, p); if (oldPlayer != null) { p.battles = oldPlayer.battles; if (chatActivity != null) { /* Updates the player in the adapter memory */ chatActivity.updatePlayer(p, oldPlayer); } } /* Updates self player */ if (p.id == myid) { me.setTo(p); } } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + message); } else { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + StringUtilities.escapeHtml((String)message)); } } else { - String str = StringUtilities.escapeHtml((String)message); if (isHtml) { - message = Html.fromHtml(str); + message = Html.fromHtml((String)message); } else { + String str = StringUtilities.escapeHtml((String)message); int index = str.indexOf(':'); if (str.startsWith("*** ")) { message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>"); } else if (index != -1) { String firstPart = str.substring(0, index); String secondPart; try { secondPart = str.substring(index+2); } catch (IndexOutOfBoundsException ex) { secondPart = ""; } CharSequence color = "#318739"; if (firstPart.equals("Welcome Message")) { color = "blue"; } else if (firstPart.equals("~~Server~~")) { color = "orange"; } message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart + ": </b></font>" + secondPart); } } } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } case BattleList: { msg.readInt(); //channel, but irrelevant int numBattles = msg.readInt(); for (; numBattles > 0; numBattles--) { int battleId = msg.readInt(); //byte mode = msg.readByte(); /* protocol is messed up */ int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } break; } case ChannelBattle: { msg.readInt(); //channel, but irrelevant int battleId = msg.readInt(); //byte mode = msg.readByte(); int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } /* case JoinChannel: case LeaveChannel: // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); msg.readByte(); // battle mode int id1 = msg.readInt(); int id2 = msg.readInt(); //Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) { if (isBattling(battleID)) { //TODO: notification on win/lose // if (mePlayer.id == id1 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You won!"); // } else if (mePlayer.id == id2 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You lost!"); // } else if (battleDesc == 2) { // showNotification(ChatActivity.class, "Chat", "You tied!"); // } } if (battleDesc < 2) { joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] + StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>")); } if (battleDesc == 0 || battleDesc == 3) { closeBattle(battleID); } } removeBattle(battleID); break; } case SendPM: { int playerId = msg.readInt(); String message = msg.readString(); dealWithPM(playerId, message); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } */ case BattleMessage: { int battleId = msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (isBattling(battleId)) { activeBattle(battleId).receiveCommand(msg); } break; } case EngageBattle: { int battleId = msg.readInt(); Bais flags = msg.readFlags(); byte mode = msg.readByte(); int p1 = msg.readInt(); int p2 = msg.readInt(); addBattle(battleId, new BattleDesc(p1, p2, mode)); if(flags.readBool()) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle Battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), myid, battleId, this); activeBattles.put(battleId, battle); joinedChannels.peek().writeToHist("Battle between " + playerName(p1) + " and " + playerName(p2) + " started!"); Intent intent; intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); findingBattle = false; showBattleNotification("Battle", battleId, conf); } if (chatActivity != null) { chatActivity.updatePlayer(players.get(p1), players.get(p1)); chatActivity.updatePlayer(players.get(p2), players.get(p2)); } break; } case SpectateBattle: { Bais flags = msg.readFlags(); int battleId = msg.readInt(); if (flags.readBool()) { if (spectatedBattles.contains(battleId)) { Log.e(TAG, "Already watching battle " + battleId); return; } BattleConf conf = new BattleConf(msg); PlayerInfo p1 = players.get(conf.id(0)); PlayerInfo p2 = players.get(conf.id(1)); SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this); spectatedBattles.put(battleId, battle); Intent intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); showBattleNotification("Spectated Battle", battleId, conf); } else { closeBattle(battleId); } break; } case SpectateBattleMessage: { int battleId = msg.readInt(); msg.readInt(); // discard the size, unneeded if (spectatedBattles.containsKey(battleId)) { spectatedBattles.get(battleId).receiveCommand(msg); } break; } case AskForPass: { salt = msg.readString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readString(), this)); break; } default: { System.out.println("Unimplented message"); } } for(SpectatingBattle battle : getBattles()) { if (battle.activity != null && battle.histDelta.length() != 0) { battle.activity.updateBattleInfo(false); } } if (chatActivity != null && chatActivity.currentChannel() != null) chatActivity.updateChat(); } /** * Creates a PM window with the other guy * @param playerId the other guy's id */ public void createPM(int playerId) { pms.createPM(players.get(playerId)); } private void dealWithPM(int playerId, String message) { pmedPlayers.add(playerId); createPM(playerId); pms.newMessage(players.get(playerId), message); showPMNotification(playerId); } private void showPMNotification(int playerId) { PlayerInfo p = players.get(playerId); if (p == null) { p = new PlayerInfo(); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_action_mail) .setContentTitle("PM - Pokemon Online") .setContentText("New message from " + p.nick()) .setOngoing(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, PrivateMessageActivity.class); resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); resultIntent.putExtra("playerId", playerId); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(ChatActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); //PendingIntent resultPendingIntent = PendingIntent.getActivity(this, battleId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = getNotificationManager(); // mId allows you to update the notification later on. mNotificationManager.notify("pm", 0, mBuilder.build()); } private void showBattleNotification(String title, int battleId, BattleConf conf) { PlayerInfo p1 = players.get(conf.id(0)); PlayerInfo p2 = players.get(conf.id(1)); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setContentTitle(title) .setContentText(p1.nick() + " vs " + p2.nick()) .setOngoing(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, BattleActivity.class); resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); resultIntent.putExtra("battleId", battleId); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(ChatActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( battleId, PendingIntent.FLAG_UPDATE_CURRENT ); //PendingIntent resultPendingIntent = PendingIntent.getActivity(this, battleId, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = getNotificationManager(); // mId allows you to update the notification later on. mNotificationManager.notify("battle", battleId, mBuilder.build()); } NotificationManager getNotificationManager() { return (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } public void sendPass(String s) { askedForPass = false; MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); Baos hashPass = new Baos(); hashPass.putBytes(md5.digest(mashBytes(toHex(md5.digest(s.getBytes("ISO-8859-1"))).getBytes("ISO-8859-1"), salt.getBytes("ISO-8859-1")))); socket.sendMessage(hashPass, Command.AskForPass); } catch (NoSuchAlgorithmException nsae) { System.out.println("Attempting authentication threw an exception: " + nsae); } catch (UnsupportedEncodingException uee) { System.out.println("Attempting authentication threw an exception: " + uee); } } private byte[] mashBytes(final byte[] a, final byte[] b) { byte[] ret = new byte[a.length + b.length]; System.arraycopy(a, 0, ret, 0, a.length); System.arraycopy(b, 0, ret, a.length, b.length); return ret; } private String toHex(byte[] b) { String ret = new BigInteger(1, b).toString(16); while (ret.length() < 32) ret = "0" + ret; return ret; } protected void addChannel(String chanName, int chanId) { Channel c = new Channel(chanId, chanName, this); channels.put(chanId, c); if(chatActivity != null) chatActivity.addChannel(c); } public void playCry(SpectatingBattle battle, ShallowBattlePoke poke) { new Thread(new CryPlayer(poke, battle)).start(); } class CryPlayer implements Runnable { ShallowBattlePoke poke; SpectatingBattle battle; public CryPlayer(ShallowBattlePoke poke, SpectatingBattle battle) { this.poke = poke; this.battle = battle; } public void run() { int resID = getResources().getIdentifier("p" + poke.uID.pokeNum, "raw", pkgName); if (resID != 0) { MediaPlayer cryPlayer = MediaPlayer.create(NetworkService.this, resID); cryPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { synchronized (mp) { mp.notify(); } } }); synchronized (cryPlayer) { cryPlayer.start(); try { cryPlayer.wait(10000); } catch (InterruptedException e) {} } cryPlayer.release(); synchronized (battle) { battle.notify(); } cryPlayer = null; } } } public void disconnect() { if (socket != null && socket.isConnected()) { socket.close(); } this.stopForeground(true); this.stopSelf(); } public PlayerInfo getPlayerByName(String playerName) { Enumeration<Integer> e = players.keys(); while(e.hasMoreElements()) { PlayerInfo info = players.get(e.nextElement()); if (info.nick().equals(playerName)) return info; } return null; } public BattleDesc battle(Integer battleid) { return battles.get(battleid); } /** * Tells the server we're not spectating a battle anymore, and close the appropriate * spectating window * @param bID the battle we're not watching anymore */ public void stopWatching(int bID) { socket.sendMessage(new Baos().putInt(bID).putBool(false), Command.SpectateBattle); closeBattle(bID); } /** * Sends a private message to a user * @param id Id of the user dest * @param message message to send */ public void sendPM(int id, String message) { Baos bb = new Baos(); bb.putInt(id); bb.putString(message); socket.sendMessage(bb, Command.SendPM); pmedPlayers.add(id); } }
false
true
public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; Log.d(TAG, "Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel:{ Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } serverName = msg.readString(); if (chatActivity != null) { chatActivity.updateTitle(); } break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } me.setTo(new PlayerInfo(msg)); myid = me.id; int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(myid, me); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); PlayerInfo oldPlayer = players.get(p.id); players.put(p.id, p); if (oldPlayer != null) { p.battles = oldPlayer.battles; if (chatActivity != null) { /* Updates the player in the adapter memory */ chatActivity.updatePlayer(p, oldPlayer); } } /* Updates self player */ if (p.id == myid) { me.setTo(p); } } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + message); } else { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + StringUtilities.escapeHtml((String)message)); } } else { String str = StringUtilities.escapeHtml((String)message); if (isHtml) { message = Html.fromHtml(str); } else { int index = str.indexOf(':'); if (str.startsWith("*** ")) { message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>"); } else if (index != -1) { String firstPart = str.substring(0, index); String secondPart; try { secondPart = str.substring(index+2); } catch (IndexOutOfBoundsException ex) { secondPart = ""; } CharSequence color = "#318739"; if (firstPart.equals("Welcome Message")) { color = "blue"; } else if (firstPart.equals("~~Server~~")) { color = "orange"; } message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart + ": </b></font>" + secondPart); } } } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } case BattleList: { msg.readInt(); //channel, but irrelevant int numBattles = msg.readInt(); for (; numBattles > 0; numBattles--) { int battleId = msg.readInt(); //byte mode = msg.readByte(); /* protocol is messed up */ int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } break; } case ChannelBattle: { msg.readInt(); //channel, but irrelevant int battleId = msg.readInt(); //byte mode = msg.readByte(); int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } /* case JoinChannel: case LeaveChannel: // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); msg.readByte(); // battle mode int id1 = msg.readInt(); int id2 = msg.readInt(); //Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) { if (isBattling(battleID)) { //TODO: notification on win/lose // if (mePlayer.id == id1 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You won!"); // } else if (mePlayer.id == id2 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You lost!"); // } else if (battleDesc == 2) { // showNotification(ChatActivity.class, "Chat", "You tied!"); // } } if (battleDesc < 2) { joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] + StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>")); } if (battleDesc == 0 || battleDesc == 3) { closeBattle(battleID); } } removeBattle(battleID); break; } case SendPM: { int playerId = msg.readInt(); String message = msg.readString(); dealWithPM(playerId, message); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } */ case BattleMessage: { int battleId = msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (isBattling(battleId)) { activeBattle(battleId).receiveCommand(msg); } break; } case EngageBattle: { int battleId = msg.readInt(); Bais flags = msg.readFlags(); byte mode = msg.readByte(); int p1 = msg.readInt(); int p2 = msg.readInt(); addBattle(battleId, new BattleDesc(p1, p2, mode)); if(flags.readBool()) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle Battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), myid, battleId, this); activeBattles.put(battleId, battle); joinedChannels.peek().writeToHist("Battle between " + playerName(p1) + " and " + playerName(p2) + " started!"); Intent intent; intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); findingBattle = false; showBattleNotification("Battle", battleId, conf); } if (chatActivity != null) { chatActivity.updatePlayer(players.get(p1), players.get(p1)); chatActivity.updatePlayer(players.get(p2), players.get(p2)); } break; } case SpectateBattle: { Bais flags = msg.readFlags(); int battleId = msg.readInt(); if (flags.readBool()) { if (spectatedBattles.contains(battleId)) { Log.e(TAG, "Already watching battle " + battleId); return; } BattleConf conf = new BattleConf(msg); PlayerInfo p1 = players.get(conf.id(0)); PlayerInfo p2 = players.get(conf.id(1)); SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this); spectatedBattles.put(battleId, battle); Intent intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); showBattleNotification("Spectated Battle", battleId, conf); } else { closeBattle(battleId); } break; } case SpectateBattleMessage: { int battleId = msg.readInt(); msg.readInt(); // discard the size, unneeded if (spectatedBattles.containsKey(battleId)) { spectatedBattles.get(battleId).receiveCommand(msg); } break; } case AskForPass: { salt = msg.readString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readString(), this)); break; } default: { System.out.println("Unimplented message"); } }
public void handleMsg(Bais msg) { byte i = msg.readByte(); Command c = Command.values()[i]; Log.d(TAG, "Received: " + c); switch (c) { case ChannelPlayers: case JoinChannel: case LeaveChannel:{ Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else Log.e(TAG, "Received message for nonexistent channel"); break; } case VersionControl: { ProtocolVersion serverVersion = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { Log.d(TAG, "Server has newer protocol version than we expect"); } else if (serverVersion.compareTo(version) < 0) { Log.d(TAG, "PO Android uses newer protocol than Server"); } serverSupportsZipCompression = msg.readBool(); ProtocolVersion lastVersionWithoutFeatures = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutCompatBreak = new ProtocolVersion(msg); ProtocolVersion lastVersionWithoutMajorCompatBreak = new ProtocolVersion(msg); if (serverVersion.compareTo(version) > 0) { if (lastVersionWithoutFeatures.compareTo(version) > 0) { Toast.makeText(this, R.string.new_server_features_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.minor_compat_break_warning, Toast.LENGTH_SHORT).show(); } else if (lastVersionWithoutMajorCompatBreak.compareTo(version) > 0) { Toast.makeText(this, R.string.major_compat_break_warning, Toast.LENGTH_LONG).show(); } } serverName = msg.readString(); if (chatActivity != null) { chatActivity.updateTitle(); } break; } case Register: { // Username not registered break; } case Login: { Bais flags = msg.readFlags(); Boolean hasReconnPass = flags.readBool(); if (hasReconnPass) { // Read byte array reconnectSecret = msg.readQByteArray(); } me.setTo(new PlayerInfo(msg)); myid = me.id; int numTiers = msg.readInt(); for (int j = 0; j < numTiers; j++) { // Tiers for each of our teams // TODO Do something with this info? msg.readString(); } players.put(myid, me); break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier(msg.readByte(), msg.readString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier(msg.readByte(), msg.readString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChannelsList: { int numChannels = msg.readInt(); for(int j = 0; j < numChannels; j++) { int chanId = msg.readInt(); Channel ch = new Channel(chanId, msg.readString(), this); channels.put(chanId, ch); //addChannel(msg.readQString(),chanId); } Log.d(TAG, channels.toString()); break; } case PlayersList: { while (msg.available() != 0) { // While there's playerInfo's available PlayerInfo p = new PlayerInfo(msg); PlayerInfo oldPlayer = players.get(p.id); players.put(p.id, p); if (oldPlayer != null) { p.battles = oldPlayer.battles; if (chatActivity != null) { /* Updates the player in the adapter memory */ chatActivity.updatePlayer(p, oldPlayer); } } /* Updates self player */ if (p.id == myid) { me.setTo(p); } } break; } case SendMessage: { Bais netFlags = msg.readFlags(); boolean hasChannel = netFlags.readBool(); boolean hasId = netFlags.readBool(); Bais dataFlags = msg.readFlags(); boolean isHtml = dataFlags.readBool(); Channel chan = hasChannel ? channels.get(msg.readInt()) : null; PlayerInfo player = hasId ? players.get(msg.readInt()) : null; CharSequence message = msg.readString(); if (hasId) { CharSequence color = (player == null ? "orange" : player.color.toHexString()); CharSequence name = player.nick(); if (isHtml) { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + message); } else { message = Html.fromHtml("<font color='" + color + "'><b>" + name + ": </b></font>" + StringUtilities.escapeHtml((String)message)); } } else { if (isHtml) { message = Html.fromHtml((String)message); } else { String str = StringUtilities.escapeHtml((String)message); int index = str.indexOf(':'); if (str.startsWith("*** ")) { message = Html.fromHtml("<font color='#FF00FF'>" + str + "</font>"); } else if (index != -1) { String firstPart = str.substring(0, index); String secondPart; try { secondPart = str.substring(index+2); } catch (IndexOutOfBoundsException ex) { secondPart = ""; } CharSequence color = "#318739"; if (firstPart.equals("Welcome Message")) { color = "blue"; } else if (firstPart.equals("~~Server~~")) { color = "orange"; } message = Html.fromHtml("<font color='" + color + "'><b>" + firstPart + ": </b></font>" + secondPart); } } } if (!hasChannel) { // Broadcast message if (chatActivity != null && message.toString().contains("Wrong password for this name.")) // XXX Is this still the message sent? chatActivity.makeToast(message.toString(), "long"); else { Iterator<Channel> it = joinedChannels.iterator(); while (it.hasNext()) { it.next().writeToHist(message); } } } else { if (chan == null) { Log.e(TAG, "Received message for nonexistent channel"); } else { chan.writeToHist(message); } } break; } case BattleList: { msg.readInt(); //channel, but irrelevant int numBattles = msg.readInt(); for (; numBattles > 0; numBattles--) { int battleId = msg.readInt(); //byte mode = msg.readByte(); /* protocol is messed up */ int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } break; } case ChannelBattle: { msg.readInt(); //channel, but irrelevant int battleId = msg.readInt(); //byte mode = msg.readByte(); int player1 = msg.readInt(); int player2 = msg.readInt(); addBattle(battleId, new BattleDesc(player1, player2)); } /* case JoinChannel: case LeaveChannel: // case ChannelMessage: // case HtmlChannel: { Channel ch = channels.get(msg.readInt()); if(ch != null) ch.handleChannelMsg(c, msg); else System.out.println("Received message for nonexistant channel"); break; // } case ServerName: { // serverName = msg.readQString(); // if (chatActivity != null) // chatActivity.updateTitle(); // break; } case TierSelection: { msg.readInt(); // Number of tiers Tier prevTier = new Tier((byte)msg.read(), msg.readQString()); prevTier.parentTier = superTier; superTier.subTiers.add(prevTier); while(msg.available() != 0) { // While there's another tier available Tier t = new Tier((byte)msg.read(), msg.readQString()); if(t.level == prevTier.level) { // Sibling case prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level < prevTier.level) { // Uncle case while(t.level < prevTier.level) prevTier = prevTier.parentTier; prevTier.parentTier.addSubTier(t); t.parentTier = prevTier.parentTier; } else if(t.level > prevTier.level) { // Child case prevTier.addSubTier(t); t.parentTier = prevTier; } prevTier = t; } break; } case ChallengeStuff: { IncomingChallenge challenge = new IncomingChallenge(msg); challenge.setNick(players.get(challenge.opponent)); System.out.println("CHALLENGE STUFF: " + ChallengeEnums.ChallengeDesc.values()[challenge.desc]); switch(ChallengeEnums.ChallengeDesc.values()[challenge.desc]) { case Sent: if (challenge.isValidChallenge(players)) { challenges.addFirst(challenge); if (chatActivity != null && chatActivity.hasWindowFocus()) { chatActivity.notifyChallenge(); } else { Notification note = new Notification(R.drawable.icon, "You've been challenged by " + challenge.oppName + "!", System.currentTimeMillis()); note.setLatestEventInfo(this, "POAndroid", "You've been challenged!", PendingIntent.getActivity(this, 0, new Intent(NetworkService.this, ChatActivity.class), Intent.FLAG_ACTIVITY_NEW_TASK)); noteMan.cancel(IncomingChallenge.note); noteMan.notify(IncomingChallenge.note, note); } } break; case Refused: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " refused your challenge", "short"); } break; case Busy: if(challenge.oppName != null && chatActivity != null) { chatActivity.makeToast(challenge.oppName + " is busy", "short"); } break; case InvalidTeam: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid team", "long"); break; case InvalidGen: if (chatActivity != null) chatActivity.makeToast("Challenge failed due to invalid gen", "long"); break; } break; }*/ case Logout: { // Only sent when player is in a PM with you and logs out int playerID = msg.readInt(); removePlayer(playerID); //System.out.println("Player " + playerID + " logged out."); break; } case BattleFinished: { int battleID = msg.readInt(); byte battleDesc = msg.readByte(); msg.readByte(); // battle mode int id1 = msg.readInt(); int id2 = msg.readInt(); //Log.i(TAG, "bID " + battleID + " battleDesc " + battleDesc + " id1 " + id1 + " id2 " + id2); String[] outcome = new String[]{" won by forfeit against ", " won against ", " tied with "}; if (isBattling(battleID) || spectatedBattles.containsKey(battleID)) { if (isBattling(battleID)) { //TODO: notification on win/lose // if (mePlayer.id == id1 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You won!"); // } else if (mePlayer.id == id2 && battleDesc < 2) { // showNotification(ChatActivity.class, "Chat", "You lost!"); // } else if (battleDesc == 2) { // showNotification(ChatActivity.class, "Chat", "You tied!"); // } } if (battleDesc < 2) { joinedChannels.peek().writeToHist(Html.fromHtml("<b><i>" + StringUtilities.escapeHtml(playerName(id1)) + outcome[battleDesc] + StringUtilities.escapeHtml(playerName(id2)) + ".</b></i>")); } if (battleDesc == 0 || battleDesc == 3) { closeBattle(battleID); } } removeBattle(battleID); break; } case SendPM: { int playerId = msg.readInt(); String message = msg.readString(); dealWithPM(playerId, message); break; }/* case SendTeam: { PlayerInfo p = new PlayerInfo(msg); if (players.containsKey(p.id)) { PlayerInfo player = players.get(p.id); player.update(p); Enumeration<Channel> e = channels.elements(); while (e.hasMoreElements()) { Channel ch = e.nextElement(); if (ch.players.containsKey(player.id)) { ch.updatePlayer(player); } } } break; } */ case BattleMessage: { int battleId = msg.readInt(); // currently support only one battle, unneeded msg.readInt(); // discard the size, unneeded if (isBattling(battleId)) { activeBattle(battleId).receiveCommand(msg); } break; } case EngageBattle: { int battleId = msg.readInt(); Bais flags = msg.readFlags(); byte mode = msg.readByte(); int p1 = msg.readInt(); int p2 = msg.readInt(); addBattle(battleId, new BattleDesc(p1, p2, mode)); if(flags.readBool()) { // This is us! BattleConf conf = new BattleConf(msg); // Start the battle Battle battle = new Battle(conf, msg, players.get(conf.id(0)), players.get(conf.id(1)), myid, battleId, this); activeBattles.put(battleId, battle); joinedChannels.peek().writeToHist("Battle between " + playerName(p1) + " and " + playerName(p2) + " started!"); Intent intent; intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); findingBattle = false; showBattleNotification("Battle", battleId, conf); } if (chatActivity != null) { chatActivity.updatePlayer(players.get(p1), players.get(p1)); chatActivity.updatePlayer(players.get(p2), players.get(p2)); } break; } case SpectateBattle: { Bais flags = msg.readFlags(); int battleId = msg.readInt(); if (flags.readBool()) { if (spectatedBattles.contains(battleId)) { Log.e(TAG, "Already watching battle " + battleId); return; } BattleConf conf = new BattleConf(msg); PlayerInfo p1 = players.get(conf.id(0)); PlayerInfo p2 = players.get(conf.id(1)); SpectatingBattle battle = new SpectatingBattle(conf, p1, p2, battleId, this); spectatedBattles.put(battleId, battle); Intent intent = new Intent(this, BattleActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("battleId", battleId); startActivity(intent); showBattleNotification("Spectated Battle", battleId, conf); } else { closeBattle(battleId); } break; } case SpectateBattleMessage: { int battleId = msg.readInt(); msg.readInt(); // discard the size, unneeded if (spectatedBattles.containsKey(battleId)) { spectatedBattles.get(battleId).receiveCommand(msg); } break; } case AskForPass: { salt = msg.readString(); // XXX not sure what the second half is supposed to check // from analyze.cpp : 265 of PO's code if (salt.length() < 6) { // || strlen((" " + salt).toUtf8().data()) < 7) System.out.println("Protocol Error: The server requires insecure authentication"); break; } askedForPass = true; if (chatActivity != null && (chatActivity.hasWindowFocus() || chatActivity.progressDialog.isShowing())) { chatActivity.notifyAskForPass(); } break; } case AddChannel: { addChannel(msg.readString(),msg.readInt()); break; } case RemoveChannel: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); break; } case ChanNameChange: { int chanId = msg.readInt(); if (chatActivity != null) chatActivity.removeChannel(channels.get(chanId)); channels.remove(chanId); channels.put(chanId, new Channel(chanId, msg.readString(), this)); break; } default: { System.out.println("Unimplented message"); } }
diff --git a/src/com/btmura/android/reddit/content/AbstractSessionLoader.java b/src/com/btmura/android/reddit/content/AbstractSessionLoader.java index 9a13abd5..64dff955 100644 --- a/src/com/btmura/android/reddit/content/AbstractSessionLoader.java +++ b/src/com/btmura/android/reddit/content/AbstractSessionLoader.java @@ -1,66 +1,65 @@ /* * Copyright (C) 2013 Brian Muramatsu * * 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.btmura.android.reddit.content; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.content.CursorLoader; import android.text.TextUtils; import android.util.Log; import com.btmura.android.reddit.BuildConfig; import com.btmura.android.reddit.database.CursorExtrasWrapper; import com.btmura.android.reddit.provider.ThingProvider; import com.btmura.android.reddit.util.Array; abstract class AbstractSessionLoader extends CursorLoader { private static final String TAG = "AbstractSessionLoader"; private long sessionId; private String more; AbstractSessionLoader(Context context, Uri uri, String[] projection, String selection, String sortOrder, long sessionId, String more) { super(context, uri, projection, selection, null, sortOrder); this.sessionId = sessionId; this.more = more; } @Override public Cursor loadInBackground() { if (BuildConfig.DEBUG) { Log.d(TAG, "loadInBackground"); } if (sessionId == 0 || !TextUtils.isEmpty(more)) { Bundle extras = createSession(sessionId, more); - if (extras != null) { - sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID); - setSelectionArgs(Array.of(sessionId)); - } else { + if (extras == null) { return null; } + sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID); } Bundle extras = new Bundle(1); extras.putLong(ThingProvider.EXTRA_SESSION_ID, sessionId); + setSelectionArgs(Array.of(sessionId)); return new CursorExtrasWrapper(super.loadInBackground(), extras); } protected abstract Bundle createSession(long sessionId, String more); }
false
true
public Cursor loadInBackground() { if (BuildConfig.DEBUG) { Log.d(TAG, "loadInBackground"); } if (sessionId == 0 || !TextUtils.isEmpty(more)) { Bundle extras = createSession(sessionId, more); if (extras != null) { sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID); setSelectionArgs(Array.of(sessionId)); } else { return null; } } Bundle extras = new Bundle(1); extras.putLong(ThingProvider.EXTRA_SESSION_ID, sessionId); return new CursorExtrasWrapper(super.loadInBackground(), extras); }
public Cursor loadInBackground() { if (BuildConfig.DEBUG) { Log.d(TAG, "loadInBackground"); } if (sessionId == 0 || !TextUtils.isEmpty(more)) { Bundle extras = createSession(sessionId, more); if (extras == null) { return null; } sessionId = extras.getLong(ThingProvider.EXTRA_SESSION_ID); } Bundle extras = new Bundle(1); extras.putLong(ThingProvider.EXTRA_SESSION_ID, sessionId); setSelectionArgs(Array.of(sessionId)); return new CursorExtrasWrapper(super.loadInBackground(), extras); }
diff --git a/android/src/org/neugierig/muni/AsyncBackendHelper.java b/android/src/org/neugierig/muni/AsyncBackendHelper.java index c393f00..6cb5267 100644 --- a/android/src/org/neugierig/muni/AsyncBackendHelper.java +++ b/android/src/org/neugierig/muni/AsyncBackendHelper.java @@ -1,80 +1,80 @@ package org.neugierig.muni; import android.app.*; import android.content.*; import android.util.Log; // AsyncBackendHelper provides a UI-side counterpart to AsyncBackend. // It has hooks into (and expects callbacks from) an Activity and // manages displaying the "Network Error" dialog. class AsyncBackendHelper implements AsyncBackend.APIResultCallback { public interface Delegate { // More Java callback snafu workaround; lets the caller pass a bit // of code to run against the AsyncBackend. public void startAsyncQuery(AsyncBackend backend); // Return the result of a query. If there was an error, it will // never get called. public void onAsyncResult(Object obj); } AsyncBackendHelper(Activity activity, Delegate delegate) { mActivity = activity; mDelegate = delegate; mBackend = new AsyncBackend(activity); } public void start() { mActivity.setProgressBarIndeterminateVisibility(true); mDelegate.startAsyncQuery(mBackend); } @Override public void onAPIResult(Object obj) { mActivity.setProgressBarIndeterminateVisibility(false); mDelegate.onAsyncResult(obj); } @Override public void onException(Exception exn) { mActivity.setProgressBarIndeterminateVisibility(false); mBackendError = exn; mActivity.showDialog(ERROR_DIALOG_ID); } public Dialog onCreateDialog(int id) { switch (id) { case ERROR_DIALOG_ID: { DialogInterface.OnClickListener clicker = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON1: - mDelegate.startAsyncQuery(mBackend); + start(); break; case DialogInterface.BUTTON2: mActivity.dismissDialog(ERROR_DIALOG_ID); mActivity.finish(); break; } } }; return new AlertDialog.Builder(mActivity) .setTitle("Server Error") .setMessage(mBackendError.getLocalizedMessage()) .setPositiveButton("Retry", clicker) .setNegativeButton("Cancel", clicker) .create(); } } return null; } private static final int ERROR_DIALOG_ID = 0; // XXX how to choose? private Activity mActivity; private Delegate mDelegate; private AsyncBackend mBackend; private Exception mBackendError; }
true
true
public Dialog onCreateDialog(int id) { switch (id) { case ERROR_DIALOG_ID: { DialogInterface.OnClickListener clicker = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON1: mDelegate.startAsyncQuery(mBackend); break; case DialogInterface.BUTTON2: mActivity.dismissDialog(ERROR_DIALOG_ID); mActivity.finish(); break; } } }; return new AlertDialog.Builder(mActivity) .setTitle("Server Error") .setMessage(mBackendError.getLocalizedMessage()) .setPositiveButton("Retry", clicker) .setNegativeButton("Cancel", clicker) .create(); } } return null; }
public Dialog onCreateDialog(int id) { switch (id) { case ERROR_DIALOG_ID: { DialogInterface.OnClickListener clicker = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON1: start(); break; case DialogInterface.BUTTON2: mActivity.dismissDialog(ERROR_DIALOG_ID); mActivity.finish(); break; } } }; return new AlertDialog.Builder(mActivity) .setTitle("Server Error") .setMessage(mBackendError.getLocalizedMessage()) .setPositiveButton("Retry", clicker) .setNegativeButton("Cancel", clicker) .create(); } } return null; }
diff --git a/OmniDrive/src/org/usfirst/frc3925/OmniDrive/commands/Drive.java b/OmniDrive/src/org/usfirst/frc3925/OmniDrive/commands/Drive.java index abf8f84..629fb9c 100644 --- a/OmniDrive/src/org/usfirst/frc3925/OmniDrive/commands/Drive.java +++ b/OmniDrive/src/org/usfirst/frc3925/OmniDrive/commands/Drive.java @@ -1,102 +1,102 @@ // RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc3925.OmniDrive.commands; import com.sun.squawk.util.MathUtils; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc3925.OmniDrive.Robot; import org.usfirst.frc3925.OmniDrive.RobotMap; /** * */ public class Drive extends Command { public Drive() { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.omniDriveSubsystem); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { double movement = Robot.oi.xbox.getRawAxis(2); double strafe = Robot.oi.xbox.getRawAxis(1); double spin = Robot.oi.xbox.getRawAxis(4); double[] speeds = getOmniSpeeds(movement, strafe, spin); RobotMap.omniDriveSubsystemTopLeftJag.set(-speeds[0]); RobotMap.omniDriveSubsystemTopRightJag.set(speeds[1]); RobotMap.omniDriveSubsystemBottomLeftJag.set(-speeds[2]); RobotMap.omniDriveSubsystemBottomRightJag.set(speeds[3]); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { RobotMap.omniDriveSubsystemTopLeftJag.set(0); RobotMap.omniDriveSubsystemTopRightJag.set(0); RobotMap.omniDriveSubsystemBottomLeftJag.set(0); RobotMap.omniDriveSubsystemBottomRightJag.set(0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } private static final double RAD_45_DEG = Math.PI/4.0; private static final double SPINSCALE = 0.5D; private double[] getOmniSpeeds(double movement, double strafe, double spin) { double[] speeds = new double[4]; movement = trimDouble(movement); strafe = trimDouble(strafe); spin = trimDouble(spin); double r, angle; r = Math.sqrt(movement*movement + strafe*strafe); - angle = MathUtils.atan2(strafe, movement); + angle = MathUtils.atan2(strafe, movement)-RAD_45_DEG; speeds[0] = trimDouble(r*Math.cos(angle) + spin*SPINSCALE); speeds[1] = trimDouble(r*Math.sin(angle) - spin*SPINSCALE); speeds[2] = trimDouble(r*Math.sin(angle) + spin*SPINSCALE); speeds[3] = trimDouble(r*Math.cos(angle) - spin*SPINSCALE); return speeds; } private double trimDouble(double in) { if (in > 1.0d){ in = 1.0d;} if (in < -1.0d){ in = -1.0d;} return in; } }
true
true
private double[] getOmniSpeeds(double movement, double strafe, double spin) { double[] speeds = new double[4]; movement = trimDouble(movement); strafe = trimDouble(strafe); spin = trimDouble(spin); double r, angle; r = Math.sqrt(movement*movement + strafe*strafe); angle = MathUtils.atan2(strafe, movement); speeds[0] = trimDouble(r*Math.cos(angle) + spin*SPINSCALE); speeds[1] = trimDouble(r*Math.sin(angle) - spin*SPINSCALE); speeds[2] = trimDouble(r*Math.sin(angle) + spin*SPINSCALE); speeds[3] = trimDouble(r*Math.cos(angle) - spin*SPINSCALE); return speeds; }
private double[] getOmniSpeeds(double movement, double strafe, double spin) { double[] speeds = new double[4]; movement = trimDouble(movement); strafe = trimDouble(strafe); spin = trimDouble(spin); double r, angle; r = Math.sqrt(movement*movement + strafe*strafe); angle = MathUtils.atan2(strafe, movement)-RAD_45_DEG; speeds[0] = trimDouble(r*Math.cos(angle) + spin*SPINSCALE); speeds[1] = trimDouble(r*Math.sin(angle) - spin*SPINSCALE); speeds[2] = trimDouble(r*Math.sin(angle) + spin*SPINSCALE); speeds[3] = trimDouble(r*Math.cos(angle) - spin*SPINSCALE); return speeds; }
diff --git a/wms/src/main/java/org/vfny/geoserver/wms/responses/GetMapResponse.java b/wms/src/main/java/org/vfny/geoserver/wms/responses/GetMapResponse.java index 06d5c6b06c..04e644a805 100644 --- a/wms/src/main/java/org/vfny/geoserver/wms/responses/GetMapResponse.java +++ b/wms/src/main/java/org/vfny/geoserver/wms/responses/GetMapResponse.java @@ -1,523 +1,503 @@ /* Copyright (c) 2001, 2003 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.vfny.geoserver.wms.responses; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultQuery; import org.geotools.data.FeatureSource; import org.geotools.data.Query; import org.geotools.data.coverage.grid.AbstractGridCoverage2DReader; import org.geotools.factory.FactoryConfigurationError; import org.geotools.feature.IllegalAttributeException; import org.geotools.feature.SchemaException; import org.geotools.filter.Filter; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.DefaultMapLayer; import org.geotools.map.MapLayer; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.styling.Style; import org.opengis.parameter.ParameterValueGroup; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import org.springframework.context.ApplicationContext; import org.vfny.geoserver.Request; import org.vfny.geoserver.Response; import org.vfny.geoserver.ServiceException; import org.vfny.geoserver.global.GeoServer; import org.vfny.geoserver.global.MapLayerInfo; import org.vfny.geoserver.global.Service; import org.vfny.geoserver.global.WMS; import org.vfny.geoserver.util.CoverageUtils; import org.vfny.geoserver.wms.GetMapProducer; import org.vfny.geoserver.wms.GetMapProducerFactorySpi; import org.vfny.geoserver.wms.WMSMapContext; import org.vfny.geoserver.wms.WmsException; import org.vfny.geoserver.wms.requests.GetMapRequest; import com.vividsolutions.jts.geom.Envelope; /** * A GetMapResponse object is responsible of generating a map based on a GetMap * request. The way the map is generated is independent of this class, wich will * use a delegate object based on the output format requested * * @author Gabriel Roldan, Axios Engineering * @version $Id: GetMapResponse.java,v 1.11 2004/03/14 23:29:30 groldan Exp $ */ public class GetMapResponse implements Response { /** DOCUMENT ME! */ private static final Logger LOGGER = Logger.getLogger(GetMapResponse.class .getPackage().getName()); /** * The map producer that will be used for the production of a map in the * requested format. */ private GetMapProducer delegate; /** * The map context */ private WMSMapContext map; /** * WMS module */ private WMS wms; /** * custom response headers */ private HashMap responseHeaders; String headerContentDisposition; private ApplicationContext applicationContext; /** * Creates a new GetMapResponse object. * @param applicationContext */ public GetMapResponse(WMS wms, ApplicationContext applicationContext) { this.wms = wms; this.applicationContext=applicationContext; responseHeaders = new HashMap(10); } /** * Returns any extra headers that this service might want to set in the HTTP response object. */ public HashMap getResponseHeaders() { return responseHeaders; } /** * DOCUMENT ME! * * @param req DOCUMENT ME! * * @throws ServiceException DOCUMENT ME! * @throws WmsException DOCUMENT ME! */ public void execute(Request req) throws ServiceException { GetMapRequest request = (GetMapRequest) req; final String outputFormat = request.getFormat(); this.delegate = getDelegate(outputFormat, wms); final MapLayerInfo[] layers = request.getLayers(); final Style[] styles = (Style[]) request.getStyles().toArray( new Style[] {}); final Filter[] filters = (request.getFilters() != null ? (Filter[]) request.getFilters().toArray( new Filter[] {}) : null); //JD:make instance variable in order to release resources later //final WMSMapContext map = new WMSMapContext(); map = new WMSMapContext(request); //DJB: the WMS spec says that the request must not be 0 area // if it is, throw a service exception! final Envelope env = request.getBbox(); if (env.isNull() || (env.getWidth() <= 0) || (env.getHeight() <= 0)) { throw new WmsException(new StringBuffer( "The request bounding box has zero area: ").append(env) .toString()); } // DJB DONE: replace by setAreaOfInterest(Envelope, // CoordinateReferenceSystem) // with the user supplied SRS parameter // if there's a crs in the request, use that. If not, assume its 4326 final CoordinateReferenceSystem mapcrs = request.getCrs(); // DJB: added this to be nicer about the "NONE" srs. if (mapcrs != null) map.setAreaOfInterest(env, mapcrs); else map.setAreaOfInterest(env, DefaultGeographicCRS.WGS84); map.setMapWidth(request.getWidth()); map.setMapHeight(request.getHeight()); map.setBgColor(request.getBgColor()); map.setTransparent(request.isTransparent()); // // // // Check to see if we really have something to display. Sometimes width // or height or both are non positivie or the requested area is null. // // /// if (request.getWidth() <= 0 || request.getHeight() <= 0 || map.getAreaOfInterest().getLength(0) <= 0 || map.getAreaOfInterest().getLength(1) <= 0) { if (LOGGER.isLoggable(Level.FINE)) LOGGER .fine("We are not going to render anything because either the are is null ar the dimensions are not positive."); return; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up map"); } try { // mapcontext can leak memory -- we make sure we done (see // finally block) MapLayer layer; // track the external caching strategy for any map layers boolean cachingPossible = request.getHttpServletRequest() .getMethod().equals("GET"); int maxAge = Integer.MAX_VALUE; FeatureSource source; AbstractGridCoverage2DReader reader; Style style; Filter definitionFilter, optionalFilter; Query definitionQuery; int nma; final int length = layers.length; for (int i = 0; i < length; i++) { style = styles[i]; try { optionalFilter = filters[i]; } catch (Exception e) { optionalFilter = null; } if (layers[i].getType() == MapLayerInfo.TYPE_VECTOR) { if (cachingPossible) { if (layers[i].getFeature().isCachingEnabled()) { nma = Integer.parseInt(layers[i].getFeature() .getCacheMaxAge()); // suppose the map contains multiple cachable // layers...we can only cache the combined map for // the // time specified by the shortest-cached layer. if (nma < maxAge) maxAge = nma; } else { // if one layer isn't cachable, then we can't cache // any of them. Disable caching. cachingPossible = false; } } // ///////////////////////////////////////////////////////// // // Adding a feature layer // // ///////////////////////////////////////////////////////// try { source = layers[i].getFeature().getFeatureSource(); - // /// - // - // Do we have something to load? - // We just need to check the bbox of the layer. - // - // // - if (layers[i].getBoundingBox() instanceof ReferencedEnvelope) { - final ReferencedEnvelope bbox = (ReferencedEnvelope) layers[i].getBoundingBox(); - if(CRS.equalsIgnoreMetadata(bbox.getCoordinateReferenceSystem(), mapcrs)) { - if (!layers[i].getBoundingBox().intersects(env)) { - continue; - } - } else { - ReferencedEnvelope prjEnv = new ReferencedEnvelope(env, mapcrs).transform(bbox.getCoordinateReferenceSystem(), true); - if (!layers[i].getBoundingBox().intersects(prjEnv)) { - continue; - } - } - } + // NOTE for the feature. Here there was some code that sounded like: + // * get the bounding box from feature source + // * eventually reproject it to the actual CRS used for map + // * if no intersection, don't bother adding the feature source to the map + // This is not an optimization, on the contrary, computing the bbox may be + // very expensive depending on the data size. Using sigma.openplans.org data + // and a tiled client like OpenLayers, it dragged the server to his knees + // and the client simply timed out } catch (IOException exp) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append( exp.getMessage()).toString(), exp); } throw new WmsException(null, new StringBuffer( "Internal error : ").append(exp.getMessage()) .toString()); - } catch (FactoryException exp) { - if (LOGGER.isLoggable(Level.SEVERE)) { - LOGGER.log(Level.SEVERE, new StringBuffer( - "Getting feature source: ").append( - exp.getMessage()).toString(), exp); - } - throw new WmsException(null, new StringBuffer( - "Internal error : ").append(exp.getMessage()) - .toString()); - } + } layer = new DefaultMapLayer(source, style); layer.setTitle(layers[i].getName()); definitionFilter = layers[i].getFeature().getDefinitionQuery(); if (definitionFilter != null) { definitionQuery = new DefaultQuery(source.getSchema() .getTypeName(), definitionFilter); layer.setQuery(definitionQuery); } else if (optionalFilter != null) { definitionQuery = new DefaultQuery(source.getSchema().getTypeName(), optionalFilter); layer.setQuery(definitionQuery); } map.addLayer(layer); } else if (layers[i].getType() == MapLayerInfo.TYPE_RASTER) { // ///////////////////////////////////////////////////////// // // Adding a coverage layer // // ///////////////////////////////////////////////////////// reader = (AbstractGridCoverage2DReader) layers[i] .getCoverage().getReader(); if (reader != null) { // ///////////////////////////////////////////////////////// // // Setting coverage reading params. // // ///////////////////////////////////////////////////////// final ParameterValueGroup params = reader.getFormat().getReadParameters(); layer = new DefaultMapLayer(DataUtilities.wrapGcReader(reader, CoverageUtils.getParameters(params, layers[i].getCoverage().getParameters())), style); layer.setTitle(layers[i].getName()); layer.setQuery(Query.ALL); map.addLayer(layer); } else throw new WmsException( null, new StringBuffer( "Internal error : unable to get reader for this coverage layer ") .append(layers[i].toString()) .toString()); } } // ///////////////////////////////////////////////////////// // // Producing the map in the requested format. // // ///////////////////////////////////////////////////////// this.delegate.produceMap(map); if (cachingPossible) responseHeaders.put("Cache-Control: max-age", maxAge + "s"); String contentDisposition = this.delegate.getContentDisposition(); if (contentDisposition != null) { this.headerContentDisposition = contentDisposition; } } catch (ClassCastException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (TransformException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (FactoryConfigurationError e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (SchemaException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (IllegalAttributeException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } finally { // clean try { // map.clearLayerList(); } catch (Exception e) // we dont want to propogate a new error { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } } } } /** * asks the internal GetMapDelegate for the MIME type of the map that it * will generate or is ready to, and returns it * * @param gs DOCUMENT ME! * * @return the MIME type of the map generated or ready to generate * * @throws IllegalStateException if a GetMapDelegate is not setted yet */ public String getContentType(GeoServer gs) throws IllegalStateException { if (this.delegate == null) { throw new IllegalStateException("No request has been processed"); } return this.delegate.getContentType(); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public String getContentEncoding() { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("returning content encoding null"); } return null; } /** * if a GetMapDelegate is set, calls it's abort method. Elsewere do * nothing. * * @param gs DOCUMENT ME! */ public void abort(Service gs) { if (this.delegate != null) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("asking delegate for aborting the process"); } this.delegate.abort(); } } /** * delegates the writing and encoding of the results of the request to the * <code>GetMapDelegate</code> wich is actually processing it, and has * been obtained when <code>execute(Request)</code> was called * * @param out the output to where the map must be written * * @throws ServiceException if the delegate throws a ServiceException * inside its <code>writeTo(OuptutStream)</code>, mostly due to * @throws IOException if the delegate throws an IOException inside its * <code>writeTo(OuptutStream)</code>, mostly due to * @throws IllegalStateException if this method is called before * <code>execute(Request)</code> has succeed */ public void writeTo(OutputStream out) throws ServiceException, IOException { try { // mapcontext can leak memory -- we make sure we done (see finally block) if (this.delegate == null) { throw new IllegalStateException( "No GetMapDelegate is setted, make sure you have called execute and it has succeed"); } if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(new StringBuffer("asking delegate for write to ") .append(out).toString()); } this.delegate.writeTo(out); } finally { try { map.clearLayerList(); } catch (Exception e) // we dont want to propogate a new error { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } } } } /** * Creates a GetMapDelegate specialized in generating the requested map * format * * @param outputFormat a request parameter object wich holds the processed * request objects, such as layers, bbox, outpu format, etc. * * @return A specialization of <code>GetMapDelegate</code> wich can produce * the requested output map format * * @throws WmsException if no specialization is configured for the output * format specified in <code>request</code> or if it can't be * instantiated */ private GetMapProducer getDelegate(String outputFormat, WMS wms) throws WmsException { Map beans=applicationContext.getBeansOfType(GetMapProducerFactorySpi.class); Collection producers=beans.values(); GetMapProducerFactorySpi factory; for (Iterator iter = producers.iterator(); iter.hasNext();) { factory = (GetMapProducerFactorySpi) iter.next(); if (factory.canProduce(outputFormat)) { return factory.createMapProducer(outputFormat, wms); } } WmsException e = new WmsException( "There is no support for creating maps in " + outputFormat + " format" ); e.setCode( "InvalidFormat" ); throw e; } /** * Convenient mehtod to inspect the available * <code>GetMapProducerFactorySpi</code> and return the set of all the map * formats' MIME types that the producers can handle * * @return a Set&lt;String&gt; with the supported mime types. */ public Set getMapFormats() { Set wmsGetMapFormats=loadImageFormats(applicationContext); return wmsGetMapFormats; } /** * Convenience method for processing the GetMapProducerFactorySpi * extension point and returning the set of available image formats. * * @param applicationContext The application context. * */ public static Set loadImageFormats(ApplicationContext applicationContext) { Map beans = applicationContext .getBeansOfType(GetMapProducerFactorySpi.class); Collection producers=beans.values(); Set formats=new HashSet(); GetMapProducerFactorySpi producer; for (Iterator iter = producers.iterator(); iter.hasNext();) { producer = (GetMapProducerFactorySpi) iter.next(); formats.addAll(producer.getSupportedFormats()); } return formats; } public String getContentDisposition() { return headerContentDisposition; } }
false
true
public void execute(Request req) throws ServiceException { GetMapRequest request = (GetMapRequest) req; final String outputFormat = request.getFormat(); this.delegate = getDelegate(outputFormat, wms); final MapLayerInfo[] layers = request.getLayers(); final Style[] styles = (Style[]) request.getStyles().toArray( new Style[] {}); final Filter[] filters = (request.getFilters() != null ? (Filter[]) request.getFilters().toArray( new Filter[] {}) : null); //JD:make instance variable in order to release resources later //final WMSMapContext map = new WMSMapContext(); map = new WMSMapContext(request); //DJB: the WMS spec says that the request must not be 0 area // if it is, throw a service exception! final Envelope env = request.getBbox(); if (env.isNull() || (env.getWidth() <= 0) || (env.getHeight() <= 0)) { throw new WmsException(new StringBuffer( "The request bounding box has zero area: ").append(env) .toString()); } // DJB DONE: replace by setAreaOfInterest(Envelope, // CoordinateReferenceSystem) // with the user supplied SRS parameter // if there's a crs in the request, use that. If not, assume its 4326 final CoordinateReferenceSystem mapcrs = request.getCrs(); // DJB: added this to be nicer about the "NONE" srs. if (mapcrs != null) map.setAreaOfInterest(env, mapcrs); else map.setAreaOfInterest(env, DefaultGeographicCRS.WGS84); map.setMapWidth(request.getWidth()); map.setMapHeight(request.getHeight()); map.setBgColor(request.getBgColor()); map.setTransparent(request.isTransparent()); // // // // Check to see if we really have something to display. Sometimes width // or height or both are non positivie or the requested area is null. // // /// if (request.getWidth() <= 0 || request.getHeight() <= 0 || map.getAreaOfInterest().getLength(0) <= 0 || map.getAreaOfInterest().getLength(1) <= 0) { if (LOGGER.isLoggable(Level.FINE)) LOGGER .fine("We are not going to render anything because either the are is null ar the dimensions are not positive."); return; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up map"); } try { // mapcontext can leak memory -- we make sure we done (see // finally block) MapLayer layer; // track the external caching strategy for any map layers boolean cachingPossible = request.getHttpServletRequest() .getMethod().equals("GET"); int maxAge = Integer.MAX_VALUE; FeatureSource source; AbstractGridCoverage2DReader reader; Style style; Filter definitionFilter, optionalFilter; Query definitionQuery; int nma; final int length = layers.length; for (int i = 0; i < length; i++) { style = styles[i]; try { optionalFilter = filters[i]; } catch (Exception e) { optionalFilter = null; } if (layers[i].getType() == MapLayerInfo.TYPE_VECTOR) { if (cachingPossible) { if (layers[i].getFeature().isCachingEnabled()) { nma = Integer.parseInt(layers[i].getFeature() .getCacheMaxAge()); // suppose the map contains multiple cachable // layers...we can only cache the combined map for // the // time specified by the shortest-cached layer. if (nma < maxAge) maxAge = nma; } else { // if one layer isn't cachable, then we can't cache // any of them. Disable caching. cachingPossible = false; } } // ///////////////////////////////////////////////////////// // // Adding a feature layer // // ///////////////////////////////////////////////////////// try { source = layers[i].getFeature().getFeatureSource(); // /// // // Do we have something to load? // We just need to check the bbox of the layer. // // // if (layers[i].getBoundingBox() instanceof ReferencedEnvelope) { final ReferencedEnvelope bbox = (ReferencedEnvelope) layers[i].getBoundingBox(); if(CRS.equalsIgnoreMetadata(bbox.getCoordinateReferenceSystem(), mapcrs)) { if (!layers[i].getBoundingBox().intersects(env)) { continue; } } else { ReferencedEnvelope prjEnv = new ReferencedEnvelope(env, mapcrs).transform(bbox.getCoordinateReferenceSystem(), true); if (!layers[i].getBoundingBox().intersects(prjEnv)) { continue; } } } } catch (IOException exp) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append( exp.getMessage()).toString(), exp); } throw new WmsException(null, new StringBuffer( "Internal error : ").append(exp.getMessage()) .toString()); } catch (FactoryException exp) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append( exp.getMessage()).toString(), exp); } throw new WmsException(null, new StringBuffer( "Internal error : ").append(exp.getMessage()) .toString()); } layer = new DefaultMapLayer(source, style); layer.setTitle(layers[i].getName()); definitionFilter = layers[i].getFeature().getDefinitionQuery(); if (definitionFilter != null) { definitionQuery = new DefaultQuery(source.getSchema() .getTypeName(), definitionFilter); layer.setQuery(definitionQuery); } else if (optionalFilter != null) { definitionQuery = new DefaultQuery(source.getSchema().getTypeName(), optionalFilter); layer.setQuery(definitionQuery); } map.addLayer(layer); } else if (layers[i].getType() == MapLayerInfo.TYPE_RASTER) { // ///////////////////////////////////////////////////////// // // Adding a coverage layer // // ///////////////////////////////////////////////////////// reader = (AbstractGridCoverage2DReader) layers[i] .getCoverage().getReader(); if (reader != null) { // ///////////////////////////////////////////////////////// // // Setting coverage reading params. // // ///////////////////////////////////////////////////////// final ParameterValueGroup params = reader.getFormat().getReadParameters(); layer = new DefaultMapLayer(DataUtilities.wrapGcReader(reader, CoverageUtils.getParameters(params, layers[i].getCoverage().getParameters())), style); layer.setTitle(layers[i].getName()); layer.setQuery(Query.ALL); map.addLayer(layer); } else throw new WmsException( null, new StringBuffer( "Internal error : unable to get reader for this coverage layer ") .append(layers[i].toString()) .toString()); } } // ///////////////////////////////////////////////////////// // // Producing the map in the requested format. // // ///////////////////////////////////////////////////////// this.delegate.produceMap(map); if (cachingPossible) responseHeaders.put("Cache-Control: max-age", maxAge + "s"); String contentDisposition = this.delegate.getContentDisposition(); if (contentDisposition != null) { this.headerContentDisposition = contentDisposition; } } catch (ClassCastException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (TransformException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (FactoryConfigurationError e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (SchemaException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (IllegalAttributeException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } finally { // clean try { // map.clearLayerList(); } catch (Exception e) // we dont want to propogate a new error { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } } } }
public void execute(Request req) throws ServiceException { GetMapRequest request = (GetMapRequest) req; final String outputFormat = request.getFormat(); this.delegate = getDelegate(outputFormat, wms); final MapLayerInfo[] layers = request.getLayers(); final Style[] styles = (Style[]) request.getStyles().toArray( new Style[] {}); final Filter[] filters = (request.getFilters() != null ? (Filter[]) request.getFilters().toArray( new Filter[] {}) : null); //JD:make instance variable in order to release resources later //final WMSMapContext map = new WMSMapContext(); map = new WMSMapContext(request); //DJB: the WMS spec says that the request must not be 0 area // if it is, throw a service exception! final Envelope env = request.getBbox(); if (env.isNull() || (env.getWidth() <= 0) || (env.getHeight() <= 0)) { throw new WmsException(new StringBuffer( "The request bounding box has zero area: ").append(env) .toString()); } // DJB DONE: replace by setAreaOfInterest(Envelope, // CoordinateReferenceSystem) // with the user supplied SRS parameter // if there's a crs in the request, use that. If not, assume its 4326 final CoordinateReferenceSystem mapcrs = request.getCrs(); // DJB: added this to be nicer about the "NONE" srs. if (mapcrs != null) map.setAreaOfInterest(env, mapcrs); else map.setAreaOfInterest(env, DefaultGeographicCRS.WGS84); map.setMapWidth(request.getWidth()); map.setMapHeight(request.getHeight()); map.setBgColor(request.getBgColor()); map.setTransparent(request.isTransparent()); // // // // Check to see if we really have something to display. Sometimes width // or height or both are non positivie or the requested area is null. // // /// if (request.getWidth() <= 0 || request.getHeight() <= 0 || map.getAreaOfInterest().getLength(0) <= 0 || map.getAreaOfInterest().getLength(1) <= 0) { if (LOGGER.isLoggable(Level.FINE)) LOGGER .fine("We are not going to render anything because either the are is null ar the dimensions are not positive."); return; } if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("setting up map"); } try { // mapcontext can leak memory -- we make sure we done (see // finally block) MapLayer layer; // track the external caching strategy for any map layers boolean cachingPossible = request.getHttpServletRequest() .getMethod().equals("GET"); int maxAge = Integer.MAX_VALUE; FeatureSource source; AbstractGridCoverage2DReader reader; Style style; Filter definitionFilter, optionalFilter; Query definitionQuery; int nma; final int length = layers.length; for (int i = 0; i < length; i++) { style = styles[i]; try { optionalFilter = filters[i]; } catch (Exception e) { optionalFilter = null; } if (layers[i].getType() == MapLayerInfo.TYPE_VECTOR) { if (cachingPossible) { if (layers[i].getFeature().isCachingEnabled()) { nma = Integer.parseInt(layers[i].getFeature() .getCacheMaxAge()); // suppose the map contains multiple cachable // layers...we can only cache the combined map for // the // time specified by the shortest-cached layer. if (nma < maxAge) maxAge = nma; } else { // if one layer isn't cachable, then we can't cache // any of them. Disable caching. cachingPossible = false; } } // ///////////////////////////////////////////////////////// // // Adding a feature layer // // ///////////////////////////////////////////////////////// try { source = layers[i].getFeature().getFeatureSource(); // NOTE for the feature. Here there was some code that sounded like: // * get the bounding box from feature source // * eventually reproject it to the actual CRS used for map // * if no intersection, don't bother adding the feature source to the map // This is not an optimization, on the contrary, computing the bbox may be // very expensive depending on the data size. Using sigma.openplans.org data // and a tiled client like OpenLayers, it dragged the server to his knees // and the client simply timed out } catch (IOException exp) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append( exp.getMessage()).toString(), exp); } throw new WmsException(null, new StringBuffer( "Internal error : ").append(exp.getMessage()) .toString()); } layer = new DefaultMapLayer(source, style); layer.setTitle(layers[i].getName()); definitionFilter = layers[i].getFeature().getDefinitionQuery(); if (definitionFilter != null) { definitionQuery = new DefaultQuery(source.getSchema() .getTypeName(), definitionFilter); layer.setQuery(definitionQuery); } else if (optionalFilter != null) { definitionQuery = new DefaultQuery(source.getSchema().getTypeName(), optionalFilter); layer.setQuery(definitionQuery); } map.addLayer(layer); } else if (layers[i].getType() == MapLayerInfo.TYPE_RASTER) { // ///////////////////////////////////////////////////////// // // Adding a coverage layer // // ///////////////////////////////////////////////////////// reader = (AbstractGridCoverage2DReader) layers[i] .getCoverage().getReader(); if (reader != null) { // ///////////////////////////////////////////////////////// // // Setting coverage reading params. // // ///////////////////////////////////////////////////////// final ParameterValueGroup params = reader.getFormat().getReadParameters(); layer = new DefaultMapLayer(DataUtilities.wrapGcReader(reader, CoverageUtils.getParameters(params, layers[i].getCoverage().getParameters())), style); layer.setTitle(layers[i].getName()); layer.setQuery(Query.ALL); map.addLayer(layer); } else throw new WmsException( null, new StringBuffer( "Internal error : unable to get reader for this coverage layer ") .append(layers[i].toString()) .toString()); } } // ///////////////////////////////////////////////////////// // // Producing the map in the requested format. // // ///////////////////////////////////////////////////////// this.delegate.produceMap(map); if (cachingPossible) responseHeaders.put("Cache-Control: max-age", maxAge + "s"); String contentDisposition = this.delegate.getContentDisposition(); if (contentDisposition != null) { this.headerContentDisposition = contentDisposition; } } catch (ClassCastException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (TransformException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (FactoryConfigurationError e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (SchemaException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } catch (IllegalAttributeException e) { throw new WmsException(e, new StringBuffer("Internal error : ") .append(e.getMessage()).toString(), ""); } finally { // clean try { // map.clearLayerList(); } catch (Exception e) // we dont want to propogate a new error { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, new StringBuffer( "Getting feature source: ").append(e.getMessage()) .toString(), e); } } } }
diff --git a/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/analysis/MethodResolver.java b/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/analysis/MethodResolver.java index 20921ff..bc6774e 100644 --- a/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/analysis/MethodResolver.java +++ b/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/analysis/MethodResolver.java @@ -1,125 +1,126 @@ /******************************************************************************* * Copyright (c) 2006 Mountainminds GmbH & Co. KG * This software is provided under the terms of the Eclipse Public License v1.0 * See http://www.eclipse.org/legal/epl-v10.html. * * $Id$ ******************************************************************************/ package com.mountainminds.eclemma.internal.core.analysis; import java.util.HashMap; import java.util.Map; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.compiler.CharOperation; import com.mountainminds.eclemma.internal.core.DebugOptions; import com.mountainminds.eclemma.internal.core.DebugOptions.ITracer; /** * Internal utility class that resolves local method signatures into absolute VM * type identifierts. * * @author Marc R. Hoffmann * @version $Revision$ */ public class MethodResolver { private static final String CONSTRUCTOR_VMNAME = "<init>"; //$NON-NLS-1$ private static final ITracer TRACER = DebugOptions.ANALYSISTRACER; private final IType type; private final Map cache = new HashMap(); /** * Creates a new resolver that works relative to the given type. * * @param type * context type to resolve local declarations in */ public MethodResolver(IType type) { this.type = type; } /** * Resolves the given signature type, e.g. <code>QMap.Entry;</code>. * Absolute types and primitve types will not be resolved. The returned string * is a VM signature type, e.g. <code>Ljava/util/Map$Entry;</code>. * * @param localName * the local dot-based signature type * @return resolved absolute VM signature * @throws JavaModelException * if thrown by the underlying JavaModel */ public char[] resolve(final String localName) throws JavaModelException { char[] cresolved = (char[]) cache.get(localName); if (cresolved != null) return cresolved; char[] clocalName = localName.toCharArray(); int arraynesting = Signature.getArrayCount(clocalName); if (arraynesting > 0) { cresolved = Signature.getElementType(clocalName); } else { cresolved = clocalName; } + cresolved = Signature.getTypeErasure(cresolved); if (Signature.getTypeSignatureKind(cresolved) == Signature.CLASS_TYPE_SIGNATURE) { String[][] hits = type.resolveType(new String(cresolved, 1, cresolved.length - 2)); if (hits == null) { // some guessing cresolved[0] = Signature.C_RESOLVED; CharOperation.replace(cresolved, '.', '/'); } else { if (hits.length > 1) { TRACER.trace("Ambigous type resolved for {0} in {1}", localName, type //$NON-NLS-1$ .getElementName()); } char[] pack = hits[0][0].toCharArray(); CharOperation.replace(pack, '.', '/'); char[] type = hits[0][1].toCharArray(); CharOperation.replace(type, '.', '$'); cresolved = new char[pack.length + type.length + 3]; cresolved[0] = Signature.C_RESOLVED; System.arraycopy(pack, 0, cresolved, 1, pack.length); cresolved[pack.length + 1] = '/'; System.arraycopy(type, 0, cresolved, pack.length + 2, type.length); cresolved[pack.length + type.length + 2] = ';'; } } if (arraynesting > 0) { cresolved = Signature.createArraySignature(cresolved, arraynesting); } cache.put(localName, cresolved); return cresolved; } public String resolve(IMethod method) throws JavaModelException { String[] params = method.getParameterTypes(); char[][] resparams = new char[params.length][]; for (int j = 0; j < params.length; j++) { resparams[j] = resolve(params[j]); } char[] resreturn = resolve(method.getReturnType()); char[] signature = Signature.createMethodSignature(resparams, resreturn); String name = method.getElementName(); name = replaceSpecialMethodNames(name); StringBuffer sb = new StringBuffer(name).append(signature); return sb.toString(); } private String replaceSpecialMethodNames(String name) { if (name.equals(type.getElementName())) { name = CONSTRUCTOR_VMNAME; } return name; } }
true
true
public char[] resolve(final String localName) throws JavaModelException { char[] cresolved = (char[]) cache.get(localName); if (cresolved != null) return cresolved; char[] clocalName = localName.toCharArray(); int arraynesting = Signature.getArrayCount(clocalName); if (arraynesting > 0) { cresolved = Signature.getElementType(clocalName); } else { cresolved = clocalName; } if (Signature.getTypeSignatureKind(cresolved) == Signature.CLASS_TYPE_SIGNATURE) { String[][] hits = type.resolveType(new String(cresolved, 1, cresolved.length - 2)); if (hits == null) { // some guessing cresolved[0] = Signature.C_RESOLVED; CharOperation.replace(cresolved, '.', '/'); } else { if (hits.length > 1) { TRACER.trace("Ambigous type resolved for {0} in {1}", localName, type //$NON-NLS-1$ .getElementName()); } char[] pack = hits[0][0].toCharArray(); CharOperation.replace(pack, '.', '/'); char[] type = hits[0][1].toCharArray(); CharOperation.replace(type, '.', '$'); cresolved = new char[pack.length + type.length + 3]; cresolved[0] = Signature.C_RESOLVED; System.arraycopy(pack, 0, cresolved, 1, pack.length); cresolved[pack.length + 1] = '/'; System.arraycopy(type, 0, cresolved, pack.length + 2, type.length); cresolved[pack.length + type.length + 2] = ';'; } } if (arraynesting > 0) { cresolved = Signature.createArraySignature(cresolved, arraynesting); } cache.put(localName, cresolved); return cresolved; }
public char[] resolve(final String localName) throws JavaModelException { char[] cresolved = (char[]) cache.get(localName); if (cresolved != null) return cresolved; char[] clocalName = localName.toCharArray(); int arraynesting = Signature.getArrayCount(clocalName); if (arraynesting > 0) { cresolved = Signature.getElementType(clocalName); } else { cresolved = clocalName; } cresolved = Signature.getTypeErasure(cresolved); if (Signature.getTypeSignatureKind(cresolved) == Signature.CLASS_TYPE_SIGNATURE) { String[][] hits = type.resolveType(new String(cresolved, 1, cresolved.length - 2)); if (hits == null) { // some guessing cresolved[0] = Signature.C_RESOLVED; CharOperation.replace(cresolved, '.', '/'); } else { if (hits.length > 1) { TRACER.trace("Ambigous type resolved for {0} in {1}", localName, type //$NON-NLS-1$ .getElementName()); } char[] pack = hits[0][0].toCharArray(); CharOperation.replace(pack, '.', '/'); char[] type = hits[0][1].toCharArray(); CharOperation.replace(type, '.', '$'); cresolved = new char[pack.length + type.length + 3]; cresolved[0] = Signature.C_RESOLVED; System.arraycopy(pack, 0, cresolved, 1, pack.length); cresolved[pack.length + 1] = '/'; System.arraycopy(type, 0, cresolved, pack.length + 2, type.length); cresolved[pack.length + type.length + 2] = ';'; } } if (arraynesting > 0) { cresolved = Signature.createArraySignature(cresolved, arraynesting); } cache.put(localName, cresolved); return cresolved; }
diff --git a/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java b/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java index f8413a0fd..ed8b64991 100644 --- a/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java +++ b/src/com/itmill/toolkit/terminal/web/ApplicationServlet.java @@ -1,1939 +1,1939 @@ /* ************************************************************************* IT Mill Toolkit Development of Browser User Interfaces Made Easy Copyright (C) 2000-2006 IT Mill Ltd ************************************************************************* This product is distributed under commercial license that can be found from the product package on license.pdf. Use of this product might require purchasing a commercial license from IT Mill Ltd. For guidelines on usage, see licensing-guidelines.html ************************************************************************* For more information, contact: IT Mill Ltd phone: +358 2 4802 7180 Ruukinkatu 2-4 fax: +358 2 4802 7181 20540, Turku email: [email protected] Finland company www: www.itmill.com Primary source for information and releases: www.itmill.com ********************************************************************** */ package com.itmill.toolkit.terminal.web; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; import java.util.WeakHashMap; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import org.xml.sax.SAXException; import com.itmill.toolkit.Application; import com.itmill.toolkit.Application.WindowAttachEvent; import com.itmill.toolkit.Application.WindowDetachEvent; import com.itmill.toolkit.service.FileTypeResolver; import com.itmill.toolkit.service.License; import com.itmill.toolkit.service.License.InvalidLicenseFile; import com.itmill.toolkit.service.License.LicenseFileHasAlreadyBeenRead; import com.itmill.toolkit.service.License.LicenseFileHasNotBeenRead; import com.itmill.toolkit.service.License.LicenseSignatureIsInvalid; import com.itmill.toolkit.service.License.LicenseViolation; import com.itmill.toolkit.terminal.DownloadStream; import com.itmill.toolkit.terminal.Paintable; import com.itmill.toolkit.terminal.ParameterHandler; import com.itmill.toolkit.terminal.ThemeResource; import com.itmill.toolkit.terminal.URIHandler; import com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent; import com.itmill.toolkit.terminal.web.ThemeSource.ThemeException; import com.itmill.toolkit.terminal.web.WebBrowser; import com.itmill.toolkit.ui.Window; /** * This servlet connects IT Mill Toolkit Application to Web. This servlet * replaces both WebAdapterServlet and AjaxAdapterServlet. * * @author IT Mill Ltd. * @version * @VERSION@ * @since 4.0 */ public class ApplicationServlet extends HttpServlet implements Application.WindowAttachListener, Application.WindowDetachListener, Paintable.RepaintRequestListener { private static final long serialVersionUID = -4937882979845826574L; /** Version number of this release. For example "4.0.0" */ public static final String VERSION; /** Major version number. For example 4 in 4.1.0. */ public static final int VERSION_MAJOR; /** Minor version number. For example 1 in 4.1.0. */ public static final int VERSION_MINOR; /** Build number. For example 0-beta1 in 4.0.0-beta1. */ public static final String VERSION_BUILD; /* Initialize version numbers from string replaced by build-script. */ static { if ("@VERSION@".equals("@" + "VERSION" + "@")) VERSION = "4.0.0-INTERNAL-NONVERSIONED-DEBUG-BUILD"; else VERSION = "@VERSION@"; String[] digits = VERSION.split("\\."); VERSION_MAJOR = Integer.parseInt(digits[0]); VERSION_MINOR = Integer.parseInt(digits[1]); VERSION_BUILD = digits[2]; } // Configurable parameter names private static final String PARAMETER_DEBUG = "Debug"; private static final String PARAMETER_DEFAULT_THEME_JAR = "DefaultThemeJar"; private static final String PARAMETER_THEMESOURCE = "ThemeSource"; private static final String PARAMETER_THEME_CACHETIME = "ThemeCacheTime"; private static final String PARAMETER_MAX_TRANSFORMERS = "MaxTransformers"; private static final String PARAMETER_TRANSFORMER_CACHETIME = "TransformerCacheTime"; private static final int DEFAULT_THEME_CACHETIME = 1000 * 60 * 60 * 24; private static final int DEFAULT_BUFFER_SIZE = 32 * 1024; private static final int DEFAULT_MAX_TRANSFORMERS = 1; private static final int MAX_BUFFER_SIZE = 64 * 1024; private static final String SESSION_ATTR_VARMAP = "itmill-toolkit-varmap"; private static final String SESSION_ATTR_CONTEXT = "itmill-toolkit-context"; protected static final String SESSION_ATTR_APPS = "itmill-toolkit-apps"; private static final String SESSION_BINDING_LISTENER = "itmill-toolkit-bindinglistener"; // TODO Should default or base theme be the default? protected static final String DEFAULT_THEME = "base"; private static final String RESOURCE_URI = "/RES/"; private static final String AJAX_UIDL_URI = "/UIDL/"; private static final String THEME_DIRECTORY_PATH = "/WEB-INF/lib/themes/"; private static final String THEME_LISTING_FILE = THEME_DIRECTORY_PATH + "themes.txt"; private static final String DEFAULT_THEME_JAR_PREFIX = "itmill-toolkit-themes"; private static final String DEFAULT_THEME_JAR = "/WEB-INF/lib/" + DEFAULT_THEME_JAR_PREFIX + "-" + VERSION + ".jar"; private static final String DEFAULT_THEME_TEMP_FILE_PREFIX = "ITMILL_TMP_"; private static final String SERVER_COMMAND_PARAM = "SERVER_COMMANDS"; private static final int SERVER_COMMAND_STREAM_MAINTAIN_PERIOD = 15000; private static final int SERVER_COMMAND_HEADER_PADDING = 2000; // Maximum delay between request for an user to be considered active (in ms) private static final long ACTIVE_USER_REQUEST_INTERVAL = 1000 * 45; // Private fields private Class applicationClass; private Properties applicationProperties; private UIDLTransformerFactory transformerFactory; private CollectionThemeSource themeSource; private String resourcePath = null; private String debugMode = ""; private int maxConcurrentTransformers; private long transformerCacheTime; private long themeCacheTime; private WeakHashMap applicationToDirtyWindowSetMap = new WeakHashMap(); private WeakHashMap applicationToServerCommandStreamLock = new WeakHashMap(); private static WeakHashMap applicationToLastRequestDate = new WeakHashMap(); private List allWindows = new LinkedList(); private WeakHashMap applicationToAjaxAppMgrMap = new WeakHashMap(); private HashMap licenseForApplicationClass = new HashMap(); private static HashSet licensePrintedForApplicationClass = new HashSet(); /** * Called by the servlet container to indicate to a servlet that the servlet * is being placed into service. * * @param servletConfig * object containing the servlet's configuration and * initialization parameters * @throws ServletException * if an exception has occurred that interferes with the * servlet's normal operation. */ public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException { super.init(servletConfig); // Get the application class name String applicationClassName = servletConfig .getInitParameter("application"); if (applicationClassName == null) { Log.error("Application not specified in servlet parameters"); } // Store the application parameters into Properties object this.applicationProperties = new Properties(); for (Enumeration e = servletConfig.getInitParameterNames(); e .hasMoreElements();) { String name = (String) e.nextElement(); this.applicationProperties.setProperty(name, servletConfig .getInitParameter(name)); } // Override with server.xml parameters ServletContext context = servletConfig.getServletContext(); for (Enumeration e = context.getInitParameterNames(); e .hasMoreElements();) { String name = (String) e.nextElement(); this.applicationProperties.setProperty(name, context .getInitParameter(name)); } // Get the debug window parameter String debug = getApplicationOrSystemProperty(PARAMETER_DEBUG, "") .toLowerCase(); // Enable application specific debug if (!"".equals(debug) && !"true".equals(debug) && !"false".equals(debug)) throw new ServletException( "If debug parameter is given for an application, it must be 'true' or 'false'"); this.debugMode = debug; // Get the maximum number of simultaneous transformers this.maxConcurrentTransformers = Integer .parseInt(getApplicationOrSystemProperty( PARAMETER_MAX_TRANSFORMERS, "-1")); if (this.maxConcurrentTransformers < 1) this.maxConcurrentTransformers = DEFAULT_MAX_TRANSFORMERS; // Get cache time for transformers this.transformerCacheTime = Integer .parseInt(getApplicationOrSystemProperty( PARAMETER_TRANSFORMER_CACHETIME, "-1")) * 1000; // Get cache time for theme resources this.themeCacheTime = Integer.parseInt(getApplicationOrSystemProperty( PARAMETER_THEME_CACHETIME, "-1")) * 1000; if (this.themeCacheTime < 0) { this.themeCacheTime = DEFAULT_THEME_CACHETIME; } // Add all specified theme sources this.themeSource = new CollectionThemeSource(); List directorySources = getThemeSources(); for (Iterator i = directorySources.iterator(); i.hasNext();) { this.themeSource.add((ThemeSource) i.next()); } // Add the default theme source String[] defaultThemeFiles = new String[] { getApplicationOrSystemProperty( PARAMETER_DEFAULT_THEME_JAR, DEFAULT_THEME_JAR) }; File f = findDefaultThemeJar(defaultThemeFiles); try { // Add themes.jar if exists if (f != null && f.exists()) this.themeSource.add(new JarThemeSource(f, this, "")); else { Log.warn("Default theme JAR not found in: " + Arrays.asList(defaultThemeFiles)); } } catch (Exception e) { throw new ServletException("Failed to load default theme from " + Arrays.asList(defaultThemeFiles), e); } // Check that at least one themesource was loaded if (this.themeSource.getThemes().size() <= 0) { throw new ServletException( "No themes found in specified themesources."); } // Initialize the transformer factory, if not initialized if (this.transformerFactory == null) { this.transformerFactory = new UIDLTransformerFactory( this.themeSource, this, this.maxConcurrentTransformers, this.transformerCacheTime); } // Load the application class using the same class loader // as the servlet itself ClassLoader loader = this.getClass().getClassLoader(); try { this.applicationClass = loader.loadClass(applicationClassName); } catch (ClassNotFoundException e) { throw new ServletException("Failed to load application class: " + applicationClassName); } } /** * Get an application or system property value. * * @param parameterName * Name or the parameter * @param defaultValue * Default to be used * @return String value or default if not found */ private String getApplicationOrSystemProperty(String parameterName, String defaultValue) { // Try application properties String val = this.applicationProperties.getProperty(parameterName); if (val != null) { return val; } // Try lowercased application properties for backward compability with // 3.0.2 and earlier val = this.applicationProperties.getProperty(parameterName .toLowerCase()); if (val != null) { return val; } // Try system properties String pkgName; Package pkg = this.getClass().getPackage(); if (pkg != null) { pkgName = pkg.getName(); } else { String clazzName = this.getClass().getName(); pkgName = new String(clazzName.toCharArray(), 0, clazzName .lastIndexOf('.')); } val = System.getProperty(pkgName + "." + parameterName); if (val != null) { return val; } // Try lowercased system properties val = System.getProperty(pkgName + "." + parameterName.toLowerCase()); if (val != null) { return val; } return defaultValue; } /** * Get ThemeSources from given path. Construct the list of avalable themes * in path using the following sources: 1. content of THEME_PATH directory * (if available) 2. The themes listed in THEME_LIST_FILE 3. "themesource" * application parameter - "ThemeSource" system property * * @param THEME_DIRECTORY_PATH * @return List */ private List getThemeSources() throws ServletException { List returnValue = new LinkedList(); // Check the list file in theme directory List sourcePaths = new LinkedList(); try { BufferedReader reader = new BufferedReader(new InputStreamReader( this.getServletContext().getResourceAsStream( THEME_LISTING_FILE))); String line = null; while ((line = reader.readLine()) != null) { sourcePaths.add(THEME_DIRECTORY_PATH + line.trim()); } if (this.isDebugMode(null)) { Log.debug("Listed " + sourcePaths.size() + " themes in " + THEME_LISTING_FILE + ". Loading " + sourcePaths); } } catch (Exception ignored) { // If the file reading fails, just skip to next method } // If no file was found or it was empty, // try to add themes filesystem directory if it is accessible if (sourcePaths.size() <= 0) { if (this.isDebugMode(null)) { Log.debug("No themes listed in " + THEME_LISTING_FILE + ". Trying to read the content of directory " + THEME_DIRECTORY_PATH); } try { String path = getResourcePath(getServletContext(), THEME_DIRECTORY_PATH); if (path != null) { File f = new File(path); if (f != null && f.exists()) returnValue.add(new DirectoryThemeSource(f, this)); } } catch (java.io.IOException je) { Log.info("Theme directory " + THEME_DIRECTORY_PATH + " not available. Skipped."); } catch (ThemeException e) { throw new ServletException("Failed to load themes from " + THEME_DIRECTORY_PATH, e); } } // Add the theme sources from application properties String paramValue = getApplicationOrSystemProperty( PARAMETER_THEMESOURCE, null); if (paramValue != null) { StringTokenizer st = new StringTokenizer(paramValue, ";"); while (st.hasMoreTokens()) { sourcePaths.add(st.nextToken()); } } // Construct appropriate theme source instances for each path for (Iterator i = sourcePaths.iterator(); i.hasNext();) { String source = (String) i.next(); File sourceFile = new File(source); try { // Relative files are treated as streams (to support // resource inside WAR files) if (!sourceFile.isAbsolute()) { returnValue.add(new ServletThemeSource(this .getServletContext(), this, source)); } else if (sourceFile.isDirectory()) { // Absolute directories are read from filesystem returnValue.add(new DirectoryThemeSource(sourceFile, this)); } else { // Absolute JAR-files are read from filesystem returnValue.add(new JarThemeSource(sourceFile, this, "")); } } catch (Exception e) { // Any exception breaks the the init throw new ServletException("Invalid theme source: " + source, e); } } // Return the constructed list of theme sources return returnValue; } /** * Receives standard HTTP requests from the public service method and * dispatches them. * * @param request * object that contains the request the client made of the * servlet * @param response * object that contains the response the servlet returns to the * client * @throws ServletException * if an input or output error occurs while the servlet is * handling the TRACE request * @throws IOException * if the request for the TRACE cannot be handled */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Transformer and output stream for the result UIDLTransformer transformer = null; HttpVariableMap variableMap = null; OutputStream out = response.getOutputStream(); HashSet currentlyDirtyWindowsForThisApplication = new HashSet(); Application application = null; try { // Handle resource requests if (handleResourceRequest(request, response)) return; // Handle server commands if (handleServerCommands(request, response)) return; // Get the application application = getApplication(request); // Create application if it doesn't exist if (application == null) application = createApplication(request); // Set the last application request date applicationToLastRequestDate.put(application, new Date()); // Invoke context transaction listeners ((WebApplicationContext) application.getContext()) .startTransaction(application, request); // Is this a download request from application DownloadStream download = null; // The rest of the process is synchronized with the application // in order to guarantee that no parallel variable handling is // made synchronized (application) { // Handle UIDL requests? String resourceId = request.getPathInfo(); if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) { getApplicationManager(application).handleUidlRequest( request, response); return; } // Get the variable map variableMap = getVariableMap(application, request); if (variableMap == null) return; // Change all variables based on request parameters Map unhandledParameters = variableMap.handleVariables(request, application); // Check/handle client side feature checks WebBrowserProbe .handleProbeRequest(request, unhandledParameters); // If rendering mode is not defined or detecting requested // try to detect it WebBrowser wb = WebBrowserProbe.getTerminalType(request .getSession()); - if (unhandledParameters.get("renderingMode").equals("detect") + if ( "detect".equals(unhandledParameters.get("renderingMode")) || wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED) { String themeName = application.getTheme(); if (themeName == null) themeName = DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); String renderingMode = theme.getPreferredMode(wb, themeSource); if (Theme.MODE_AJAX.equals(renderingMode)) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } else { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } } if (unhandledParameters.get("renderingMode") != null) { String renderingMode = (String) ((Object[]) unhandledParameters .get("renderingMode"))[0]; if (renderingMode.equals("html")) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } else if(renderingMode.equals("ajax")){ wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } } // Handle the URI if the application is still running if (application.isRunning()) download = handleURI(application, request, response); // If this is not a download request if (download == null) { // Window renders are not cacheable response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); // Find the window within the application Window window = null; if (application.isRunning()) window = getApplicationWindow(request, application, unhandledParameters); // Handle the unhandled parameters if the application is // still running if (window != null && unhandledParameters != null && !unhandledParameters.isEmpty()) { try { window.handleParameters(unhandledParameters); } catch (Throwable t) { application .terminalError(new ParameterHandlerErrorImpl( window, t)); } } // Remove application if it has stopped if (!application.isRunning()) { endApplication(request, response, application); return; } // Return blank page, if no window found if (window == null) { response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head><script>"); page .write(ThemeFunctionLibrary .generateWindowScript( null, application, this, WebBrowserProbe .getTerminalType(request .getSession()))); page.write("</script></head><body>"); page .write("The requested window has been removed from application."); page.write("</body></html>"); page.close(); return; } // Set terminal type for the window, if not already set if (window.getTerminal() == null) { window.setTerminal(wb); } // Find theme String themeName = window.getTheme() != null ? window .getTheme() : DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); if (theme == null) throw new ServletException("Theme (named '" + themeName + "') can not be found"); // If in ajax rendering mode, print an html page for it if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_AJAX) { writeAjaxPage(request, response, out, unhandledParameters, window, wb, theme); return; } // If other than html or ajax mode is requested if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED && !(window instanceof DebugWindow)) { // TODO More informal message should be given is browser // is not supported response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head></head><body>"); page.write("Unsupported browser."); page.write("</body></html>"); page.close(); return; } // Initialize Transformer UIDLTransformerType transformerType = new UIDLTransformerType( wb, theme); transformer = this.transformerFactory .getTransformer(transformerType); // Set the response type response.setContentType(wb.getContentType()); // Create UIDL writer WebPaintTarget paintTarget = transformer .getPaintTarget(variableMap); // Assure that the correspoding debug window will be // repainted property // by clearing it before the actual paint. DebugWindow debugWindow = (DebugWindow) application .getWindow(DebugWindow.WINDOW_NAME); if (debugWindow != null && debugWindow != window) { debugWindow.setWindowUIDL(window, "Painting..."); } // Paint window window.paint(paintTarget); paintTarget.close(); // For exception handling, memorize the current dirty status Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap .get(application); if (dirtyWindows == null) { dirtyWindows = new HashSet(); applicationToDirtyWindowSetMap.put(application, dirtyWindows); } currentlyDirtyWindowsForThisApplication .addAll(dirtyWindows); // Window is now painted windowPainted(application, window); // Debug if (debugWindow != null && debugWindow != window) { debugWindow .setWindowUIDL(window, paintTarget.getUIDL()); } // Set the function library state for this thread ThemeFunctionLibrary.setState(application, window, transformerType.getWebBrowser(), request .getSession(), this, transformerType .getTheme().getName()); } } // For normal requests, transform the window if (download == null) { // Transform and output the result to browser // Note that the transform and transfer of the result is // not synchronized with the variable map. This allows // parallel transfers and transforms for better performance, // but requires that all calls from the XSL to java are // thread-safe transformer.transform(out); } // For download request, transfer the downloaded data else { handleDownload(download, request, response); } } catch (UIDLTransformerException te) { try { // Write the error report to client response.setContentType("text/html"); BufferedWriter err = new BufferedWriter(new OutputStreamWriter( out)); err .write("<html><head><title>Application Internal Error</title></head><body>"); err.write("<h1>" + te.getMessage() + "</h1>"); err.write(te.getHTMLDescription()); err.write("</body></html>"); err.close(); } catch (Throwable t) { Log.except("Failed to write error page: " + t + ". Original exception was: ", te); } // Add previously dirty windows to dirtyWindowList in order // to make sure that eventually they are repainted Application currentApplication = getApplication(request); for (Iterator iter = currentlyDirtyWindowsForThisApplication .iterator(); iter.hasNext();) { Window dirtyWindow = (Window) iter.next(); addDirtyWindow(currentApplication, dirtyWindow); } } catch (Throwable e) { // Re-throw other exceptions throw new ServletException(e); } finally { // Release transformer if (transformer != null) transformerFactory.releaseTransformer(transformer); // Notify transaction end if (application != null) ((WebApplicationContext) application.getContext()) .endTransaction(application, request); // Clean the function library state for this thread // for security reasons ThemeFunctionLibrary.cleanState(); } } private void writeAjaxPage(HttpServletRequest request, HttpServletResponse response, OutputStream out, Map unhandledParameters, Window window, WebBrowser terminalType, Theme theme) throws IOException, MalformedURLException { response.setContentType("text/html"); BufferedWriter page = new BufferedWriter(new OutputStreamWriter(out)); page .write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"); page .write("<html><head>\n<title>" + window.getCaption() + "</title>\n"); page .write("<NOSCRIPT><META http-equiv=\"refresh\" content=\"0; url=?WA_NOSCRIPT=1\" /></NOSCRIPT>\n"); Theme t = theme; Vector themes = new Vector(); themes.add(t); while (t.getParent() != null) { String parentName = t.getParent(); t = themeSource.getThemeByName(parentName); themes.add(t); } for (int k = themes.size() - 1; k >= 0; k--) { t = (Theme) themes.get(k); Collection files = t.getFileNames(terminalType, Theme.MODE_AJAX); for (Iterator i = files.iterator(); i.hasNext();) { String file = (String) i.next(); if (file.endsWith(".css")) page.write("<link rel=\"stylesheet\" href=\"" + getResourceLocation(t.getName(), new ThemeResource(file)) + "\" type=\"text/css\" />\n"); else if (file.endsWith(".js")) page.write("<script src=\"" + getResourceLocation(t.getName(), new ThemeResource(file)) + "\" type=\"text/javascript\"></script>\n"); } } page.write("</head><body class=\"itmtk\">\n"); page.write("<div id=\"ajax-wait\">Loading...</div>\n"); page.write("<div id=\"ajax-window\"></div>\n"); page.write("<script language=\"JavaScript\">\n"); String[] urlParts = getApplicationUrl(request).toString().split("\\/"); if (urlParts[2].endsWith(":80")) urlParts[2] = urlParts[2].substring(0, urlParts[2].length() - 3); String appUrl = ""; for (int i = 0; i < urlParts.length; i++) appUrl += (i > 0 ? "/" : "") + urlParts[i]; if (appUrl.endsWith("/")) appUrl = appUrl.substring(0, appUrl.length() - 1); page.write("itmill.tmp = new itmill.Client(" + "document.getElementById('ajax-window')," + "\"" + appUrl + "/UIDL/" + "\",\"" + resourcePath + ((Theme) themes.get(themes.size() - 1)).getName() + "/" + "client/\",document.getElementById('ajax-wait'));\n"); // TODO Only current theme is registered to the client // for (int k = themes.size() - 1; k >= 0; k--) { // t = (Theme) themes.get(k); t = theme; String themeObjName = "itmill.themes." + t.getName().substring(0, 1).toUpperCase() + t.getName().substring(1); page.write(" (new " + themeObjName + "(\"" + resourcePath + t.getName() + "/\")).registerTo(itmill.tmp);\n"); // } if (isDebugMode(unhandledParameters)) page.write("itmill.tmp.debugEnabled =true;\n"); page.write("itmill.tmp.start();\n"); page.write("delete itmill.tmp;\n"); page.write("</script>\n"); page.write("</body></html>\n"); page.close(); } /** * Handle the requested URI. An application can add handlers to do special * processing, when a certain URI is requested. The handlers are invoked * before any windows URIs are processed and if a DownloadStream is returned * it is sent to the client. * * @see com.itmill.toolkit.terminal.URIHandler * * @param application * Application owning the URI * @param request * HTTP request instance * @param response * HTTP response to write to. * @return boolean True if the request was handled and further processing * should be suppressed, false otherwise. */ private DownloadStream handleURI(Application application, HttpServletRequest request, HttpServletResponse response) { String uri = request.getPathInfo(); // If no URI is available if (uri == null || uri.length() == 0 || uri.equals("/")) return null; // Remove the leading / while (uri.startsWith("/") && uri.length() > 0) uri = uri.substring(1); // Handle the uri DownloadStream stream = null; try { stream = application.handleURI(application.getURL(), uri); } catch (Throwable t) { application.terminalError(new URIHandlerErrorImpl(application, t)); } return stream; } /** * Handle the requested URI. An application can add handlers to do special * processing, when a certain URI is requested. The handlers are invoked * before any windows URIs are processed and if a DownloadStream is returned * it is sent to the client. * * @see com.itmill.toolkit.terminal.URIHandler * * @param application * Application owning the URI * @param request * HTTP request instance * @param response * HTTP response to write to. * @return boolean True if the request was handled and further processing * should be suppressed, false otherwise. */ private void handleDownload(DownloadStream stream, HttpServletRequest request, HttpServletResponse response) { // Download from given stream InputStream data = stream.getStream(); if (data != null) { // Set content type response.setContentType(stream.getContentType()); // Set cache headers long cacheTime = stream.getCacheTime(); if (cacheTime <= 0) { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); } else { response.setHeader("Cache-Control", "max-age=" + cacheTime / 1000); response.setDateHeader("Expires", System.currentTimeMillis() + cacheTime); response.setHeader("Pragma", "cache"); // Required to apply // caching in some // Tomcats } // Copy download stream parameters directly // to HTTP headers. Iterator i = stream.getParameterNames(); if (i != null) { while (i.hasNext()) { String param = (String) i.next(); response.setHeader((String) param, stream .getParameter(param)); } } int bufferSize = stream.getBufferSize(); if (bufferSize <= 0 || bufferSize > MAX_BUFFER_SIZE) bufferSize = DEFAULT_BUFFER_SIZE; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; try { OutputStream out = response.getOutputStream(); while ((bytesRead = data.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); out.flush(); } out.close(); } catch (IOException ignored) { } } } /** * Look for default theme JAR file. * * @return Jar file or null if not found. */ private File findDefaultThemeJar(String[] fileList) { // Try to find the default theme JAR file based on the given path for (int i = 0; i < fileList.length; i++) { String path = getResourcePath(getServletContext(), fileList[i]); File file = null; if (path != null && (file = new File(path)).exists()) { return file; } } // If we do not have access to individual files, create a temporary // file from named resource. for (int i = 0; i < fileList.length; i++) { InputStream defaultTheme = this.getServletContext() .getResourceAsStream(fileList[i]); // Read the content to temporary file and return it if (defaultTheme != null) { return createTemporaryFile(defaultTheme, ".jar"); } } // Try to find the default theme JAR file based on file naming scheme // NOTE: This is for backward compability with 3.0.2 and earlier. String path = getResourcePath(getServletContext(), "/WEB-INF/lib"); if (path != null) { File lib = new File(path); String[] files = lib.list(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].toLowerCase().endsWith(".jar") && files[i].startsWith(DEFAULT_THEME_JAR_PREFIX)) { return new File(lib, files[i]); } } } } // If no file was found return null return null; } /** * Create a temporary file for given stream. * * @param stream * Stream to be stored into temporary file. * @param extension * File type extension * @return File */ private File createTemporaryFile(InputStream stream, String extension) { File tmpFile; try { tmpFile = File.createTempFile(DEFAULT_THEME_TEMP_FILE_PREFIX, extension); FileOutputStream out = new FileOutputStream(tmpFile); byte[] buf = new byte[1024]; int bytes = 0; while ((bytes = stream.read(buf)) > 0) { out.write(buf, 0, bytes); } out.close(); } catch (IOException e) { System.err .println("Failed to create temporary file for default theme: " + e); tmpFile = null; } return tmpFile; } /** * Handle theme resource file requests. Resources supplied with the themes * are provided by the WebAdapterServlet. * * @param request * HTTP request * @param response * HTTP response * @return boolean True if the request was handled and further processing * should be suppressed, false otherwise. */ private boolean handleResourceRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { // If the resource path is unassigned, initialize it if (resourcePath == null) resourcePath = request.getContextPath() + request.getServletPath() + RESOURCE_URI; String resourceId = request.getPathInfo(); // Check if this really is a resource request if (resourceId == null || !resourceId.startsWith(RESOURCE_URI)) return false; // Check the resource type resourceId = resourceId.substring(RESOURCE_URI.length()); InputStream data = null; // Get theme resources try { data = themeSource.getResource(resourceId); } catch (ThemeSource.ThemeException e) { Log.info(e.getMessage()); data = null; } // Write the response try { if (data != null) { response.setContentType(FileTypeResolver .getMIMEType(resourceId)); // Use default cache time for theme resources if (this.themeCacheTime > 0) { response.setHeader("Cache-Control", "max-age=" + this.themeCacheTime / 1000); response.setDateHeader("Expires", System .currentTimeMillis() + this.themeCacheTime); response.setHeader("Pragma", "cache"); // Required to apply // caching in some // Tomcats } // Write the data to client byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int bytesRead = 0; OutputStream out = response.getOutputStream(); while ((bytesRead = data.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); data.close(); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (java.io.IOException e) { Log.info("Resource transfer failed: " + request.getRequestURI() + ". (" + e.getMessage() + ")"); } return true; } /** Get the variable map for the session */ private static synchronized HttpVariableMap getVariableMap( Application application, HttpServletRequest request) { HttpSession session = request.getSession(); // Get the application to variablemap map Map varMapMap = (Map) session.getAttribute(SESSION_ATTR_VARMAP); if (varMapMap == null) { varMapMap = new WeakHashMap(); session.setAttribute(SESSION_ATTR_VARMAP, varMapMap); } // Create a variable map, if it does not exists. HttpVariableMap variableMap = (HttpVariableMap) varMapMap .get(application); if (variableMap == null) { variableMap = new HttpVariableMap(); varMapMap.put(application, variableMap); } return variableMap; } /** Get the current application URL from request */ private URL getApplicationUrl(HttpServletRequest request) throws MalformedURLException { URL applicationUrl; try { URL reqURL = new URL((request.isSecure() ? "https://" : "http://") + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI()); String servletPath = request.getContextPath() + request.getServletPath(); if (servletPath.length() == 0 || servletPath.charAt(servletPath.length() - 1) != '/') servletPath = servletPath + "/"; applicationUrl = new URL(reqURL, servletPath); } catch (MalformedURLException e) { Log.error("Error constructing application url " + request.getRequestURI() + " (" + e + ")"); throw e; } return applicationUrl; } /** * Get the existing application for given request. Looks for application * instance for given request based on the requested URL. * * @param request * HTTP request * @return Application instance, or null if the URL does not map to valid * application. */ private Application getApplication(HttpServletRequest request) throws MalformedURLException { // Ensure that the session is still valid HttpSession session = request.getSession(false); if (session == null) return null; // Get application list for the session. LinkedList applications = (LinkedList) session .getAttribute(SESSION_ATTR_APPS); if (applications == null) return null; // Search for the application (using the application URI) from the list Application application = null; for (Iterator i = applications.iterator(); i.hasNext() && application == null;) { Application a = (Application) i.next(); String aPath = a.getURL().getPath(); String servletPath = request.getContextPath() + request.getServletPath(); if (servletPath.length() < aPath.length()) servletPath += "/"; if (servletPath.equals(aPath)) application = a; } // Remove stopped applications from the list if (application != null && !application.isRunning()) { applications.remove(application); application = null; } return application; } /** * Create a new application. * * @return New application instance * @throws SAXException * @throws LicenseViolation * @throws InvalidLicenseFile * @throws LicenseSignatureIsInvalid * @throws LicenseFileHasNotBeenRead */ private Application createApplication(HttpServletRequest request) throws MalformedURLException, InstantiationException, IllegalAccessException, LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation, SAXException { Application application = null; // Get the application url URL applicationUrl = getApplicationUrl(request); // Get application list. HttpSession session = request.getSession(); if (session == null) return null; LinkedList applications = (LinkedList) session .getAttribute(SESSION_ATTR_APPS); if (applications == null) { applications = new LinkedList(); session.setAttribute(SESSION_ATTR_APPS, applications); HttpSessionBindingListener sessionBindingListener = new SessionBindingListener( applications); session.setAttribute(SESSION_BINDING_LISTENER, sessionBindingListener); } // Create new application and start it try { application = (Application) this.applicationClass.newInstance(); applications.add(application); // Listen to window add/removes (for web mode) application.addListener((Application.WindowAttachListener) this); application.addListener((Application.WindowDetachListener) this); // Set localte application.setLocale(request.getLocale()); // Get application context for this session WebApplicationContext context = (WebApplicationContext) session .getAttribute(SESSION_ATTR_CONTEXT); if (context == null) { context = new WebApplicationContext(session); session.setAttribute(SESSION_ATTR_CONTEXT, context); } // Start application and check license initializeLicense(application); application.start(applicationUrl, this.applicationProperties, context); checkLicense(application); } catch (IllegalAccessException e) { Log.error("Illegal access to application class " + this.applicationClass.getName()); throw e; } catch (InstantiationException e) { Log.error("Failed to instantiate application class: " + this.applicationClass.getName()); throw e; } return application; } private void initializeLicense(Application application) { License license = (License) licenseForApplicationClass.get(application .getClass()); if (license == null) { license = new License(); licenseForApplicationClass.put(application.getClass(), license); } application.setToolkitLicense(license); } private void checkLicense(Application application) throws LicenseFileHasNotBeenRead, LicenseSignatureIsInvalid, InvalidLicenseFile, LicenseViolation, SAXException { License license = application.getToolkitLicense(); if (!license.hasBeenRead()) { InputStream lis; try { lis = getServletContext().getResource( "/WEB-INF/itmill-toolkit-license.xml").openStream(); license.readLicenseFile(lis); } catch (MalformedURLException e) { // This should not happen throw new RuntimeException(e); } catch (IOException e) { // This should not happen throw new RuntimeException(e); } catch (LicenseFileHasAlreadyBeenRead e) { // This should not happen throw new RuntimeException(e); } } // For each application class, print license description - once if (!licensePrintedForApplicationClass.contains(applicationClass)) { licensePrintedForApplicationClass.add(applicationClass); if (license.shouldLimitsBePrintedOnInit()) System.out.print(license.getDescription()); } // Check license validity try { license.check(applicationClass, getNumberOfActiveUsers() + 1, VERSION_MAJOR, VERSION_MINOR, "IT Mill Toolkit", null); } catch (LicenseFileHasNotBeenRead e) { application.close(); throw e; } catch (LicenseSignatureIsInvalid e) { application.close(); throw e; } catch (InvalidLicenseFile e) { application.close(); throw e; } catch (LicenseViolation e) { application.close(); throw e; } } /** * Get the number of active application-user pairs. * * This returns total number of all applications in the server that are * considered to be active. For an application to be active, it must have * been accessed less than ACTIVE_USER_REQUEST_INTERVAL ms. * * @return Number of active application instances in the server. */ private int getNumberOfActiveUsers() { Set apps = applicationToLastRequestDate.keySet(); int active = 0; long now = System.currentTimeMillis(); for (Iterator i = apps.iterator(); i.hasNext();) { Date lastReq = (Date) applicationToLastRequestDate.get(i.next()); if (now - lastReq.getTime() < ACTIVE_USER_REQUEST_INTERVAL) active++; } return active; } /** End application */ private void endApplication(HttpServletRequest request, HttpServletResponse response, Application application) throws IOException { String logoutUrl = application.getLogoutURL(); if (logoutUrl == null) logoutUrl = application.getURL().toString(); HttpSession session = request.getSession(); if (session != null) { LinkedList applications = (LinkedList) session .getAttribute(SESSION_ATTR_APPS); if (applications != null) applications.remove(application); } response.sendRedirect(response.encodeRedirectURL(logoutUrl)); } /** * Get the existing application or create a new one. Get a window within an * application based on the requested URI. * * @param request * HTTP Request. * @param application * Application to query for window. * @return Window mathing the given URI or null if not found. */ private Window getApplicationWindow(HttpServletRequest request, Application application, Map params) throws ServletException { Window window = null; // Find the window where the request is handled String path = request.getPathInfo(); // Main window as the URI is empty if (path == null || path.length() == 0 || path.equals("/")) window = application.getMainWindow(); // Try to search by window name else { String windowName = null; if (path.charAt(0) == '/') path = path.substring(1); int index = path.indexOf('/'); if (index < 0) { windowName = path; path = ""; } else { windowName = path.substring(0, index); path = path.substring(index + 1); } window = application.getWindow(windowName); if (window == null) { // If the window has existed, and is now removed // send a blank page if (allWindows.contains(windowName)) return null; // By default, we use main window window = application.getMainWindow(); } else if (!window.isVisible()) { // Implicitly painting without actually invoking paint() window.requestRepaintRequests(); // If the window is invisible send a blank page return null; } } // Create and open new debug window for application if requested Window debugWindow = application.getWindow(DebugWindow.WINDOW_NAME); if (debugWindow == null) { if (isDebugMode(params) && WebBrowserProbe.getTerminalType(request.getSession()) .getRenderingMode() != WebBrowser.RENDERING_MODE_AJAX) { try { debugWindow = new DebugWindow(application, request .getSession(false), this); debugWindow.setWidth(370); debugWindow.setHeight(480); application.addWindow(debugWindow); } catch (Exception e) { throw new ServletException( "Failed to create debug window for application", e); } } } else if (window != debugWindow) { if (isDebugMode(params)) debugWindow.requestRepaint(); else application.removeWindow(debugWindow); } return window; } /** * Get relative location of a theme resource. * * @param theme * Theme name * @param resource * Theme resource * @return External URI specifying the resource */ public String getResourceLocation(String theme, ThemeResource resource) { if (resourcePath == null) return resource.getResourceId(); return resourcePath + theme + "/" + resource.getResourceId(); } /** * Check if web adapter is in debug mode. Extra output is generated to log * when debug mode is enabled. * * @return Debug mode */ public boolean isDebugMode(Map parameters) { if (parameters != null) { Object[] debug = (Object[]) parameters.get("debug"); if (debug != null && !"false".equals(debug[0].toString()) && !"false".equals(debugMode)) return true; } return "true".equals(debugMode); } /** * Returns the theme source. * * @return ThemeSource */ public ThemeSource getThemeSource() { return themeSource; } protected void addDirtyWindow(Application application, Window window) { synchronized (applicationToDirtyWindowSetMap) { HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap .get(application); if (dirtyWindows == null) { dirtyWindows = new HashSet(); applicationToDirtyWindowSetMap.put(application, dirtyWindows); } dirtyWindows.add(window); } } protected void removeDirtyWindow(Application application, Window window) { synchronized (applicationToDirtyWindowSetMap) { HashSet dirtyWindows = (HashSet) applicationToDirtyWindowSetMap .get(application); if (dirtyWindows != null) dirtyWindows.remove(window); } } /** * @see com.itmill.toolkit.Application.WindowAttachListener#windowAttached(Application.WindowAttachEvent) */ public void windowAttached(WindowAttachEvent event) { Window win = event.getWindow(); win.addListener((Paintable.RepaintRequestListener) this); // Add to window names allWindows.add(win.getName()); // Add window to dirty window references if it is visible // Or request the window to pass on the repaint requests if (win.isVisible()) addDirtyWindow(event.getApplication(), win); else win.requestRepaintRequests(); } /** * @see com.itmill.toolkit.Application.WindowDetachListener#windowDetached(Application.WindowDetachEvent) */ public void windowDetached(WindowDetachEvent event) { event.getWindow().removeListener( (Paintable.RepaintRequestListener) this); // Add dirty window reference for closing the window addDirtyWindow(event.getApplication(), event.getWindow()); } /** * @see com.itmill.toolkit.terminal.Paintable.RepaintRequestListener#repaintRequested(Paintable.RepaintRequestEvent) */ public void repaintRequested(RepaintRequestEvent event) { Paintable p = event.getPaintable(); Application app = null; if (p instanceof Window) app = ((Window) p).getApplication(); if (app != null) addDirtyWindow(app, ((Window) p)); Object lock = applicationToServerCommandStreamLock.get(app); if (lock != null) synchronized (lock) { lock.notifyAll(); } } /** Get the list of dirty windows in application */ protected Set getDirtyWindows(Application app) { HashSet dirtyWindows; synchronized (applicationToDirtyWindowSetMap) { dirtyWindows = (HashSet) applicationToDirtyWindowSetMap.get(app); } return dirtyWindows; } /** Remove a window from the list of dirty windows */ private void windowPainted(Application app, Window window) { removeDirtyWindow(app, window); } /** * Generate server commands stream. If the server commands are not * requested, return false */ private boolean handleServerCommands(HttpServletRequest request, HttpServletResponse response) { // Server commands are allways requested with certain parameter if (request.getParameter(SERVER_COMMAND_PARAM) == null) return false; // Get the application Application application; try { application = getApplication(request); } catch (MalformedURLException e) { return false; } if (application == null) return false; // Create continuous server commands stream try { // Writer for writing the stream PrintWriter w = new PrintWriter(response.getOutputStream()); // Print necessary http page headers and padding w.println("<html><head></head><body>"); for (int i = 0; i < SERVER_COMMAND_HEADER_PADDING; i++) w.print(' '); // Clock for synchronizing the stream Object lock = new Object(); synchronized (applicationToServerCommandStreamLock) { Object oldlock = applicationToServerCommandStreamLock .get(application); if (oldlock != null) synchronized (oldlock) { oldlock.notifyAll(); } applicationToServerCommandStreamLock.put(application, lock); } while (applicationToServerCommandStreamLock.get(application) == lock && application.isRunning()) { synchronized (application) { // Session expiration Date lastRequest = (Date) applicationToLastRequestDate .get(application); if (lastRequest != null && lastRequest.getTime() + request.getSession() .getMaxInactiveInterval() * 1000 < System .currentTimeMillis()) { // Session expired, close application application.close(); } else { // Application still alive - keep updating windows Set dws = getDirtyWindows(application); if (dws != null && !dws.isEmpty()) { // For one of the dirty windows (in each // application) // request redraw Window win = (Window) dws.iterator().next(); w .println("<script>\n" + ThemeFunctionLibrary .getWindowRefreshScript( application, win, WebBrowserProbe .getTerminalType(request .getSession())) + "</script>"); removeDirtyWindow(application, win); // Windows that are closed immediately are "painted" // now if (win.getApplication() == null || !win.isVisible()) win.requestRepaintRequests(); } } } // Send the generated commands and newline immediately to // browser w.println(" "); w.flush(); response.flushBuffer(); synchronized (lock) { try { lock.wait(SERVER_COMMAND_STREAM_MAINTAIN_PERIOD); } catch (InterruptedException ignored) { } } } } catch (IOException ignore) { // In case of an Exceptions the server command stream is // terminated synchronized (applicationToServerCommandStreamLock) { if (applicationToServerCommandStreamLock.get(application) == application) applicationToServerCommandStreamLock.remove(application); } } return true; } private class SessionBindingListener implements HttpSessionBindingListener { private LinkedList applications; protected SessionBindingListener(LinkedList applications) { this.applications = applications; } /** * @see javax.servlet.http.HttpSessionBindingListener#valueBound(HttpSessionBindingEvent) */ public void valueBound(HttpSessionBindingEvent arg0) { // We are not interested in bindings } /** * @see javax.servlet.http.HttpSessionBindingListener#valueUnbound(HttpSessionBindingEvent) */ public void valueUnbound(HttpSessionBindingEvent event) { // If the binding listener is unbound from the session, the // session must be closing if (event.getName().equals(SESSION_BINDING_LISTENER)) { // Close all applications Object[] apps = applications.toArray(); for (int i = 0; i < apps.length; i++) { if (apps[i] != null) { // Close app ((Application) apps[i]).close(); // Stop application server commands stream Object lock = applicationToServerCommandStreamLock .get(apps[i]); if (lock != null) synchronized (lock) { lock.notifyAll(); } applicationToServerCommandStreamLock.remove(apps[i]); // Remove application from applications list applications.remove(apps[i]); } } } } } /** Implementation of ParameterHandler.ErrorEvent interface. */ public class ParameterHandlerErrorImpl implements ParameterHandler.ErrorEvent { private ParameterHandler owner; private Throwable throwable; private ParameterHandlerErrorImpl(ParameterHandler owner, Throwable throwable) { this.owner = owner; this.throwable = throwable; } /** * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable() */ public Throwable getThrowable() { return this.throwable; } /** * @see com.itmill.toolkit.terminal.ParameterHandler.ErrorEvent#getParameterHandler() */ public ParameterHandler getParameterHandler() { return this.owner; } } /** Implementation of URIHandler.ErrorEvent interface. */ public class URIHandlerErrorImpl implements URIHandler.ErrorEvent { private URIHandler owner; private Throwable throwable; private URIHandlerErrorImpl(URIHandler owner, Throwable throwable) { this.owner = owner; this.throwable = throwable; } /** * @see com.itmill.toolkit.terminal.Terminal.ErrorEvent#getThrowable() */ public Throwable getThrowable() { return this.throwable; } /** * @see com.itmill.toolkit.terminal.URIHandler.ErrorEvent#getURIHandler() */ public URIHandler getURIHandler() { return this.owner; } } /** * Get AJAX application manager for an application. * * If this application has not been running in ajax mode before, new manager * is created and web adapter stops listening to changes. * * @param application * @return AJAX Application Manager */ private AjaxApplicationManager getApplicationManager(Application application) { AjaxApplicationManager mgr = (AjaxApplicationManager) applicationToAjaxAppMgrMap .get(application); // This application is going from Web to AJAX mode, create new manager if (mgr == null) { // Create new manager mgr = new AjaxApplicationManager(application); applicationToAjaxAppMgrMap.put(application, mgr); // Stop sending changes to this servlet because manager will take // control application.removeListener((Application.WindowAttachListener) this); application.removeListener((Application.WindowDetachListener) this); // Deregister all window listeners for (Iterator wins = application.getWindows().iterator(); wins .hasNext();) ((Window) wins.next()) .removeListener((Paintable.RepaintRequestListener) this); // Manager takes control over the application mgr.takeControl(); } return mgr; } /** * Get resource path using different implementations. Required fo supporting * different servlet container implementations (application servers). * * @param path * @return */ protected static String getResourcePath(ServletContext servletContext, String path) { String resultPath = null; resultPath = servletContext.getRealPath(path); if (resultPath != null) { return resultPath; } else { try { URL url = servletContext.getResource(path); resultPath = url.getFile(); } catch (Exception e) { // ignored } } return resultPath; } }
true
true
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Transformer and output stream for the result UIDLTransformer transformer = null; HttpVariableMap variableMap = null; OutputStream out = response.getOutputStream(); HashSet currentlyDirtyWindowsForThisApplication = new HashSet(); Application application = null; try { // Handle resource requests if (handleResourceRequest(request, response)) return; // Handle server commands if (handleServerCommands(request, response)) return; // Get the application application = getApplication(request); // Create application if it doesn't exist if (application == null) application = createApplication(request); // Set the last application request date applicationToLastRequestDate.put(application, new Date()); // Invoke context transaction listeners ((WebApplicationContext) application.getContext()) .startTransaction(application, request); // Is this a download request from application DownloadStream download = null; // The rest of the process is synchronized with the application // in order to guarantee that no parallel variable handling is // made synchronized (application) { // Handle UIDL requests? String resourceId = request.getPathInfo(); if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) { getApplicationManager(application).handleUidlRequest( request, response); return; } // Get the variable map variableMap = getVariableMap(application, request); if (variableMap == null) return; // Change all variables based on request parameters Map unhandledParameters = variableMap.handleVariables(request, application); // Check/handle client side feature checks WebBrowserProbe .handleProbeRequest(request, unhandledParameters); // If rendering mode is not defined or detecting requested // try to detect it WebBrowser wb = WebBrowserProbe.getTerminalType(request .getSession()); if (unhandledParameters.get("renderingMode").equals("detect") || wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED) { String themeName = application.getTheme(); if (themeName == null) themeName = DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); String renderingMode = theme.getPreferredMode(wb, themeSource); if (Theme.MODE_AJAX.equals(renderingMode)) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } else { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } } if (unhandledParameters.get("renderingMode") != null) { String renderingMode = (String) ((Object[]) unhandledParameters .get("renderingMode"))[0]; if (renderingMode.equals("html")) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } else if(renderingMode.equals("ajax")){ wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } } // Handle the URI if the application is still running if (application.isRunning()) download = handleURI(application, request, response); // If this is not a download request if (download == null) { // Window renders are not cacheable response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); // Find the window within the application Window window = null; if (application.isRunning()) window = getApplicationWindow(request, application, unhandledParameters); // Handle the unhandled parameters if the application is // still running if (window != null && unhandledParameters != null && !unhandledParameters.isEmpty()) { try { window.handleParameters(unhandledParameters); } catch (Throwable t) { application .terminalError(new ParameterHandlerErrorImpl( window, t)); } } // Remove application if it has stopped if (!application.isRunning()) { endApplication(request, response, application); return; } // Return blank page, if no window found if (window == null) { response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head><script>"); page .write(ThemeFunctionLibrary .generateWindowScript( null, application, this, WebBrowserProbe .getTerminalType(request .getSession()))); page.write("</script></head><body>"); page .write("The requested window has been removed from application."); page.write("</body></html>"); page.close(); return; } // Set terminal type for the window, if not already set if (window.getTerminal() == null) { window.setTerminal(wb); } // Find theme String themeName = window.getTheme() != null ? window .getTheme() : DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); if (theme == null) throw new ServletException("Theme (named '" + themeName + "') can not be found"); // If in ajax rendering mode, print an html page for it if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_AJAX) { writeAjaxPage(request, response, out, unhandledParameters, window, wb, theme); return; } // If other than html or ajax mode is requested if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED && !(window instanceof DebugWindow)) { // TODO More informal message should be given is browser // is not supported response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head></head><body>"); page.write("Unsupported browser."); page.write("</body></html>"); page.close(); return; } // Initialize Transformer UIDLTransformerType transformerType = new UIDLTransformerType( wb, theme); transformer = this.transformerFactory .getTransformer(transformerType); // Set the response type response.setContentType(wb.getContentType()); // Create UIDL writer WebPaintTarget paintTarget = transformer .getPaintTarget(variableMap); // Assure that the correspoding debug window will be // repainted property // by clearing it before the actual paint. DebugWindow debugWindow = (DebugWindow) application .getWindow(DebugWindow.WINDOW_NAME); if (debugWindow != null && debugWindow != window) { debugWindow.setWindowUIDL(window, "Painting..."); } // Paint window window.paint(paintTarget); paintTarget.close(); // For exception handling, memorize the current dirty status Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap .get(application); if (dirtyWindows == null) { dirtyWindows = new HashSet(); applicationToDirtyWindowSetMap.put(application, dirtyWindows); } currentlyDirtyWindowsForThisApplication .addAll(dirtyWindows); // Window is now painted windowPainted(application, window); // Debug if (debugWindow != null && debugWindow != window) { debugWindow .setWindowUIDL(window, paintTarget.getUIDL()); } // Set the function library state for this thread ThemeFunctionLibrary.setState(application, window, transformerType.getWebBrowser(), request .getSession(), this, transformerType .getTheme().getName()); } } // For normal requests, transform the window if (download == null) { // Transform and output the result to browser // Note that the transform and transfer of the result is // not synchronized with the variable map. This allows // parallel transfers and transforms for better performance, // but requires that all calls from the XSL to java are // thread-safe transformer.transform(out); } // For download request, transfer the downloaded data else { handleDownload(download, request, response); } } catch (UIDLTransformerException te) { try { // Write the error report to client response.setContentType("text/html"); BufferedWriter err = new BufferedWriter(new OutputStreamWriter( out)); err .write("<html><head><title>Application Internal Error</title></head><body>"); err.write("<h1>" + te.getMessage() + "</h1>"); err.write(te.getHTMLDescription()); err.write("</body></html>"); err.close(); } catch (Throwable t) { Log.except("Failed to write error page: " + t + ". Original exception was: ", te); } // Add previously dirty windows to dirtyWindowList in order // to make sure that eventually they are repainted Application currentApplication = getApplication(request); for (Iterator iter = currentlyDirtyWindowsForThisApplication .iterator(); iter.hasNext();) { Window dirtyWindow = (Window) iter.next(); addDirtyWindow(currentApplication, dirtyWindow); } } catch (Throwable e) { // Re-throw other exceptions throw new ServletException(e); } finally { // Release transformer if (transformer != null) transformerFactory.releaseTransformer(transformer); // Notify transaction end if (application != null) ((WebApplicationContext) application.getContext()) .endTransaction(application, request); // Clean the function library state for this thread // for security reasons ThemeFunctionLibrary.cleanState(); } }
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Transformer and output stream for the result UIDLTransformer transformer = null; HttpVariableMap variableMap = null; OutputStream out = response.getOutputStream(); HashSet currentlyDirtyWindowsForThisApplication = new HashSet(); Application application = null; try { // Handle resource requests if (handleResourceRequest(request, response)) return; // Handle server commands if (handleServerCommands(request, response)) return; // Get the application application = getApplication(request); // Create application if it doesn't exist if (application == null) application = createApplication(request); // Set the last application request date applicationToLastRequestDate.put(application, new Date()); // Invoke context transaction listeners ((WebApplicationContext) application.getContext()) .startTransaction(application, request); // Is this a download request from application DownloadStream download = null; // The rest of the process is synchronized with the application // in order to guarantee that no parallel variable handling is // made synchronized (application) { // Handle UIDL requests? String resourceId = request.getPathInfo(); if (resourceId != null && resourceId.startsWith(AJAX_UIDL_URI)) { getApplicationManager(application).handleUidlRequest( request, response); return; } // Get the variable map variableMap = getVariableMap(application, request); if (variableMap == null) return; // Change all variables based on request parameters Map unhandledParameters = variableMap.handleVariables(request, application); // Check/handle client side feature checks WebBrowserProbe .handleProbeRequest(request, unhandledParameters); // If rendering mode is not defined or detecting requested // try to detect it WebBrowser wb = WebBrowserProbe.getTerminalType(request .getSession()); if ( "detect".equals(unhandledParameters.get("renderingMode")) || wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED) { String themeName = application.getTheme(); if (themeName == null) themeName = DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); String renderingMode = theme.getPreferredMode(wb, themeSource); if (Theme.MODE_AJAX.equals(renderingMode)) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } else { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } } if (unhandledParameters.get("renderingMode") != null) { String renderingMode = (String) ((Object[]) unhandledParameters .get("renderingMode"))[0]; if (renderingMode.equals("html")) { wb.setRenderingMode(WebBrowser.RENDERING_MODE_HTML); } else if(renderingMode.equals("ajax")){ wb.setRenderingMode(WebBrowser.RENDERING_MODE_AJAX); } } // Handle the URI if the application is still running if (application.isRunning()) download = handleURI(application, request, response); // If this is not a download request if (download == null) { // Window renders are not cacheable response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); // Find the window within the application Window window = null; if (application.isRunning()) window = getApplicationWindow(request, application, unhandledParameters); // Handle the unhandled parameters if the application is // still running if (window != null && unhandledParameters != null && !unhandledParameters.isEmpty()) { try { window.handleParameters(unhandledParameters); } catch (Throwable t) { application .terminalError(new ParameterHandlerErrorImpl( window, t)); } } // Remove application if it has stopped if (!application.isRunning()) { endApplication(request, response, application); return; } // Return blank page, if no window found if (window == null) { response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head><script>"); page .write(ThemeFunctionLibrary .generateWindowScript( null, application, this, WebBrowserProbe .getTerminalType(request .getSession()))); page.write("</script></head><body>"); page .write("The requested window has been removed from application."); page.write("</body></html>"); page.close(); return; } // Set terminal type for the window, if not already set if (window.getTerminal() == null) { window.setTerminal(wb); } // Find theme String themeName = window.getTheme() != null ? window .getTheme() : DEFAULT_THEME; if (unhandledParameters.get("theme") != null) { themeName = (String) ((Object[]) unhandledParameters .get("theme"))[0]; } Theme theme = themeSource.getThemeByName(themeName); if (theme == null) throw new ServletException("Theme (named '" + themeName + "') can not be found"); // If in ajax rendering mode, print an html page for it if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_AJAX) { writeAjaxPage(request, response, out, unhandledParameters, window, wb, theme); return; } // If other than html or ajax mode is requested if (wb.getRenderingMode() == WebBrowser.RENDERING_MODE_UNDEFINED && !(window instanceof DebugWindow)) { // TODO More informal message should be given is browser // is not supported response.setContentType("text/html"); BufferedWriter page = new BufferedWriter( new OutputStreamWriter(out)); page.write("<html><head></head><body>"); page.write("Unsupported browser."); page.write("</body></html>"); page.close(); return; } // Initialize Transformer UIDLTransformerType transformerType = new UIDLTransformerType( wb, theme); transformer = this.transformerFactory .getTransformer(transformerType); // Set the response type response.setContentType(wb.getContentType()); // Create UIDL writer WebPaintTarget paintTarget = transformer .getPaintTarget(variableMap); // Assure that the correspoding debug window will be // repainted property // by clearing it before the actual paint. DebugWindow debugWindow = (DebugWindow) application .getWindow(DebugWindow.WINDOW_NAME); if (debugWindow != null && debugWindow != window) { debugWindow.setWindowUIDL(window, "Painting..."); } // Paint window window.paint(paintTarget); paintTarget.close(); // For exception handling, memorize the current dirty status Collection dirtyWindows = (Collection) applicationToDirtyWindowSetMap .get(application); if (dirtyWindows == null) { dirtyWindows = new HashSet(); applicationToDirtyWindowSetMap.put(application, dirtyWindows); } currentlyDirtyWindowsForThisApplication .addAll(dirtyWindows); // Window is now painted windowPainted(application, window); // Debug if (debugWindow != null && debugWindow != window) { debugWindow .setWindowUIDL(window, paintTarget.getUIDL()); } // Set the function library state for this thread ThemeFunctionLibrary.setState(application, window, transformerType.getWebBrowser(), request .getSession(), this, transformerType .getTheme().getName()); } } // For normal requests, transform the window if (download == null) { // Transform and output the result to browser // Note that the transform and transfer of the result is // not synchronized with the variable map. This allows // parallel transfers and transforms for better performance, // but requires that all calls from the XSL to java are // thread-safe transformer.transform(out); } // For download request, transfer the downloaded data else { handleDownload(download, request, response); } } catch (UIDLTransformerException te) { try { // Write the error report to client response.setContentType("text/html"); BufferedWriter err = new BufferedWriter(new OutputStreamWriter( out)); err .write("<html><head><title>Application Internal Error</title></head><body>"); err.write("<h1>" + te.getMessage() + "</h1>"); err.write(te.getHTMLDescription()); err.write("</body></html>"); err.close(); } catch (Throwable t) { Log.except("Failed to write error page: " + t + ". Original exception was: ", te); } // Add previously dirty windows to dirtyWindowList in order // to make sure that eventually they are repainted Application currentApplication = getApplication(request); for (Iterator iter = currentlyDirtyWindowsForThisApplication .iterator(); iter.hasNext();) { Window dirtyWindow = (Window) iter.next(); addDirtyWindow(currentApplication, dirtyWindow); } } catch (Throwable e) { // Re-throw other exceptions throw new ServletException(e); } finally { // Release transformer if (transformer != null) transformerFactory.releaseTransformer(transformer); // Notify transaction end if (application != null) ((WebApplicationContext) application.getContext()) .endTransaction(application, request); // Clean the function library state for this thread // for security reasons ThemeFunctionLibrary.cleanState(); } }
diff --git a/jnalib/test/com/sun/jna/CallbacksTest.java b/jnalib/test/com/sun/jna/CallbacksTest.java index de7bed24..a71eee91 100644 --- a/jnalib/test/com/sun/jna/CallbacksTest.java +++ b/jnalib/test/com/sun/jna/CallbacksTest.java @@ -1,163 +1,173 @@ /* Copyright (c) 2007 Timothy Wall, All Rights Reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * <p/> * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package com.sun.jna; import java.lang.ref.WeakReference; import java.util.Map; import com.sun.jna.Library.Handler.CallbackReference; import junit.framework.TestCase; /** Exercise a range of native methods. * * @author [email protected] */ public class CallbacksTest extends TestCase { private static final double DOUBLE_MAGIC = -118.625d; private static final float FLOAT_MAGIC = -118.625f; public static interface TestLibrary extends Library { TestLibrary INSTANCE = (TestLibrary) Native.loadLibrary("testlib", TestLibrary.class); interface VoidCallback extends Callback { void callback(); } void callVoidCallback(VoidCallback c); interface Int32Callback extends Callback { int callback(int arg, int arg2); } int callInt32Callback(Int32Callback c, int arg, int arg2); interface Int64Callback extends Callback { long callback(long arg, long arg2); } long callInt64Callback(Int64Callback c, long arg, long arg2); interface FloatCallback extends Callback { float callback(float arg, float arg2); } float callFloatCallback(FloatCallback c, float arg, float arg2); interface DoubleCallback extends Callback { double callback(double arg, double arg2); } double callDoubleCallback(DoubleCallback c, double arg, double arg2); } TestLibrary lib; protected void setUp() { lib = TestLibrary.INSTANCE; } protected void tearDown() { lib = null; } public void testGCCallback() throws Exception { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); Map refs = Library.Handler.callbackMap; assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); Pointer cbstruct = ref.cbstruct; cb = null; System.gc(); + for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { + try { + Thread.sleep(1); // Give the GC a chance to run + } finally {} + } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); + for (int i = 0; i < 100 && cbstruct.peer != 0; ++i) { + try { + Thread.sleep(1); // Give the GC a chance to run + } finally {} + } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); } public void testCallInt32Callback() { final int MAGIC = 0x11111111; final boolean[] called = { false }; TestLibrary.Int32Callback cb = new TestLibrary.Int32Callback() { public int callback(int arg, int arg2) { called[0] = true; return arg + arg2; } }; final int EXPECTED = MAGIC*3; int value = lib.callInt32Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", Integer.toHexString(EXPECTED), Integer.toHexString(value)); value = lib.callInt32Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } public void testCallInt64Callback() { final long MAGIC = 0x1111111111111111L; final boolean[] called = { false }; TestLibrary.Int64Callback cb = new TestLibrary.Int64Callback() { public long callback(long arg, long arg2) { called[0] = true; return arg + arg2; } }; final long EXPECTED = MAGIC*3; long value = lib.callInt64Callback(cb, MAGIC, MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", Long.toHexString(EXPECTED), Long.toHexString(value)); value = lib.callInt64Callback(cb, -1, -2); assertEquals("Wrong callback return", -3, value); } public void testCallFloatCallback() { final boolean[] called = { false }; TestLibrary.FloatCallback cb = new TestLibrary.FloatCallback() { public float callback(float arg, float arg2) { called[0] = true; return arg + arg2; } }; final float EXPECTED = FLOAT_MAGIC*3; float value = lib.callFloatCallback(cb, FLOAT_MAGIC, FLOAT_MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", EXPECTED, value, 0); value = lib.callFloatCallback(cb, -1f, -2f); assertEquals("Wrong callback return", -3f, value, 0); } public void testCallDoubleCallback() { final boolean[] called = { false }; TestLibrary.DoubleCallback cb = new TestLibrary.DoubleCallback() { public double callback(double arg, double arg2) { called[0] = true; return arg + arg2; } }; final double EXPECTED = DOUBLE_MAGIC*3; double value = lib.callDoubleCallback(cb, DOUBLE_MAGIC, DOUBLE_MAGIC*2); assertTrue("Callback not called", called[0]); assertEquals("Wrong callback value", EXPECTED, value, 0); value = lib.callDoubleCallback(cb, -1d, -2d); assertEquals("Wrong callback return", -3d, value, 0); } public static void main(java.lang.String[] argList) { junit.textui.TestRunner.run(CallbacksTest.class); } }
false
true
public void testGCCallback() throws Exception { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); Map refs = Library.Handler.callbackMap; assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); Pointer cbstruct = ref.cbstruct; cb = null; System.gc(); assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); assertEquals("Callback trampoline not freed", 0, cbstruct.peer); }
public void testGCCallback() throws Exception { final boolean[] called = { false }; TestLibrary.VoidCallback cb = new TestLibrary.VoidCallback() { public void callback() { called[0] = true; } }; lib.callVoidCallback(cb); assertTrue("Callback not called", called[0]); Map refs = Library.Handler.callbackMap; assertTrue("Callback not cached", refs.containsKey(cb)); CallbackReference ref = (CallbackReference)refs.get(cb); Pointer cbstruct = ref.cbstruct; cb = null; System.gc(); for (int i = 0; i < 100 && (ref.get() != null || refs.containsValue(ref)); ++i) { try { Thread.sleep(1); // Give the GC a chance to run } finally {} } assertNull("Callback not GC'd", ref.get()); assertFalse("Callback still in map", refs.containsValue(ref)); ref = null; System.gc(); for (int i = 0; i < 100 && cbstruct.peer != 0; ++i) { try { Thread.sleep(1); // Give the GC a chance to run } finally {} } assertEquals("Callback trampoline not freed", 0, cbstruct.peer); }
diff --git a/restygwt/src/test/java/org/fusesource/restygwt/server/event/EchoServlet.java b/restygwt/src/test/java/org/fusesource/restygwt/server/event/EchoServlet.java index 9898eeb..344bfbb 100644 --- a/restygwt/src/test/java/org/fusesource/restygwt/server/event/EchoServlet.java +++ b/restygwt/src/test/java/org/fusesource/restygwt/server/event/EchoServlet.java @@ -1,106 +1,106 @@ /** * Copyright (C) 2010 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.fusesource.restygwt.server.event; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * servlet to reflect the incoming request * * @author <a href="mailto:[email protected]">andi</<a> */ public class EchoServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger log = Logger.getLogger(EchoServlet.class.getName()); private final String CONTENT_TYPE = "application/json"; private final String RESPONSE_CODE_HEADER_NAME = "X-Echo-Code"; private final String RESPONSE_BODY_HEADER_NAME = "X-Echo-Body"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { if (log.isLoggable(Level.INFO)) { log.info("path: " + request.getPathTranslated()); @SuppressWarnings("unchecked") Enumeration<String> headerNames = request.getHeaderNames(); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("URI : ").append(request.getRequestURI()).append("\n"); sb.append("Method : ").append(request.getMethod()).append("\n"); sb.append("Headers:\n"); sb.append("========\n"); - for (String s = null; headerNames.hasMoreElements(); s = headerNames.nextElement()) { - if (s != null) - sb.append(" ").append(s).append(": ").append(request.getHeader(s)).append("\n"); + while(headerNames.hasMoreElements()) { + final String s = headerNames.nextElement(); + sb.append(" ").append(s).append(": ").append(request.getHeader(s)).append("\n"); } sb.append("========\n"); sb.append("Body :\n"); sb.append("========\n"); String line = null; do { line = request.getReader().readLine(); if (null != line) sb.append(line).append("\n"); } while(null != line); sb.append("========\n"); log.info(sb.toString()); } response.setContentType(CONTENT_TYPE); int statusCode = HttpServletResponse.SC_OK; if (null != request.getHeader(RESPONSE_CODE_HEADER_NAME)) { statusCode = Integer.parseInt(request.getHeader(RESPONSE_CODE_HEADER_NAME)); } response.setStatus(statusCode); String out = ""; if (null != request.getHeader(RESPONSE_BODY_HEADER_NAME)) { out = request.getHeader(RESPONSE_BODY_HEADER_NAME); response.getWriter().print(out); } log.info("respond: (" + statusCode + ") `" + out + "´"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException { doPost(request, response); } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { if (log.isLoggable(Level.INFO)) { log.info("path: " + request.getPathTranslated()); @SuppressWarnings("unchecked") Enumeration<String> headerNames = request.getHeaderNames(); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("URI : ").append(request.getRequestURI()).append("\n"); sb.append("Method : ").append(request.getMethod()).append("\n"); sb.append("Headers:\n"); sb.append("========\n"); for (String s = null; headerNames.hasMoreElements(); s = headerNames.nextElement()) { if (s != null) sb.append(" ").append(s).append(": ").append(request.getHeader(s)).append("\n"); } sb.append("========\n"); sb.append("Body :\n"); sb.append("========\n"); String line = null; do { line = request.getReader().readLine(); if (null != line) sb.append(line).append("\n"); } while(null != line); sb.append("========\n"); log.info(sb.toString()); } response.setContentType(CONTENT_TYPE); int statusCode = HttpServletResponse.SC_OK; if (null != request.getHeader(RESPONSE_CODE_HEADER_NAME)) { statusCode = Integer.parseInt(request.getHeader(RESPONSE_CODE_HEADER_NAME)); } response.setStatus(statusCode); String out = ""; if (null != request.getHeader(RESPONSE_BODY_HEADER_NAME)) { out = request.getHeader(RESPONSE_BODY_HEADER_NAME); response.getWriter().print(out); } log.info("respond: (" + statusCode + ") `" + out + "´"); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { if (log.isLoggable(Level.INFO)) { log.info("path: " + request.getPathTranslated()); @SuppressWarnings("unchecked") Enumeration<String> headerNames = request.getHeaderNames(); StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("URI : ").append(request.getRequestURI()).append("\n"); sb.append("Method : ").append(request.getMethod()).append("\n"); sb.append("Headers:\n"); sb.append("========\n"); while(headerNames.hasMoreElements()) { final String s = headerNames.nextElement(); sb.append(" ").append(s).append(": ").append(request.getHeader(s)).append("\n"); } sb.append("========\n"); sb.append("Body :\n"); sb.append("========\n"); String line = null; do { line = request.getReader().readLine(); if (null != line) sb.append(line).append("\n"); } while(null != line); sb.append("========\n"); log.info(sb.toString()); } response.setContentType(CONTENT_TYPE); int statusCode = HttpServletResponse.SC_OK; if (null != request.getHeader(RESPONSE_CODE_HEADER_NAME)) { statusCode = Integer.parseInt(request.getHeader(RESPONSE_CODE_HEADER_NAME)); } response.setStatus(statusCode); String out = ""; if (null != request.getHeader(RESPONSE_BODY_HEADER_NAME)) { out = request.getHeader(RESPONSE_BODY_HEADER_NAME); response.getWriter().print(out); } log.info("respond: (" + statusCode + ") `" + out + "´"); }
diff --git a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/periodicals/UpdateSubscriptions.java b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/periodicals/UpdateSubscriptions.java index 2dea3d485..ee5a76df5 100644 --- a/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/periodicals/UpdateSubscriptions.java +++ b/cyklotron-ui/src/main/java/net/cyklotron/cms/modules/actions/periodicals/UpdateSubscriptions.java @@ -1,237 +1,237 @@ /* * Created on Nov 7, 2003 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package net.cyklotron.cms.modules.actions.periodicals; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import org.jcontainer.dna.Logger; import org.objectledge.context.Context; import org.objectledge.coral.entity.EntityDoesNotExistException; import org.objectledge.coral.security.Subject; import org.objectledge.coral.session.CoralSession; import org.objectledge.coral.store.Resource; import org.objectledge.parameters.Parameters; import org.objectledge.pipeline.ProcessingException; import org.objectledge.templating.TemplatingContext; import org.objectledge.utils.StackTrace; import org.objectledge.web.HttpContext; import org.objectledge.web.mvc.MVCContext; import net.cyklotron.cms.CmsDataFactory; import net.cyklotron.cms.confirmation.EmailConfirmationRequestResource; import net.cyklotron.cms.periodicals.EmailPeriodicalResource; import net.cyklotron.cms.periodicals.PeriodicalResource; import net.cyklotron.cms.periodicals.PeriodicalsService; import net.cyklotron.cms.periodicals.PeriodicalsSubscriptionService; import net.cyklotron.cms.periodicals.UnsubscriptionInfo; import net.cyklotron.cms.site.SiteResource; import net.cyklotron.cms.site.SiteService; import net.cyklotron.cms.structure.StructureService; /** * @author <a href="[email protected]">Rafal Krzewski</a> * @version $Id: UpdateSubscriptions.java,v 1.8 2008-10-07 14:47:54 rafal Exp $ */ public class UpdateSubscriptions extends BasePeriodicalsAction { private final PeriodicalsSubscriptionService periodicalsSubscriptionService; public UpdateSubscriptions(Logger logger, StructureService structureService, CmsDataFactory cmsDataFactory, PeriodicalsService periodicalsService, PeriodicalsSubscriptionService periodicalsSubscriptionService, SiteService siteService) { super(logger, structureService, cmsDataFactory, periodicalsService, siteService); this.periodicalsSubscriptionService = periodicalsSubscriptionService; } /** * {@inheritdoc} */ public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { try { Subject rootSubject = coralSession.getSecurity().getSubject(Subject.ROOT); boolean subscribe = parameters.getBoolean("subscribe", false); String cookie = null; if(subscribe) { cookie = parameters.get("cookie",""); if (cookie.length() == 0) { templatingContext.put("result", "parameter_not_found"); return; } templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); String email = req.getEmail(); if (req == null) { // invalid cookie - screen will complain return; } StringTokenizer st = new StringTokenizer(req.getData(), " "); Set selected = new HashSet(); while (st.hasMoreTokens()) { long periodicalId = Long.parseLong(st.nextToken()); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } synchronized(periodicalsService) { Iterator i = selected.iterator(); while(i.hasNext()) { EmailPeriodicalResource periodical = (EmailPeriodicalResource)i.next(); subscribe(periodical, email, rootSubject); } } } else { String email; SiteResource site; if(parameters.isDefined("token")) { String unsubToken = parameters.get("token"); UnsubscriptionInfo unsubInfo = periodicalsSubscriptionService .decodeUnsubscriptionToken(unsubToken, false); if(!unsubInfo.isValid()) { throw new ProcessingException("authorization failed"); } email = unsubInfo.getAddress(); PeriodicalResource periodical = (PeriodicalResource)coralSession.getStore() .getResource(unsubInfo.getPeriodicalId()); site = periodical.getSite(); } else { cookie = parameters.get("cookie"); templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); email = req.getEmail(); } Set selected = new HashSet(); String[] ids = parameters.getStrings("selected"); for(int i = 0; i < ids.length; i++) { long periodicalId = Long.parseLong(ids[i]); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } - if(cookie != null && selected.size() == 1) + if(cookie != null && selected.size() > 0) { PeriodicalResource periodical = (PeriodicalResource)selected.toArray()[0]; site = periodical.getSite(); } else { site = getSite(context); - } + } EmailPeriodicalResource[] subscribedArray = periodicalsSubscriptionService .getSubscribedEmailPeriodicals(coralSession, site, email); Set subscribed = new HashSet(Arrays.asList(subscribedArray)); EmailPeriodicalResource[] periodicals = periodicalsService.getEmailPeriodicals(coralSession, site); for (int i = 0; i < periodicals.length; i++) { EmailPeriodicalResource periodical = periodicals[i]; if(selected.contains(periodical) && !subscribed.contains(periodical)) { subscribe(periodical, email, rootSubject); } if(!selected.contains(periodical) && subscribed.contains(periodical)) { unsubscribe(periodical, email, rootSubject); } } } // success parameters.remove("cookie"); if(cookie != null) { periodicalsSubscriptionService.discardSubscriptionRequest(coralSession, cookie); } templatingContext.put("result", "updated_successfully"); } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); } } public void subscribe(EmailPeriodicalResource periodical, String email, Subject subject) throws Exception { if(periodical.getAddresses().indexOf(email) < 0) { periodical.setAddresses(sortAddresses(periodical.getAddresses()+"\n"+email)); periodical.update(); } } public void unsubscribe(EmailPeriodicalResource periodical, String email, Subject subject) throws Exception { if(periodical.getAddresses().indexOf(email) >= 0) { String addresses = periodical.getAddresses(); int i1 = addresses.indexOf(email); int i2 = addresses.indexOf('\n', i1); if(i2 > 0) { addresses = addresses.substring(0,i1).concat(addresses.substring(i2+1)); } else { addresses = addresses.substring(0, i1); } periodical.setAddresses(sortAddresses(addresses)); periodical.update(); } } public boolean checkAccessRights(Context context) throws ProcessingException { return true; } /** * @{inheritDoc} */ public boolean requiresAuthenticatedUser(Context context) throws Exception { return false; } }
false
true
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { try { Subject rootSubject = coralSession.getSecurity().getSubject(Subject.ROOT); boolean subscribe = parameters.getBoolean("subscribe", false); String cookie = null; if(subscribe) { cookie = parameters.get("cookie",""); if (cookie.length() == 0) { templatingContext.put("result", "parameter_not_found"); return; } templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); String email = req.getEmail(); if (req == null) { // invalid cookie - screen will complain return; } StringTokenizer st = new StringTokenizer(req.getData(), " "); Set selected = new HashSet(); while (st.hasMoreTokens()) { long periodicalId = Long.parseLong(st.nextToken()); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } synchronized(periodicalsService) { Iterator i = selected.iterator(); while(i.hasNext()) { EmailPeriodicalResource periodical = (EmailPeriodicalResource)i.next(); subscribe(periodical, email, rootSubject); } } } else { String email; SiteResource site; if(parameters.isDefined("token")) { String unsubToken = parameters.get("token"); UnsubscriptionInfo unsubInfo = periodicalsSubscriptionService .decodeUnsubscriptionToken(unsubToken, false); if(!unsubInfo.isValid()) { throw new ProcessingException("authorization failed"); } email = unsubInfo.getAddress(); PeriodicalResource periodical = (PeriodicalResource)coralSession.getStore() .getResource(unsubInfo.getPeriodicalId()); site = periodical.getSite(); } else { cookie = parameters.get("cookie"); templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); email = req.getEmail(); } Set selected = new HashSet(); String[] ids = parameters.getStrings("selected"); for(int i = 0; i < ids.length; i++) { long periodicalId = Long.parseLong(ids[i]); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } if(cookie != null && selected.size() == 1) { PeriodicalResource periodical = (PeriodicalResource)selected.toArray()[0]; site = periodical.getSite(); } else { site = getSite(context); } EmailPeriodicalResource[] subscribedArray = periodicalsSubscriptionService .getSubscribedEmailPeriodicals(coralSession, site, email); Set subscribed = new HashSet(Arrays.asList(subscribedArray)); EmailPeriodicalResource[] periodicals = periodicalsService.getEmailPeriodicals(coralSession, site); for (int i = 0; i < periodicals.length; i++) { EmailPeriodicalResource periodical = periodicals[i]; if(selected.contains(periodical) && !subscribed.contains(periodical)) { subscribe(periodical, email, rootSubject); } if(!selected.contains(periodical) && subscribed.contains(periodical)) { unsubscribe(periodical, email, rootSubject); } } } // success parameters.remove("cookie"); if(cookie != null) { periodicalsSubscriptionService.discardSubscriptionRequest(coralSession, cookie); } templatingContext.put("result", "updated_successfully"); } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); } }
public void execute(Context context, Parameters parameters, MVCContext mvcContext, TemplatingContext templatingContext, HttpContext httpContext, CoralSession coralSession) throws ProcessingException { try { Subject rootSubject = coralSession.getSecurity().getSubject(Subject.ROOT); boolean subscribe = parameters.getBoolean("subscribe", false); String cookie = null; if(subscribe) { cookie = parameters.get("cookie",""); if (cookie.length() == 0) { templatingContext.put("result", "parameter_not_found"); return; } templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); String email = req.getEmail(); if (req == null) { // invalid cookie - screen will complain return; } StringTokenizer st = new StringTokenizer(req.getData(), " "); Set selected = new HashSet(); while (st.hasMoreTokens()) { long periodicalId = Long.parseLong(st.nextToken()); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } synchronized(periodicalsService) { Iterator i = selected.iterator(); while(i.hasNext()) { EmailPeriodicalResource periodical = (EmailPeriodicalResource)i.next(); subscribe(periodical, email, rootSubject); } } } else { String email; SiteResource site; if(parameters.isDefined("token")) { String unsubToken = parameters.get("token"); UnsubscriptionInfo unsubInfo = periodicalsSubscriptionService .decodeUnsubscriptionToken(unsubToken, false); if(!unsubInfo.isValid()) { throw new ProcessingException("authorization failed"); } email = unsubInfo.getAddress(); PeriodicalResource periodical = (PeriodicalResource)coralSession.getStore() .getResource(unsubInfo.getPeriodicalId()); site = periodical.getSite(); } else { cookie = parameters.get("cookie"); templatingContext.put("cookie", cookie); EmailConfirmationRequestResource req = periodicalsSubscriptionService .getSubscriptionRequest(coralSession, cookie); email = req.getEmail(); } Set selected = new HashSet(); String[] ids = parameters.getStrings("selected"); for(int i = 0; i < ids.length; i++) { long periodicalId = Long.parseLong(ids[i]); try { Resource periodical = coralSession.getStore().getResource(periodicalId); selected.add(periodical); } catch(EntityDoesNotExistException e) { // periodical was deleted, ignore } } if(cookie != null && selected.size() > 0) { PeriodicalResource periodical = (PeriodicalResource)selected.toArray()[0]; site = periodical.getSite(); } else { site = getSite(context); } EmailPeriodicalResource[] subscribedArray = periodicalsSubscriptionService .getSubscribedEmailPeriodicals(coralSession, site, email); Set subscribed = new HashSet(Arrays.asList(subscribedArray)); EmailPeriodicalResource[] periodicals = periodicalsService.getEmailPeriodicals(coralSession, site); for (int i = 0; i < periodicals.length; i++) { EmailPeriodicalResource periodical = periodicals[i]; if(selected.contains(periodical) && !subscribed.contains(periodical)) { subscribe(periodical, email, rootSubject); } if(!selected.contains(periodical) && subscribed.contains(periodical)) { unsubscribe(periodical, email, rootSubject); } } } // success parameters.remove("cookie"); if(cookie != null) { periodicalsSubscriptionService.discardSubscriptionRequest(coralSession, cookie); } templatingContext.put("result", "updated_successfully"); } catch(Exception e) { templatingContext.put("result", "exception"); templatingContext.put("trace", new StackTrace(e)); } }
diff --git a/src/main/ed/db/DBJni.java b/src/main/ed/db/DBJni.java index e01a12eeb..5da0d1af2 100644 --- a/src/main/ed/db/DBJni.java +++ b/src/main/ed/db/DBJni.java @@ -1,362 +1,362 @@ // DBJni.java package ed.db; import java.io.*; import java.net.*; import java.nio.*; import java.util.*; import ed.js.*; public class DBJni extends DBBase { static final boolean D = false; public DBJni( String root ){ this( root , null ); } public DBJni( String root , String ip ){ if ( ip == null || ip.length() == 0 ) ip = "127.0.0.1"; else { try { ip = InetAddress.getByName( ip ).getHostAddress(); } catch ( IOException ioe ){ throw new RuntimeException( "can't get ip for:" + ip ); } } _ip = ip; _root = root; _sock = getSockAddr( _ip ); } public MyCollection getCollection( String name ){ MyCollection c = _collections.get( name ); if ( c != null ) return c; synchronized ( _collections ){ c = _collections.get( name ); if ( c != null ) return c; c = new MyCollection( name ); _collections.put( name , c ); } return c; } public Collection<String> getCollectionNames(){ throw new RuntimeException( "not implemented yet" ); } class MyCollection extends DBCollection { MyCollection( String name ){ super( name ); _fullNameSpace = _root + "." + name; } public ObjectId apply( JSObject o ){ ObjectId id = (ObjectId)o.get( "_id" ); if ( id == null ){ id = ObjectId.get(); o.set( "_id" , id ); } return id; } public JSObject find( ObjectId id ){ JSObject lookup = new JSObjectBase(); lookup.set( "_id" , id ); Iterator<JSObject> res = find( lookup ); if ( res == null ) return null; JSObject o = res.next(); if ( res.hasNext() ) throw new RuntimeException( "something is wrong" ); return o; } public JSObject save( JSObject o ){ apply( o ); ByteEncoder encoder = new ByteEncoder(); encoder._buf.putInt( 0 ); // reserved encoder._put( _fullNameSpace ); encoder.putObject( null , o ); encoder.flip(); insert( _sock , encoder._buf , encoder._buf.position() , encoder._buf.limit() ); return o; } public int remove( JSObject o ){ ByteEncoder encoder = new ByteEncoder(); encoder._buf.putInt( 0 ); // reserved encoder._put( _fullNameSpace ); if ( o.keySet().size() == 1 && o.get( o.keySet().iterator().next() ) instanceof ObjectId ) encoder._buf.putInt( 1 ); else encoder._buf.putInt( 0 ); encoder.putObject( null , o ); encoder.flip(); doDelete( _sock , encoder._buf , encoder._buf.position() , encoder._buf.limit() ); return -1; } public Iterator<JSObject> find( JSObject ref ){ ByteEncoder encoder = new ByteEncoder(); encoder._buf.putInt( 0 ); // reserved encoder._put( _fullNameSpace ); encoder._buf.putInt( 0 ); // num to return encoder.putObject( null , ref ); encoder.flip(); ByteDecoder decoder = new ByteDecoder(); int len = query( _sock , encoder._buf , encoder._buf.position() , encoder._buf.limit() , decoder._buf ); decoder.doneReading( len ); SingleResult res = new SingleResult( _fullNameSpace , decoder ); if ( res._lst.size() == 0 ) return null; return new Result( res ); } public JSObject update( JSObject query , JSObject o , boolean upsert ){ apply( o ); ByteEncoder encoder = new ByteEncoder(); encoder._buf.putInt( 0 ); // reserved encoder._put( _fullNameSpace ); encoder._buf.putInt( upsert ? 1 : 0 ); encoder.putObject( null , query ); encoder.putObject( null , o ); encoder.flip(); doUpdate( _sock , encoder._buf , encoder._buf.position() , encoder._buf.limit() ); return o; } final String _fullNameSpace; } public String toString(){ return "DBConnection " + _ip + ":" + _root; } final Map<String,MyCollection> _collections = Collections.synchronizedMap( new HashMap<String,MyCollection>() ); final String _ip; final String _root; final long _sock; class SingleResult { SingleResult( String fullNameSpace , ByteDecoder decoder ){ _fullNameSpace = fullNameSpace; _reserved = decoder.getInt(); _cursor = decoder.getLong(); _startingFrom = decoder.getInt(); _num = decoder.getInt(); System.out.println( "cursor:" + _cursor ); if ( _num == 0 ) _lst = EMPTY; else if ( _num < 3 ) _lst = new LinkedList<JSObject>(); else _lst = new ArrayList<JSObject>(); if ( _num > 0 ){ int num = 0; while( decoder.more() && num < _num ){ final JSObject o = decoder.readObject(); _lst.add( o ); num++; if ( D ) { System.out.println( "-- : " + o.keySet().size() ); for ( String s : o.keySet() ) System.out.println( "\t " + s + " : " + o.get( s ) ); } } } } public String toString(){ return "reserved:" + _reserved + " _cursor:" + _cursor + " _startingFrom:" + _startingFrom + " _num:" + _num ; } final String _fullNameSpace; final int _reserved; final long _cursor; final int _startingFrom; final int _num; final List<JSObject> _lst; } class Result implements Iterator<JSObject> { Result( SingleResult res ){ init( res ); } private void init( SingleResult res ){ _curResult = res; _cur = res._lst.iterator(); _all.add( res ); } public JSObject next(){ if ( _cur.hasNext() ) return _cur.next(); if ( _curResult._cursor > 0 ){ ByteEncoder encoder = new ByteEncoder(); encoder._buf.putInt( 0 ); // reserved encoder._put( _curResult._fullNameSpace ); encoder._buf.putInt( 0 ); // num to return encoder._buf.putLong( _curResult._cursor ); encoder.flip(); ByteDecoder decoder = new ByteDecoder(); int len = getMore( _sock , encoder._buf , encoder._buf.position() , encoder._buf.limit() , decoder._buf ); decoder.doneReading( len ); SingleResult res = new SingleResult( _curResult._fullNameSpace , decoder ); init( res ); return next(); } throw new RuntimeException( "no more" ); } public boolean hasNext(){ if ( _cur.hasNext() ) return true; if ( _curResult._cursor > 0 ) return true; return false; } public void remove(){ throw new RuntimeException( "can't remove this way" ); } public String toString(){ return "DBCursor"; } SingleResult _curResult; Iterator<JSObject> _cur; final List<SingleResult> _all = new LinkedList<SingleResult>(); } // library init static { String ext = "so"; String os = System.getenv("OSTYPE" ); if ( "darwin".equals( os ) ) ext = "jnilib"; System.load( ( new java.io.File( "build/libdb." + ext ) ).getAbsolutePath() ); _defaultIp = createSock( "127.0.0.1" ); } static long getSockAddr( String name ){ Long addr = _ipToSockAddr.get( name ); if ( addr != null ) return addr; addr = createSock( name ); _ipToSockAddr.put( name, addr ); return addr; } private static native long createSock( String name ); private static native String msg( long sock ); private static native void insert( long sock , ByteBuffer buf , int position , int limit ); private static native void doDelete( long sock , ByteBuffer buf , int position , int limit ); private static native void doUpdate( long sock , ByteBuffer buf , int position , int limit ); private static native int query( long sock , ByteBuffer buf , int position , int limit , ByteBuffer res ); private static native int getMore( long sock , ByteBuffer buf , int position , int limit , ByteBuffer res ); static final Map<String,Long> _ipToSockAddr = Collections.synchronizedMap( new HashMap<String,Long>() ); static final List<JSObject> EMPTY = Collections.unmodifiableList( new LinkedList<JSObject>() ); static final long _defaultIp; // ----- TESTING public static void main( String args[] ){ MyCollection c = (new DBJni( "eliot" ) ).getCollection( "t1" ); JSObject o = new JSObjectBase(); o.set( "jumpy" , "yes" ); o.set( "name" , "ab" ); c.save( o ); - for ( int i=0; i<1; i++ ){ + for ( int i=0; i<100; i++ ){ System.out.println( i ); o = new JSObjectBase(); o.set( "jumpyasd" , "no" ); o.set( "name" , "ce" ); c.save( o ); } System.out.println( "done saving" ); JSObject q = new JSObjectBase(); System.out.println( "2 things : " + c.find( q ) ); c.update( o , o , true ); System.out.println( c.find( q ) ); JSObjectBase d = new JSObjectBase(); d.set( "name" , "ab" ); c.remove( d ); System.out.println( c.find( new JSObjectBase() ) ); } }
true
true
public static void main( String args[] ){ MyCollection c = (new DBJni( "eliot" ) ).getCollection( "t1" ); JSObject o = new JSObjectBase(); o.set( "jumpy" , "yes" ); o.set( "name" , "ab" ); c.save( o ); for ( int i=0; i<1; i++ ){ System.out.println( i ); o = new JSObjectBase(); o.set( "jumpyasd" , "no" ); o.set( "name" , "ce" ); c.save( o ); } System.out.println( "done saving" ); JSObject q = new JSObjectBase(); System.out.println( "2 things : " + c.find( q ) ); c.update( o , o , true ); System.out.println( c.find( q ) ); JSObjectBase d = new JSObjectBase(); d.set( "name" , "ab" ); c.remove( d ); System.out.println( c.find( new JSObjectBase() ) ); }
public static void main( String args[] ){ MyCollection c = (new DBJni( "eliot" ) ).getCollection( "t1" ); JSObject o = new JSObjectBase(); o.set( "jumpy" , "yes" ); o.set( "name" , "ab" ); c.save( o ); for ( int i=0; i<100; i++ ){ System.out.println( i ); o = new JSObjectBase(); o.set( "jumpyasd" , "no" ); o.set( "name" , "ce" ); c.save( o ); } System.out.println( "done saving" ); JSObject q = new JSObjectBase(); System.out.println( "2 things : " + c.find( q ) ); c.update( o , o , true ); System.out.println( c.find( q ) ); JSObjectBase d = new JSObjectBase(); d.set( "name" , "ab" ); c.remove( d ); System.out.println( c.find( new JSObjectBase() ) ); }
diff --git a/src/com/android/exchange/eas/EasOperation.java b/src/com/android/exchange/eas/EasOperation.java index 6d615d77..1c695e08 100644 --- a/src/com/android/exchange/eas/EasOperation.java +++ b/src/com/android/exchange/eas/EasOperation.java @@ -1,554 +1,556 @@ /* * Copyright (C) 2013 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.exchange.eas; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SyncResult; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.telephony.TelephonyManager; import android.text.format.DateUtils; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.utility.Utility; import com.android.exchange.Eas; import com.android.exchange.EasResponse; import com.android.exchange.adapter.Serializer; import com.android.exchange.adapter.Tags; import com.android.exchange.service.EasServerConnection; import com.android.mail.utils.LogUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import java.io.IOException; /** * Base class for all Exchange operations that use a POST to talk to the server. * * The core of this class is {@link #performOperation}, which provides the skeleton of making * a request, handling common errors, and setting fields on the {@link SyncResult} if there is one. * This class abstracts the connection handling from its subclasses and callers. * * A subclass must implement the abstract functions below that create the request and parse the * response. There are also a set of functions that a subclass may override if it's substantially * different from the "normal" operation (e.g. most requests use the same request URI, but auto * discover deviates since it's not account-specific), but the default implementation should suffice * for most. The subclass must also define a public function which calls {@link #performOperation}, * possibly doing nothing other than that. (I chose to force subclasses to do this, rather than * provide that function in the base class, in order to force subclasses to consider, for example, * whether it needs a {@link SyncResult} parameter, and what the proper name for the "doWork" * function ought to be for the subclass.) */ public abstract class EasOperation { public static final String LOG_TAG = Eas.LOG_TAG; /** The maximum number of server redirects we allow before returning failure. */ private static final int MAX_REDIRECTS = 3; /** Message MIME type for EAS version 14 and later. */ private static final String EAS_14_MIME_TYPE = "application/vnd.ms-sync.wbxml"; /** Error code indicating the operation was cancelled via {@link #abort}. */ public static final int RESULT_ABORT = -1; /** Error code indicating the operation was cancelled via {@link #restart}. */ public static final int RESULT_RESTART = -2; /** Error code indicating the Exchange servers redirected too many times. */ public static final int RESULT_TOO_MANY_REDIRECTS = -3; /** Error code indicating the request failed due to a network problem. */ public static final int RESULT_REQUEST_FAILURE = -4; /** Error code indicating a 403 (forbidden) error. */ public static final int RESULT_FORBIDDEN = -5; /** Error code indicating an unresolved provisioning error. */ public static final int RESULT_PROVISIONING_ERROR = -6; /** Error code indicating an authentication problem. */ public static final int RESULT_AUTHENTICATION_ERROR = -7; /** Error code indicating the client is missing a certificate. */ public static final int RESULT_CLIENT_CERTIFICATE_REQUIRED = -8; /** Error code indicating we don't have a protocol version in common with the server. */ public static final int RESULT_PROTOCOL_VERSION_UNSUPPORTED = -9; /** Error code indicating some other failure. */ public static final int RESULT_OTHER_FAILURE = -10; protected final Context mContext; /** * The account id for this operation. * NOTE: You will be tempted to add a reference to the {@link Account} here. Resist. * It's too easy for that to lead to creep and stale data. */ protected final long mAccountId; private final EasServerConnection mConnection; // TODO: Make this private again when EasSyncHandler is converted to be a subclass. protected EasOperation(final Context context, final long accountId, final EasServerConnection connection) { mContext = context; mAccountId = accountId; mConnection = connection; } protected EasOperation(final Context context, final Account account, final HostAuth hostAuth) { this(context, account.mId, new EasServerConnection(context, account, hostAuth)); } protected EasOperation(final Context context, final Account account) { this(context, account, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv)); } /** * This constructor is for use by operations that are created by other operations, e.g. * {@link EasProvision}. * @param parentOperation The {@link EasOperation} that is creating us. */ protected EasOperation(final EasOperation parentOperation) { this(parentOperation.mContext, parentOperation.mAccountId, parentOperation.mConnection); } /** * Request that this operation terminate. Intended for use by the sync service to interrupt * running operations, primarily Ping. */ public final void abort() { mConnection.stop(EasServerConnection.STOPPED_REASON_ABORT); } /** * Request that this operation restart. Intended for use by the sync service to interrupt * running operations, primarily Ping. */ public final void restart() { mConnection.stop(EasServerConnection.STOPPED_REASON_RESTART); } /** * The skeleton of performing an operation. This function handles all the common code and * error handling, calling into virtual functions that are implemented or overridden by the * subclass to do the operation-specific logic. * * The result codes work as follows: * - Negative values indicate common error codes and are defined above (the various RESULT_* * constants). * - Non-negative values indicate the result of {@link #handleResponse}. These are obviously * specific to the subclass, and may indicate success or error conditions. * * The common error codes primarily indicate conditions that occur when performing the POST * itself, such as network errors and handling of the HTTP response. However, some errors that * can be indicated in the HTTP response code can also be indicated in the payload of the * response as well, so {@link #handleResponse} should in those cases return the appropriate * negative result code, which will be handled the same as if it had been indicated in the HTTP * response code. * * @param syncResult If this operation is a sync, the {@link SyncResult} object that should * be written to for this sync; otherwise null. * @return A result code for the outcome of this operation, as described above. */ protected final int performOperation(final SyncResult syncResult) { // We handle server redirects by looping, but we need to protect against too much looping. int redirectCount = 0; do { // Perform the HTTP request and handle exceptions. final EasResponse response; try { if (registerClientCert()) { response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout()); } else { + LogUtils.e(LOG_TAG, "Problem registering client cert"); // TODO: Is this the best stat to increment? if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } return RESULT_CLIENT_CERTIFICATE_REQUIRED; } } catch (final IOException e) { // If we were stopped, return the appropriate result code. switch (mConnection.getStoppedReason()) { case EasServerConnection.STOPPED_REASON_ABORT: return RESULT_ABORT; case EasServerConnection.STOPPED_REASON_RESTART: return RESULT_RESTART; default: break; } // If we're here, then we had a IOException that's not from a stop request. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } catch (final IllegalStateException e) { // Subclasses use ISE to signal a hard error when building the request. // TODO: Switch away from ISEs. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { syncResult.databaseError = true; } return RESULT_OTHER_FAILURE; } // The POST completed, so process the response. try { final int result; // First off, the success case. if (response.isSuccess()) { try { result = handleResponse(response, syncResult); if (result >= 0) { return result; } } catch (final IOException e) { LogUtils.e(LOG_TAG, e, "Exception while handling response"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } } else { result = RESULT_OTHER_FAILURE; } // If this operation has distinct handling for 403 errors, do that. if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) { LogUtils.e(LOG_TAG, "Forbidden response"); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_FORBIDDEN; } // Handle provisioning errors. if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) { if (handleProvisionError(syncResult, mAccountId)) { // The provisioning error has been taken care of, so we should re-do this // request. continue; } if (syncResult != null) { + LogUtils.e(LOG_TAG, "Issue with provisioning"); // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_PROVISIONING_ERROR; } // Handle authentication errors. if (response.isAuthError()) { LogUtils.e(LOG_TAG, "Authentication error"); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } if (response.isMissingCertificate()) { return RESULT_CLIENT_CERTIFICATE_REQUIRED; } return RESULT_AUTHENTICATION_ERROR; } // Handle redirects. if (response.isRedirectError()) { ++redirectCount; mConnection.redirectHostAuth(response.getRedirectAddress()); // Note that unlike other errors, we do NOT return here; we just keep looping. } else { // All other errors. LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d", getCommand(), response.getStatus(), result); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numIoExceptions; } return RESULT_OTHER_FAILURE; } } finally { response.close(); } } while (redirectCount < MAX_REDIRECTS); // Non-redirects return immediately after handling, so the only way to reach here is if we // looped too many times. LogUtils.e(LOG_TAG, "Too many redirects"); if (syncResult != null) { syncResult.tooManyRetries = true; } return RESULT_TOO_MANY_REDIRECTS; } /** * Reset the protocol version to use for this connection. If it's changed, and our account is * persisted, also write back the changes to the DB. * @param protocolVersion The new protocol version to use, as a string. */ protected final void setProtocolVersion(final String protocolVersion) { if (mConnection.setProtocolVersion(protocolVersion) && mAccountId != Account.NOT_SAVED) { final Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId); final ContentValues cv = new ContentValues(2); if (getProtocolVersion() >= 12.0) { final int oldFlags = Utility.getFirstRowInt(mContext, uri, Account.ACCOUNT_FLAGS_PROJECTION, null, null, null, Account.ACCOUNT_FLAGS_COLUMN_FLAGS, 0); final int newFlags = oldFlags | Account.FLAGS_SUPPORTS_GLOBAL_SEARCH + Account.FLAGS_SUPPORTS_SEARCH; if (oldFlags != newFlags) { cv.put(EmailContent.AccountColumns.FLAGS, newFlags); } } cv.put(EmailContent.AccountColumns.PROTOCOL_VERSION, protocolVersion); mContext.getContentResolver().update(uri, cv, null, null); } } /** * Create the request object for this operation. * Most operations use a POST, but some use other request types (e.g. Options). * @return An {@link HttpUriRequest}. * @throws IOException */ private final HttpUriRequest makeRequest() throws IOException { final String requestUri = getRequestUri(); if (requestUri == null) { return mConnection.makeOptions(); } return mConnection.makePost(requestUri, getRequestEntity(), getRequestContentType(), addPolicyKeyHeaderToRequest()); } /** * The following functions MUST be overridden by subclasses; these are things that are unique * to each operation. */ /** * Get the name of the operation, used as the "Cmd=XXX" query param in the request URI. Note * that if you override {@link #getRequestUri}, then this function may be unused for normal * operation, but all subclasses should return something non-null for use with logging. * @return The name of the command for this operation as defined by the EAS protocol, or for * commands that don't need it, a suitable descriptive name for logging. */ protected abstract String getCommand(); /** * Build the {@link HttpEntity} which is used to construct the POST. Typically this function * will build the Exchange request using a {@link Serializer} and then call {@link #makeEntity}. * If the subclass is not using a POST, then it should override this to return null. * @return The {@link HttpEntity} to pass to {@link EasServerConnection#makePost}. * @throws IOException */ protected abstract HttpEntity getRequestEntity() throws IOException; /** * Parse the response from the Exchange perform whatever actions are dictated by that. * @param response The {@link EasResponse} to our request. * @param syncResult The {@link SyncResult} object for this operation, or null if we're not * handling a sync. * @return A result code. Non-negative values are returned directly to the caller; negative * values * * that is returned to the caller of {@link #performOperation}. * @throws IOException */ protected abstract int handleResponse(final EasResponse response, final SyncResult syncResult) throws IOException; /** * The following functions may be overriden by a subclass, but most operations will not need * to do so. */ /** * Get the URI for the Exchange server and this operation. Most (signed in) operations need * not override this; the notable operation that needs to override it is auto-discover. * @return */ protected String getRequestUri() { return mConnection.makeUriString(getCommand()); } /** * @return Whether to set the X-MS-PolicyKey header. Only Ping does not want this header. */ protected boolean addPolicyKeyHeaderToRequest() { return true; } /** * @return The content type of this request. */ protected String getRequestContentType() { return EAS_14_MIME_TYPE; } /** * @return The timeout to use for the POST. */ protected long getTimeout() { return 30 * DateUtils.SECOND_IN_MILLIS; } /** * If 403 responses should be handled in a special way, this function should be overridden to * do that. * @return Whether we handle 403 responses; if false, then treat 403 as a provisioning error. */ protected boolean handleForbidden() { return false; } /** * Handle a provisioning error. Subclasses may override this to do something different, e.g. * to validate rather than actually do the provisioning. * @param syncResult * @param accountId * @return */ protected boolean handleProvisionError(final SyncResult syncResult, final long accountId) { final EasProvision provisionOperation = new EasProvision(this); return provisionOperation.provision(syncResult, accountId); } /** * Convenience methods for subclasses to use. */ /** * Convenience method to make an {@link HttpEntity} from {@link Serializer}. */ protected final HttpEntity makeEntity(final Serializer s) { return new ByteArrayEntity(s.toByteArray()); } /** * Check whether we should ask the server what protocol versions it supports and set this * account to use that version. * @return Whether we need a new protocol version from the server. */ protected final boolean shouldGetProtocolVersion() { // TODO: Find conditions under which we should check other than not having one yet. return !mConnection.isProtocolVersionSet(); } /** * @return The protocol version to use. */ protected final double getProtocolVersion() { return mConnection.getProtocolVersion(); } /** * @return Our useragent. */ protected final String getUserAgent() { return mConnection.getUserAgent(); } /** * @return Whether we succeeeded in registering the client cert. */ protected final boolean registerClientCert() { return mConnection.registerClientCert(); } /** * Add the device information to the current request. * @param s The {@link Serializer} for our current request. * @throws IOException */ protected final void addDeviceInformationToSerlializer(final Serializer s) throws IOException { final TelephonyManager tm = (TelephonyManager)mContext.getSystemService( Context.TELEPHONY_SERVICE); final String deviceId; final String phoneNumber; final String operator; if (tm != null) { deviceId = tm.getDeviceId(); phoneNumber = tm.getLine1Number(); operator = tm.getNetworkOperator(); } else { deviceId = null; phoneNumber = null; operator = null; } // TODO: Right now, we won't send this information unless the device is provisioned again. // Potentially, this means that our phone number could be out of date if the user // switches sims. Is there something we can do to force a reprovision? s.start(Tags.SETTINGS_DEVICE_INFORMATION).start(Tags.SETTINGS_SET); s.data(Tags.SETTINGS_MODEL, Build.MODEL); if (deviceId != null) { s.data(Tags.SETTINGS_IMEI, tm.getDeviceId()); } // TODO: What should we use for friendly name? //s.data(Tags.SETTINGS_FRIENDLY_NAME, "Friendly Name"); s.data(Tags.SETTINGS_OS, "Android " + Build.VERSION.RELEASE); if (phoneNumber != null) { s.data(Tags.SETTINGS_PHONE_NUMBER, phoneNumber); } // TODO: Consider setting this, but make sure we know what it's used for. // If the user changes the device's locale and we don't do a reprovision, the server's // idea of the language will be wrong. Since we're not sure what this is used for, // right now we're leaving it out. //s.data(Tags.SETTINGS_OS_LANGUAGE, Locale.getDefault().getDisplayLanguage()); s.data(Tags.SETTINGS_USER_AGENT, getUserAgent()); if (operator != null) { s.data(Tags.SETTINGS_MOBILE_OPERATOR, operator); } s.end().end(); // SETTINGS_SET, SETTINGS_DEVICE_INFORMATION } /** * Convenience method for adding a Message to an account's outbox * @param account The {@link Account} from which to send the message. * @param msg the message to send */ protected final void sendMessage(final Account account, final EmailContent.Message msg) { long mailboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX); // TODO: Improve system mailbox handling. if (mailboxId == Mailbox.NO_MAILBOX) { LogUtils.d(LOG_TAG, "No outbox for account %d, creating it", account.mId); final Mailbox outbox = Mailbox.newSystemMailbox(mContext, account.mId, Mailbox.TYPE_OUTBOX); outbox.save(mContext); mailboxId = outbox.mId; } msg.mMailboxKey = mailboxId; msg.mAccountKey = account.mId; msg.save(mContext); requestSyncForMailbox(new android.accounts.Account(account.mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), EmailContent.AUTHORITY, mailboxId); } /** * Issue a {@link android.content.ContentResolver#requestSync} for a specific mailbox. * @param amAccount The {@link android.accounts.Account} for the account we're pinging. * @param authority The authority for the mailbox that needs to sync. * @param mailboxId The id of the mailbox that needs to sync. */ protected static void requestSyncForMailbox(final android.accounts.Account amAccount, final String authority, final long mailboxId) { final Bundle extras = new Bundle(1); extras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId); ContentResolver.requestSync(amAccount, authority, extras); LogUtils.i(LOG_TAG, "requestSync EasOperation requestSyncForMailbox %s, %s", amAccount.toString(), extras.toString()); } }
false
true
protected final int performOperation(final SyncResult syncResult) { // We handle server redirects by looping, but we need to protect against too much looping. int redirectCount = 0; do { // Perform the HTTP request and handle exceptions. final EasResponse response; try { if (registerClientCert()) { response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout()); } else { // TODO: Is this the best stat to increment? if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } return RESULT_CLIENT_CERTIFICATE_REQUIRED; } } catch (final IOException e) { // If we were stopped, return the appropriate result code. switch (mConnection.getStoppedReason()) { case EasServerConnection.STOPPED_REASON_ABORT: return RESULT_ABORT; case EasServerConnection.STOPPED_REASON_RESTART: return RESULT_RESTART; default: break; } // If we're here, then we had a IOException that's not from a stop request. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } catch (final IllegalStateException e) { // Subclasses use ISE to signal a hard error when building the request. // TODO: Switch away from ISEs. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { syncResult.databaseError = true; } return RESULT_OTHER_FAILURE; } // The POST completed, so process the response. try { final int result; // First off, the success case. if (response.isSuccess()) { try { result = handleResponse(response, syncResult); if (result >= 0) { return result; } } catch (final IOException e) { LogUtils.e(LOG_TAG, e, "Exception while handling response"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } } else { result = RESULT_OTHER_FAILURE; } // If this operation has distinct handling for 403 errors, do that. if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) { LogUtils.e(LOG_TAG, "Forbidden response"); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_FORBIDDEN; } // Handle provisioning errors. if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) { if (handleProvisionError(syncResult, mAccountId)) { // The provisioning error has been taken care of, so we should re-do this // request. continue; } if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_PROVISIONING_ERROR; } // Handle authentication errors. if (response.isAuthError()) { LogUtils.e(LOG_TAG, "Authentication error"); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } if (response.isMissingCertificate()) { return RESULT_CLIENT_CERTIFICATE_REQUIRED; } return RESULT_AUTHENTICATION_ERROR; } // Handle redirects. if (response.isRedirectError()) { ++redirectCount; mConnection.redirectHostAuth(response.getRedirectAddress()); // Note that unlike other errors, we do NOT return here; we just keep looping. } else { // All other errors. LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d", getCommand(), response.getStatus(), result); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numIoExceptions; } return RESULT_OTHER_FAILURE; } } finally { response.close(); } } while (redirectCount < MAX_REDIRECTS); // Non-redirects return immediately after handling, so the only way to reach here is if we // looped too many times. LogUtils.e(LOG_TAG, "Too many redirects"); if (syncResult != null) { syncResult.tooManyRetries = true; } return RESULT_TOO_MANY_REDIRECTS; }
protected final int performOperation(final SyncResult syncResult) { // We handle server redirects by looping, but we need to protect against too much looping. int redirectCount = 0; do { // Perform the HTTP request and handle exceptions. final EasResponse response; try { if (registerClientCert()) { response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout()); } else { LogUtils.e(LOG_TAG, "Problem registering client cert"); // TODO: Is this the best stat to increment? if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } return RESULT_CLIENT_CERTIFICATE_REQUIRED; } } catch (final IOException e) { // If we were stopped, return the appropriate result code. switch (mConnection.getStoppedReason()) { case EasServerConnection.STOPPED_REASON_ABORT: return RESULT_ABORT; case EasServerConnection.STOPPED_REASON_RESTART: return RESULT_RESTART; default: break; } // If we're here, then we had a IOException that's not from a stop request. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } catch (final IllegalStateException e) { // Subclasses use ISE to signal a hard error when building the request. // TODO: Switch away from ISEs. LogUtils.e(LOG_TAG, e, "Exception while sending request"); if (syncResult != null) { syncResult.databaseError = true; } return RESULT_OTHER_FAILURE; } // The POST completed, so process the response. try { final int result; // First off, the success case. if (response.isSuccess()) { try { result = handleResponse(response, syncResult); if (result >= 0) { return result; } } catch (final IOException e) { LogUtils.e(LOG_TAG, e, "Exception while handling response"); if (syncResult != null) { ++syncResult.stats.numIoExceptions; } return RESULT_REQUEST_FAILURE; } } else { result = RESULT_OTHER_FAILURE; } // If this operation has distinct handling for 403 errors, do that. if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) { LogUtils.e(LOG_TAG, "Forbidden response"); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_FORBIDDEN; } // Handle provisioning errors. if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) { if (handleProvisionError(syncResult, mAccountId)) { // The provisioning error has been taken care of, so we should re-do this // request. continue; } if (syncResult != null) { LogUtils.e(LOG_TAG, "Issue with provisioning"); // TODO: Is this the best stat to increment? ++syncResult.stats.numAuthExceptions; } return RESULT_PROVISIONING_ERROR; } // Handle authentication errors. if (response.isAuthError()) { LogUtils.e(LOG_TAG, "Authentication error"); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } if (response.isMissingCertificate()) { return RESULT_CLIENT_CERTIFICATE_REQUIRED; } return RESULT_AUTHENTICATION_ERROR; } // Handle redirects. if (response.isRedirectError()) { ++redirectCount; mConnection.redirectHostAuth(response.getRedirectAddress()); // Note that unlike other errors, we do NOT return here; we just keep looping. } else { // All other errors. LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d", getCommand(), response.getStatus(), result); if (syncResult != null) { // TODO: Is this the best stat to increment? ++syncResult.stats.numIoExceptions; } return RESULT_OTHER_FAILURE; } } finally { response.close(); } } while (redirectCount < MAX_REDIRECTS); // Non-redirects return immediately after handling, so the only way to reach here is if we // looped too many times. LogUtils.e(LOG_TAG, "Too many redirects"); if (syncResult != null) { syncResult.tooManyRetries = true; } return RESULT_TOO_MANY_REDIRECTS; }
diff --git a/src/main/java/cc/redberry/core/indices/SimpleIndicesBuilder.java b/src/main/java/cc/redberry/core/indices/SimpleIndicesBuilder.java index 7c86162..74f2bc4 100644 --- a/src/main/java/cc/redberry/core/indices/SimpleIndicesBuilder.java +++ b/src/main/java/cc/redberry/core/indices/SimpleIndicesBuilder.java @@ -1,114 +1,115 @@ /* * Redberry: symbolic tensor computations. * * Copyright (c) 2010-2012: * Stanislav Poslavsky <[email protected]> * Bolotin Dmitriy <[email protected]> * * This file is part of Redberry. * * Redberry 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. * * Redberry 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 Redberry. If not, see <http://www.gnu.org/licenses/>. */ package cc.redberry.core.indices; import cc.redberry.core.combinatorics.Combinatorics; import cc.redberry.core.combinatorics.Symmetry; import cc.redberry.core.combinatorics.UnsafeCombinatorics; import cc.redberry.core.combinatorics.symmetries.Symmetries; import cc.redberry.core.combinatorics.symmetries.SymmetriesFactory; import cc.redberry.core.utils.ArraysUtils; import cc.redberry.core.utils.IntArrayList; import java.util.ArrayList; import java.util.List; /** * * @author Dmitry Bolotin * @author Stanislav Poslavsky */ public final class SimpleIndicesBuilder { private final IntArrayList data; private final List<Symmetries> symmetries; public SimpleIndicesBuilder(int initialCapacity) { data = new IntArrayList(initialCapacity); symmetries = new ArrayList<>(initialCapacity); } public SimpleIndicesBuilder() { this(7); } public SimpleIndicesBuilder append(SimpleIndices indices) { if (indices.size() == 0) return this; data.addAll(((SimpleIndicesAbstract) indices).data); symmetries.add(indices.getSymmetries().getInnerSymmetries()); return this; } public SimpleIndicesBuilder appendWithoutSymmetries(Indices indices) { if (indices.size() == 0) return this; data.addAll(((AbstractIndices) indices).data); symmetries.add(SymmetriesFactory.createSymmetries(indices.size())); return this; } public SimpleIndices getIndices() { final int[] data = this.data.toArray(); //Sorting indices by type int j; int[] types = new int[data.length]; for (j = 0; j < data.length; ++j) types[j] = data[j] & 0x7F000000; int[] cosort = Combinatorics.createIdentity(data.length); //only stable sort ArraysUtils.stableSort(types, cosort); int[] cosortInv = Combinatorics.inverse(cosort); //Allocating resulting symmetries object //it already contains identity symmetry Symmetries resultingSymmetries = SymmetriesFactory.createSymmetries(data.length); int[] c; int position = 0, k; + SimpleIndices sd = IndicesFactory.createSimple(null, data); //rescaling symmetries to the actual length and positions corresponding //to the sorted indices for (Symmetries ss : this.symmetries) { final List<Symmetry> basis = ss.getBasisSymmetries(); //iterating from 1 because zero'th element is always identity symmetry for (k = 1; k < basis.size(); ++k) { c = new int[data.length]; Symmetry s = basis.get(k); for (j = 0; j < data.length; ++j) if (cosort[j] < position || cosort[j] >= position + s.dimension()) - c[j] = cosortInv[j]; + c[j] = j; else - c[j] = cosortInv[s.newIndexOf(j - position) + position]; + c[j] = cosortInv[s.newIndexOf(cosort[j] - position) + position]; resultingSymmetries.addUnsafe(UnsafeCombinatorics.createUnsafe(c, s.isAntiSymmetry())); } //increasing position in the total symmetry array position += ss.dimension(); } - return UnsafeIndicesFactory.createIsolatedUnsafeWithoutSort( + return IndicesFactory.createSimple( new IndicesSymmetries(new IndicesTypeStructure(data), resultingSymmetries), data); } }
false
true
public SimpleIndices getIndices() { final int[] data = this.data.toArray(); //Sorting indices by type int j; int[] types = new int[data.length]; for (j = 0; j < data.length; ++j) types[j] = data[j] & 0x7F000000; int[] cosort = Combinatorics.createIdentity(data.length); //only stable sort ArraysUtils.stableSort(types, cosort); int[] cosortInv = Combinatorics.inverse(cosort); //Allocating resulting symmetries object //it already contains identity symmetry Symmetries resultingSymmetries = SymmetriesFactory.createSymmetries(data.length); int[] c; int position = 0, k; //rescaling symmetries to the actual length and positions corresponding //to the sorted indices for (Symmetries ss : this.symmetries) { final List<Symmetry> basis = ss.getBasisSymmetries(); //iterating from 1 because zero'th element is always identity symmetry for (k = 1; k < basis.size(); ++k) { c = new int[data.length]; Symmetry s = basis.get(k); for (j = 0; j < data.length; ++j) if (cosort[j] < position || cosort[j] >= position + s.dimension()) c[j] = cosortInv[j]; else c[j] = cosortInv[s.newIndexOf(j - position) + position]; resultingSymmetries.addUnsafe(UnsafeCombinatorics.createUnsafe(c, s.isAntiSymmetry())); } //increasing position in the total symmetry array position += ss.dimension(); } return UnsafeIndicesFactory.createIsolatedUnsafeWithoutSort( new IndicesSymmetries(new IndicesTypeStructure(data), resultingSymmetries), data); }
public SimpleIndices getIndices() { final int[] data = this.data.toArray(); //Sorting indices by type int j; int[] types = new int[data.length]; for (j = 0; j < data.length; ++j) types[j] = data[j] & 0x7F000000; int[] cosort = Combinatorics.createIdentity(data.length); //only stable sort ArraysUtils.stableSort(types, cosort); int[] cosortInv = Combinatorics.inverse(cosort); //Allocating resulting symmetries object //it already contains identity symmetry Symmetries resultingSymmetries = SymmetriesFactory.createSymmetries(data.length); int[] c; int position = 0, k; SimpleIndices sd = IndicesFactory.createSimple(null, data); //rescaling symmetries to the actual length and positions corresponding //to the sorted indices for (Symmetries ss : this.symmetries) { final List<Symmetry> basis = ss.getBasisSymmetries(); //iterating from 1 because zero'th element is always identity symmetry for (k = 1; k < basis.size(); ++k) { c = new int[data.length]; Symmetry s = basis.get(k); for (j = 0; j < data.length; ++j) if (cosort[j] < position || cosort[j] >= position + s.dimension()) c[j] = j; else c[j] = cosortInv[s.newIndexOf(cosort[j] - position) + position]; resultingSymmetries.addUnsafe(UnsafeCombinatorics.createUnsafe(c, s.isAntiSymmetry())); } //increasing position in the total symmetry array position += ss.dimension(); } return IndicesFactory.createSimple( new IndicesSymmetries(new IndicesTypeStructure(data), resultingSymmetries), data); }
diff --git a/src/main/java/edu/rivfader/commands/InsertCommandWithoutValues.java b/src/main/java/edu/rivfader/commands/InsertCommandWithoutValues.java index bf9c65e..02f9e53 100644 --- a/src/main/java/edu/rivfader/commands/InsertCommandWithoutValues.java +++ b/src/main/java/edu/rivfader/commands/InsertCommandWithoutValues.java @@ -1,59 +1,59 @@ package edu.rivfader.commands; import edu.rivfader.data.Database; import edu.rivfader.data.Row; import edu.rivfader.relalg.ITable; import edu.rivfader.relalg.IQualifiedNameRow; import edu.rivfader.relalg.QualifiedNameRow; import edu.rivfader.relalg.IQualifiedColumnName; import edu.rivfader.errors.NoColumnValueMappingPossible; import java.io.Writer; import java.io.IOException; import java.util.List; /** * This command implements inserting without specifying the columns. * @author harald */ public class InsertCommandWithoutValues implements ICommand { /** * contains the table to insert into. */ private ITable table; /** * contains the values to set. */ private List<String> values; /** * constructs a new insertion node. * @param pTableName the name of the table to modify. * @param pValues the values to insert into the table */ public InsertCommandWithoutValues(final ITable pTable, final List<String> pValues) { table = pTable; values = pValues; } @Override public void execute(final Database context, final Writer output) throws IOException { List<IQualifiedColumnName> cns; // column names IQualifiedNameRow vr; // value row table.setDatabase(context); cns = table.getColumnNames(); if(cns.size() != values.size()) { throw new NoColumnValueMappingPossible( - "Incorect amount of values for table"); + "Incorrect amount of values for table"); } vr = new QualifiedNameRow(cns); for(int i = 0; i < values.size(); i++) { vr.setData(cns.get(i), values.get(i)); } table.appendRow(vr); } }
true
true
public void execute(final Database context, final Writer output) throws IOException { List<IQualifiedColumnName> cns; // column names IQualifiedNameRow vr; // value row table.setDatabase(context); cns = table.getColumnNames(); if(cns.size() != values.size()) { throw new NoColumnValueMappingPossible( "Incorect amount of values for table"); } vr = new QualifiedNameRow(cns); for(int i = 0; i < values.size(); i++) { vr.setData(cns.get(i), values.get(i)); } table.appendRow(vr); }
public void execute(final Database context, final Writer output) throws IOException { List<IQualifiedColumnName> cns; // column names IQualifiedNameRow vr; // value row table.setDatabase(context); cns = table.getColumnNames(); if(cns.size() != values.size()) { throw new NoColumnValueMappingPossible( "Incorrect amount of values for table"); } vr = new QualifiedNameRow(cns); for(int i = 0; i < values.size(); i++) { vr.setData(cns.get(i), values.get(i)); } table.appendRow(vr); }
diff --git a/src/com/android/calendar/month/MonthWeekEventsView.java b/src/com/android/calendar/month/MonthWeekEventsView.java index 99c8f0e7..e1c78c67 100644 --- a/src/com/android/calendar/month/MonthWeekEventsView.java +++ b/src/com/android/calendar/month/MonthWeekEventsView.java @@ -1,1109 +1,1110 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar.month; import com.android.calendar.Event; import com.android.calendar.R; import com.android.calendar.Utils; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Service; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.provider.CalendarContract.Attendees; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.MotionEvent; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Formatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; public class MonthWeekEventsView extends SimpleWeekView { private static final String TAG = "MonthView"; private static final boolean DEBUG_LAYOUT = false; public static final String VIEW_PARAMS_ORIENTATION = "orientation"; public static final String VIEW_PARAMS_ANIMATE_TODAY = "animate_today"; /* NOTE: these are not constants, and may be multiplied by a scale factor */ private static int TEXT_SIZE_MONTH_NUMBER = 32; private static int TEXT_SIZE_EVENT = 12; private static int TEXT_SIZE_EVENT_TITLE = 14; private static int TEXT_SIZE_MORE_EVENTS = 12; private static int TEXT_SIZE_MONTH_NAME = 14; private static int TEXT_SIZE_WEEK_NUM = 12; private static int DNA_MARGIN = 4; private static int DNA_ALL_DAY_HEIGHT = 4; private static int DNA_MIN_SEGMENT_HEIGHT = 4; private static int DNA_WIDTH = 8; private static int DNA_ALL_DAY_WIDTH = 32; private static int DNA_SIDE_PADDING = 6; private static int CONFLICT_COLOR = Color.BLACK; private static int EVENT_TEXT_COLOR = Color.WHITE; private static int DEFAULT_EDGE_SPACING = 0; private static int SIDE_PADDING_MONTH_NUMBER = 4; private static int TOP_PADDING_MONTH_NUMBER = 4; private static int TOP_PADDING_WEEK_NUMBER = 4; private static int SIDE_PADDING_WEEK_NUMBER = 20; private static int DAY_SEPARATOR_OUTER_WIDTH = 0; private static int DAY_SEPARATOR_INNER_WIDTH = 1; private static int DAY_SEPARATOR_VERTICAL_LENGTH = 53; private static int DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT = 64; private static int MIN_WEEK_WIDTH = 50; private static int EVENT_X_OFFSET_LANDSCAPE = 38; private static int EVENT_Y_OFFSET_LANDSCAPE = 8; private static int EVENT_Y_OFFSET_PORTRAIT = 7; private static int EVENT_SQUARE_WIDTH = 10; private static int EVENT_SQUARE_BORDER = 2; private static int EVENT_LINE_PADDING = 2; private static int EVENT_RIGHT_PADDING = 4; private static int EVENT_BOTTOM_PADDING = 3; private static int TODAY_HIGHLIGHT_WIDTH = 2; private static int SPACING_WEEK_NUMBER = 24; private static boolean mInitialized = false; private static boolean mShowDetailsInMonth; protected Time mToday = new Time(); protected boolean mHasToday = false; protected int mTodayIndex = -1; protected int mOrientation = Configuration.ORIENTATION_LANDSCAPE; protected List<ArrayList<Event>> mEvents = null; protected ArrayList<Event> mUnsortedEvents = null; HashMap<Integer, Utils.DNAStrand> mDna = null; // This is for drawing the outlines around event chips and supports up to 10 // events being drawn on each day. The code will expand this if necessary. protected FloatRef mEventOutlines = new FloatRef(10 * 4 * 4 * 7); protected static StringBuilder mStringBuilder = new StringBuilder(50); // TODO recreate formatter when locale changes protected static Formatter mFormatter = new Formatter(mStringBuilder, Locale.getDefault()); protected Paint mMonthNamePaint; protected TextPaint mEventPaint; protected TextPaint mSolidBackgroundEventPaint; protected TextPaint mFramedEventPaint; protected TextPaint mDeclinedEventPaint; protected TextPaint mEventExtrasPaint; protected TextPaint mEventDeclinedExtrasPaint; protected Paint mWeekNumPaint; protected Paint mDNAAllDayPaint; protected Paint mDNATimePaint; protected Paint mEventSquarePaint; protected Drawable mTodayDrawable; protected int mMonthNumHeight; protected int mMonthNumAscentHeight; protected int mEventHeight; protected int mEventAscentHeight; protected int mExtrasHeight; protected int mExtrasAscentHeight; protected int mExtrasDescent; protected int mWeekNumAscentHeight; protected int mMonthBGColor; protected int mMonthBGOtherColor; protected int mMonthBGTodayColor; protected int mMonthNumColor; protected int mMonthNumOtherColor; protected int mMonthNumTodayColor; protected int mMonthNameColor; protected int mMonthNameOtherColor; protected int mMonthEventColor; protected int mMonthDeclinedEventColor; protected int mMonthDeclinedExtrasColor; protected int mMonthEventExtraColor; protected int mMonthEventOtherColor; protected int mMonthEventExtraOtherColor; protected int mMonthWeekNumColor; protected int mMonthBusyBitsBgColor; protected int mMonthBusyBitsBusyTimeColor; protected int mMonthBusyBitsConflictTimeColor; private int mClickedDayIndex = -1; private int mClickedDayColor; private static final int mClickedAlpha = 128; protected int mEventChipOutlineColor = 0xFFFFFFFF; protected int mDaySeparatorInnerColor; protected int mTodayAnimateColor; private boolean mAnimateToday; private int mAnimateTodayAlpha = 0; private ObjectAnimator mTodayAnimator = null; private final TodayAnimatorListener mAnimatorListener = new TodayAnimatorListener(); class TodayAnimatorListener extends AnimatorListenerAdapter { private volatile Animator mAnimator = null; private volatile boolean mFadingIn = false; @Override public void onAnimationEnd(Animator animation) { synchronized (this) { if (mAnimator != animation) { animation.removeAllListeners(); animation.cancel(); return; } if (mFadingIn) { if (mTodayAnimator != null) { mTodayAnimator.removeAllListeners(); mTodayAnimator.cancel(); } mTodayAnimator = ObjectAnimator.ofInt(MonthWeekEventsView.this, "animateTodayAlpha", 255, 0); mAnimator = mTodayAnimator; mFadingIn = false; mTodayAnimator.addListener(this); mTodayAnimator.setDuration(600); mTodayAnimator.start(); } else { mAnimateToday = false; mAnimateTodayAlpha = 0; mAnimator.removeAllListeners(); mAnimator = null; mTodayAnimator = null; invalidate(); } } } public void setAnimator(Animator animation) { mAnimator = animation; } public void setFadingIn(boolean fadingIn) { mFadingIn = fadingIn; } } private int[] mDayXs; /** * This provides a reference to a float array which allows for easy size * checking and reallocation. Used for drawing lines. */ private class FloatRef { float[] array; public FloatRef(int size) { array = new float[size]; } public void ensureSize(int newSize) { if (newSize >= array.length) { // Add enough space for 7 more boxes to be drawn array = Arrays.copyOf(array, newSize + 16 * 7); } } } /** * Shows up as an error if we don't include this. */ public MonthWeekEventsView(Context context) { super(context); } // Sets the list of events for this week. Takes a sorted list of arrays // divided up by day for generating the large month version and the full // arraylist sorted by start time to generate the dna version. public void setEvents(List<ArrayList<Event>> sortedEvents, ArrayList<Event> unsortedEvents) { setEvents(sortedEvents); // The MIN_WEEK_WIDTH is a hack to prevent the view from trying to // generate dna bits before its width has been fixed. createDna(unsortedEvents); } /** * Sets up the dna bits for the view. This will return early if the view * isn't in a state that will create a valid set of dna yet (such as the * views width not being set correctly yet). */ public void createDna(ArrayList<Event> unsortedEvents) { if (unsortedEvents == null || mWidth <= MIN_WEEK_WIDTH || getContext() == null) { // Stash the list of events for use when this view is ready, or // just clear it if a null set has been passed to this view mUnsortedEvents = unsortedEvents; mDna = null; return; } else { // clear the cached set of events since we're ready to build it now mUnsortedEvents = null; } // Create the drawing coordinates for dna if (!mShowDetailsInMonth) { int numDays = mEvents.size(); int effectiveWidth = mWidth - mPadding * 2; if (mShowWeekNum) { effectiveWidth -= SPACING_WEEK_NUMBER; } DNA_ALL_DAY_WIDTH = effectiveWidth / numDays - 2 * DNA_SIDE_PADDING; mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH); mDayXs = new int[numDays]; for (int day = 0; day < numDays; day++) { mDayXs[day] = computeDayLeftPosition(day) + DNA_WIDTH / 2 + DNA_SIDE_PADDING; } int top = DAY_SEPARATOR_INNER_WIDTH + DNA_MARGIN + DNA_ALL_DAY_HEIGHT + 1; int bottom = mHeight - DNA_MARGIN; mDna = Utils.createDNAStrands(mFirstJulianDay, unsortedEvents, top, bottom, DNA_MIN_SEGMENT_HEIGHT, mDayXs, getContext()); } } public void setEvents(List<ArrayList<Event>> sortedEvents) { mEvents = sortedEvents; if (sortedEvents == null) { return; } if (sortedEvents.size() != mNumDays) { if (Log.isLoggable(TAG, Log.ERROR)) { Log.wtf(TAG, "Events size must be same as days displayed: size=" + sortedEvents.size() + " days=" + mNumDays); } mEvents = null; return; } } protected void loadColors(Context context) { Resources res = context.getResources(); mMonthWeekNumColor = res.getColor(R.color.month_week_num_color); mMonthNumColor = res.getColor(R.color.month_day_number); mMonthNumOtherColor = res.getColor(R.color.month_day_number_other); mMonthNumTodayColor = res.getColor(R.color.month_today_number); mMonthNameColor = mMonthNumColor; mMonthNameOtherColor = mMonthNumOtherColor; mMonthEventColor = res.getColor(R.color.month_event_color); mMonthDeclinedEventColor = res.getColor(R.color.agenda_item_declined_color); mMonthDeclinedExtrasColor = res.getColor(R.color.agenda_item_where_declined_text_color); mMonthEventExtraColor = res.getColor(R.color.month_event_extra_color); mMonthEventOtherColor = res.getColor(R.color.month_event_other_color); mMonthEventExtraOtherColor = res.getColor(R.color.month_event_extra_other_color); mMonthBGTodayColor = res.getColor(R.color.month_today_bgcolor); mMonthBGOtherColor = res.getColor(R.color.month_other_bgcolor); mMonthBGColor = res.getColor(R.color.month_bgcolor); mDaySeparatorInnerColor = res.getColor(R.color.month_grid_lines); mTodayAnimateColor = res.getColor(R.color.today_highlight_color); mClickedDayColor = res.getColor(R.color.day_clicked_background_color); mTodayDrawable = res.getDrawable(R.drawable.today_blue_week_holo_light); } /** * Sets up the text and style properties for painting. Override this if you * want to use a different paint. */ @Override protected void initView() { super.initView(); if (!mInitialized) { Resources resources = getContext().getResources(); mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month); + TEXT_SIZE_EVENT_TITLE = resources.getInteger(R.integer.text_size_event_title); TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number); SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin); CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color); EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color); if (mScale != 1) { TOP_PADDING_MONTH_NUMBER *= mScale; TOP_PADDING_WEEK_NUMBER *= mScale; SIDE_PADDING_MONTH_NUMBER *= mScale; SIDE_PADDING_WEEK_NUMBER *= mScale; SPACING_WEEK_NUMBER *= mScale; TEXT_SIZE_MONTH_NUMBER *= mScale; TEXT_SIZE_EVENT *= mScale; TEXT_SIZE_EVENT_TITLE *= mScale; TEXT_SIZE_MORE_EVENTS *= mScale; TEXT_SIZE_MONTH_NAME *= mScale; TEXT_SIZE_WEEK_NUM *= mScale; DAY_SEPARATOR_OUTER_WIDTH *= mScale; DAY_SEPARATOR_INNER_WIDTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale; EVENT_X_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_PORTRAIT *= mScale; EVENT_SQUARE_WIDTH *= mScale; EVENT_SQUARE_BORDER *= mScale; EVENT_LINE_PADDING *= mScale; EVENT_BOTTOM_PADDING *= mScale; EVENT_RIGHT_PADDING *= mScale; DNA_MARGIN *= mScale; DNA_WIDTH *= mScale; DNA_ALL_DAY_HEIGHT *= mScale; DNA_MIN_SEGMENT_HEIGHT *= mScale; DNA_SIDE_PADDING *= mScale; DEFAULT_EDGE_SPACING *= mScale; DNA_ALL_DAY_WIDTH *= mScale; TODAY_HIGHLIGHT_WIDTH *= mScale; } if (!mShowDetailsInMonth) { TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN; } mInitialized = true; } mPadding = DEFAULT_EDGE_SPACING; loadColors(getContext()); // TODO modify paint properties depending on isMini mMonthNumPaint = new Paint(); mMonthNumPaint.setFakeBoldText(false); mMonthNumPaint.setAntiAlias(true); mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER); mMonthNumPaint.setColor(mMonthNumColor); mMonthNumPaint.setStyle(Style.FILL); mMonthNumPaint.setTextAlign(Align.RIGHT); mMonthNumPaint.setTypeface(Typeface.DEFAULT); mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f); mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f); mEventPaint = new TextPaint(); mEventPaint.setFakeBoldText(true); mEventPaint.setAntiAlias(true); mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mEventPaint.setColor(mMonthEventColor); mSolidBackgroundEventPaint = new TextPaint(mEventPaint); mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR); mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint); mDeclinedEventPaint = new TextPaint(); mDeclinedEventPaint.setFakeBoldText(true); mDeclinedEventPaint.setAntiAlias(true); mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mDeclinedEventPaint.setColor(mMonthDeclinedEventColor); mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f); mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f); mEventExtrasPaint = new TextPaint(); mEventExtrasPaint.setFakeBoldText(false); mEventExtrasPaint.setAntiAlias(true); mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventExtrasPaint.setColor(mMonthEventExtraColor); mEventExtrasPaint.setStyle(Style.FILL); mEventExtrasPaint.setTextAlign(Align.LEFT); mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f); mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f); mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f); mEventDeclinedExtrasPaint = new TextPaint(); mEventDeclinedExtrasPaint.setFakeBoldText(false); mEventDeclinedExtrasPaint.setAntiAlias(true); mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor); mEventDeclinedExtrasPaint.setStyle(Style.FILL); mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT); mWeekNumPaint = new Paint(); mWeekNumPaint.setFakeBoldText(false); mWeekNumPaint.setAntiAlias(true); mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM); mWeekNumPaint.setColor(mWeekNumColor); mWeekNumPaint.setStyle(Style.FILL); mWeekNumPaint.setTextAlign(Align.RIGHT); mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f); mDNAAllDayPaint = new Paint(); mDNATimePaint = new Paint(); mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor); mDNATimePaint.setStyle(Style.FILL_AND_STROKE); mDNATimePaint.setStrokeWidth(DNA_WIDTH); mDNATimePaint.setAntiAlias(false); mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor); mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE); mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH); mDNAAllDayPaint.setAntiAlias(false); mEventSquarePaint = new Paint(); mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventSquarePaint.setAntiAlias(false); if (DEBUG_LAYOUT) { Log.d("EXTRA", "mScale=" + mScale); Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent() + " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight); Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent() + " descent=" + mEventPaint.descent() + " int height=" + mEventHeight + " int ascent=" + mEventAscentHeight); Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent() + " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight); Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent() + " descent=" + mWeekNumPaint.descent()); } } @Override public void setWeekParams(HashMap<String, Integer> params, String tz) { super.setWeekParams(params, tz); if (params.containsKey(VIEW_PARAMS_ORIENTATION)) { mOrientation = params.get(VIEW_PARAMS_ORIENTATION); } updateToday(tz); mNumCells = mNumDays + 1; if (params.containsKey(VIEW_PARAMS_ANIMATE_TODAY) && mHasToday) { synchronized (mAnimatorListener) { if (mTodayAnimator != null) { mTodayAnimator.removeAllListeners(); mTodayAnimator.cancel(); } mTodayAnimator = ObjectAnimator.ofInt(this, "animateTodayAlpha", Math.max(mAnimateTodayAlpha, 80), 255); mTodayAnimator.setDuration(150); mAnimatorListener.setAnimator(mTodayAnimator); mAnimatorListener.setFadingIn(true); mTodayAnimator.addListener(mAnimatorListener); mAnimateToday = true; mTodayAnimator.start(); } } } /** * @param tz */ public boolean updateToday(String tz) { mToday.timezone = tz; mToday.setToNow(); mToday.normalize(true); int julianToday = Time.getJulianDay(mToday.toMillis(false), mToday.gmtoff); if (julianToday >= mFirstJulianDay && julianToday < mFirstJulianDay + mNumDays) { mHasToday = true; mTodayIndex = julianToday - mFirstJulianDay; } else { mHasToday = false; mTodayIndex = -1; } return mHasToday; } public void setAnimateTodayAlpha(int alpha) { mAnimateTodayAlpha = alpha; invalidate(); } @Override protected void onDraw(Canvas canvas) { drawBackground(canvas); drawWeekNums(canvas); drawDaySeparators(canvas); if (mHasToday && mAnimateToday) { drawToday(canvas); } if (mShowDetailsInMonth) { drawEvents(canvas); } else { if (mDna == null && mUnsortedEvents != null) { createDna(mUnsortedEvents); } drawDNA(canvas); } drawClick(canvas); } protected void drawToday(Canvas canvas) { r.top = DAY_SEPARATOR_INNER_WIDTH + (TODAY_HIGHLIGHT_WIDTH / 2); r.bottom = mHeight - (int) Math.ceil(TODAY_HIGHLIGHT_WIDTH / 2.0f); p.setStyle(Style.STROKE); p.setStrokeWidth(TODAY_HIGHLIGHT_WIDTH); r.left = computeDayLeftPosition(mTodayIndex) + (TODAY_HIGHLIGHT_WIDTH / 2); r.right = computeDayLeftPosition(mTodayIndex + 1) - (int) Math.ceil(TODAY_HIGHLIGHT_WIDTH / 2.0f); p.setColor(mTodayAnimateColor | (mAnimateTodayAlpha << 24)); canvas.drawRect(r, p); p.setStyle(Style.FILL); } // TODO move into SimpleWeekView // Computes the x position for the left side of the given day private int computeDayLeftPosition(int day) { int effectiveWidth = mWidth; int x = 0; int xOffset = 0; if (mShowWeekNum) { xOffset = SPACING_WEEK_NUMBER + mPadding; effectiveWidth -= xOffset; } x = day * effectiveWidth / mNumDays + xOffset; return x; } @Override protected void drawDaySeparators(Canvas canvas) { float lines[] = new float[8 * 4]; int count = 6 * 4; int wkNumOffset = 0; int i = 0; if (mShowWeekNum) { // This adds the first line separating the week number int xOffset = SPACING_WEEK_NUMBER + mPadding; count += 4; lines[i++] = xOffset; lines[i++] = 0; lines[i++] = xOffset; lines[i++] = mHeight; wkNumOffset++; } count += 4; lines[i++] = 0; lines[i++] = 0; lines[i++] = mWidth; lines[i++] = 0; int y0 = 0; int y1 = mHeight; while (i < count) { int x = computeDayLeftPosition(i / 4 - wkNumOffset); lines[i++] = x; lines[i++] = y0; lines[i++] = x; lines[i++] = y1; } p.setColor(mDaySeparatorInnerColor); p.setStrokeWidth(DAY_SEPARATOR_INNER_WIDTH); canvas.drawLines(lines, 0, count, p); } @Override protected void drawBackground(Canvas canvas) { int i = 0; int offset = 0; r.top = DAY_SEPARATOR_INNER_WIDTH; r.bottom = mHeight; if (mShowWeekNum) { i++; offset++; } if (!mOddMonth[i]) { while (++i < mOddMonth.length && !mOddMonth[i]) ; r.right = computeDayLeftPosition(i - offset); r.left = 0; p.setColor(mMonthBGOtherColor); canvas.drawRect(r, p); // compute left edge for i, set up r, draw } else if (!mOddMonth[(i = mOddMonth.length - 1)]) { while (--i >= offset && !mOddMonth[i]) ; i++; // compute left edge for i, set up r, draw r.right = mWidth; r.left = computeDayLeftPosition(i - offset); p.setColor(mMonthBGOtherColor); canvas.drawRect(r, p); } if (mHasToday) { p.setColor(mMonthBGTodayColor); r.left = computeDayLeftPosition(mTodayIndex); r.right = computeDayLeftPosition(mTodayIndex + 1); canvas.drawRect(r, p); } } // Draw the "clicked" color on the tapped day private void drawClick(Canvas canvas) { if (mClickedDayIndex != -1) { int alpha = p.getAlpha(); p.setColor(mClickedDayColor); p.setAlpha(mClickedAlpha); r.left = computeDayLeftPosition(mClickedDayIndex); r.right = computeDayLeftPosition(mClickedDayIndex + 1); r.top = DAY_SEPARATOR_INNER_WIDTH; r.bottom = mHeight; canvas.drawRect(r, p); p.setAlpha(alpha); } } @Override protected void drawWeekNums(Canvas canvas) { int y; int i = 0; int offset = -1; int todayIndex = mTodayIndex; int x = 0; int numCount = mNumDays; if (mShowWeekNum) { x = SIDE_PADDING_WEEK_NUMBER + mPadding; y = mWeekNumAscentHeight + TOP_PADDING_WEEK_NUMBER; canvas.drawText(mDayNumbers[0], x, y, mWeekNumPaint); numCount++; i++; todayIndex++; offset++; } y = mMonthNumAscentHeight + TOP_PADDING_MONTH_NUMBER; boolean isFocusMonth = mFocusDay[i]; boolean isBold = false; mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor); for (; i < numCount; i++) { if (mHasToday && todayIndex == i) { mMonthNumPaint.setColor(mMonthNumTodayColor); mMonthNumPaint.setFakeBoldText(isBold = true); if (i + 1 < numCount) { // Make sure the color will be set back on the next // iteration isFocusMonth = !mFocusDay[i + 1]; } } else if (mFocusDay[i] != isFocusMonth) { isFocusMonth = mFocusDay[i]; mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor); } x = computeDayLeftPosition(i - offset) - (SIDE_PADDING_MONTH_NUMBER); canvas.drawText(mDayNumbers[i], x, y, mMonthNumPaint); if (isBold) { mMonthNumPaint.setFakeBoldText(isBold = false); } } } protected void drawEvents(Canvas canvas) { if (mEvents == null) { return; } int day = -1; for (ArrayList<Event> eventDay : mEvents) { day++; if (eventDay == null || eventDay.size() == 0) { continue; } int ySquare; int xSquare = computeDayLeftPosition(day) + SIDE_PADDING_MONTH_NUMBER + 1; int rightEdge = computeDayLeftPosition(day + 1); if (mOrientation == Configuration.ORIENTATION_PORTRAIT) { ySquare = EVENT_Y_OFFSET_PORTRAIT + mMonthNumHeight + TOP_PADDING_MONTH_NUMBER; rightEdge -= SIDE_PADDING_MONTH_NUMBER + 1; } else { ySquare = EVENT_Y_OFFSET_LANDSCAPE; rightEdge -= EVENT_X_OFFSET_LANDSCAPE; } // Determine if everything will fit when time ranges are shown. boolean showTimes = true; Iterator<Event> iter = eventDay.iterator(); int yTest = ySquare; while (iter.hasNext()) { Event event = iter.next(); int newY = drawEvent(canvas, event, xSquare, yTest, rightEdge, iter.hasNext(), showTimes, /*doDraw*/ false); if (newY == yTest) { showTimes = false; break; } yTest = newY; } int eventCount = 0; iter = eventDay.iterator(); while (iter.hasNext()) { Event event = iter.next(); int newY = drawEvent(canvas, event, xSquare, ySquare, rightEdge, iter.hasNext(), showTimes, /*doDraw*/ true); if (newY == ySquare) { break; } eventCount++; ySquare = newY; } int remaining = eventDay.size() - eventCount; if (remaining > 0) { drawMoreEvents(canvas, remaining, xSquare); } } } protected int addChipOutline(FloatRef lines, int count, int x, int y) { lines.ensureSize(count + 16); // top of box lines.array[count++] = x; lines.array[count++] = y; lines.array[count++] = x + EVENT_SQUARE_WIDTH; lines.array[count++] = y; // right side of box lines.array[count++] = x + EVENT_SQUARE_WIDTH; lines.array[count++] = y; lines.array[count++] = x + EVENT_SQUARE_WIDTH; lines.array[count++] = y + EVENT_SQUARE_WIDTH; // left side of box lines.array[count++] = x; lines.array[count++] = y; lines.array[count++] = x; lines.array[count++] = y + EVENT_SQUARE_WIDTH + 1; // bottom of box lines.array[count++] = x; lines.array[count++] = y + EVENT_SQUARE_WIDTH; lines.array[count++] = x + EVENT_SQUARE_WIDTH + 1; lines.array[count++] = y + EVENT_SQUARE_WIDTH; return count; } /** * Attempts to draw the given event. Returns the y for the next event or the * original y if the event will not fit. An event is considered to not fit * if the event and its extras won't fit or if there are more events and the * more events line would not fit after drawing this event. * * @param canvas the canvas to draw on * @param event the event to draw * @param x the top left corner for this event's color chip * @param y the top left corner for this event's color chip * @param rightEdge the rightmost point we're allowed to draw on (exclusive) * @param moreEvents indicates whether additional events will follow this one * @param showTimes if set, a second line with a time range will be displayed for non-all-day * events * @param doDraw if set, do the actual drawing; otherwise this just computes the height * and returns * @return the y for the next event or the original y if it won't fit */ protected int drawEvent(Canvas canvas, Event event, int x, int y, int rightEdge, boolean moreEvents, boolean showTimes, boolean doDraw) { /* * Vertical layout: * (top of box) * a. EVENT_Y_OFFSET_LANDSCAPE or portrait equivalent * b. Event title: mEventHeight for a normal event, + 2xBORDER_SPACE for all-day event * c. [optional] Time range (mExtrasHeight) * d. EVENT_LINE_PADDING * * Repeat (b,c,d) as needed and space allows. If we have more events than fit, we need * to leave room for something like "+2" at the bottom: * * e. "+ more" line (mExtrasHeight) * * f. EVENT_BOTTOM_PADDING (overlaps EVENT_LINE_PADDING) * (bottom of box) */ final int BORDER_SPACE = EVENT_SQUARE_BORDER + 1; // want a 1-pixel gap inside border final int STROKE_WIDTH_ADJ = EVENT_SQUARE_BORDER / 2; // adjust bounds for stroke width boolean allDay = event.allDay; int eventRequiredSpace = mEventHeight; if (allDay) { // Add a few pixels for the box we draw around all-day events. eventRequiredSpace += BORDER_SPACE * 2; } else if (showTimes) { // Need room for the "1pm - 2pm" line. eventRequiredSpace += mExtrasHeight; } int reservedSpace = EVENT_BOTTOM_PADDING; // leave a bit of room at the bottom if (moreEvents) { // More events follow. Leave a bit of space between events. eventRequiredSpace += EVENT_LINE_PADDING; // Make sure we have room for the "+ more" line. (The "+ more" line is expected // to be <= the height of an event line, so we won't show "+1" when we could be // showing the event.) reservedSpace += mExtrasHeight; } if (y + eventRequiredSpace + reservedSpace > mHeight) { // Not enough space, return original y return y; } else if (!doDraw) { return y + eventRequiredSpace; } boolean isDeclined = event.selfAttendeeStatus == Attendees.ATTENDEE_STATUS_DECLINED; int color = event.color; if (isDeclined) { color = Utils.getDeclinedColorFromColor(color); } int textX, textY, textRightEdge; if (allDay) { // We shift the render offset "inward", because drawRect with a stroke width greater // than 1 draws outside the specified bounds. (We don't adjust the left edge, since // we want to match the existing appearance of the "event square".) r.left = x; r.right = rightEdge - STROKE_WIDTH_ADJ; r.top = y + STROKE_WIDTH_ADJ; r.bottom = y + mEventHeight + BORDER_SPACE * 2 - STROKE_WIDTH_ADJ; textX = x + BORDER_SPACE; textY = y + mEventAscentHeight + BORDER_SPACE; textRightEdge = rightEdge - BORDER_SPACE; } else { r.left = x; r.right = x + EVENT_SQUARE_WIDTH; r.bottom = y + mEventAscentHeight; r.top = r.bottom - EVENT_SQUARE_WIDTH; textX = x + EVENT_SQUARE_WIDTH + EVENT_RIGHT_PADDING; textY = y + mEventAscentHeight; textRightEdge = rightEdge; } Style boxStyle = Style.STROKE; boolean solidBackground = false; if (event.selfAttendeeStatus != Attendees.ATTENDEE_STATUS_INVITED) { boxStyle = Style.FILL_AND_STROKE; if (allDay) { solidBackground = true; } } mEventSquarePaint.setStyle(boxStyle); mEventSquarePaint.setColor(color); canvas.drawRect(r, mEventSquarePaint); float avail = textRightEdge - textX; CharSequence text = TextUtils.ellipsize( event.title, mEventPaint, avail, TextUtils.TruncateAt.END); Paint textPaint; if (solidBackground) { // Text color needs to contrast with solid background. textPaint = mSolidBackgroundEventPaint; } else if (isDeclined) { // Use "declined event" color. textPaint = mDeclinedEventPaint; } else if (allDay) { // Text inside frame is same color as frame. mFramedEventPaint.setColor(color); textPaint = mFramedEventPaint; } else { // Use generic event text color. textPaint = mEventPaint; } canvas.drawText(text.toString(), textX, textY, textPaint); y += mEventHeight; if (allDay) { y += BORDER_SPACE * 2; } if (showTimes && !allDay) { // show start/end time, e.g. "1pm - 2pm" textY = y + mExtrasAscentHeight; mStringBuilder.setLength(0); text = DateUtils.formatDateRange(getContext(), mFormatter, event.startMillis, event.endMillis, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL, Utils.getTimeZone(getContext(), null)).toString(); text = TextUtils.ellipsize(text, mEventExtrasPaint, avail, TextUtils.TruncateAt.END); canvas.drawText(text.toString(), textX, textY, isDeclined ? mEventDeclinedExtrasPaint : mEventExtrasPaint); y += mExtrasHeight; } y += EVENT_LINE_PADDING; return y; } protected void drawMoreEvents(Canvas canvas, int remainingEvents, int x) { int y = mHeight - (mExtrasDescent + EVENT_BOTTOM_PADDING); String text = getContext().getResources().getQuantityString( R.plurals.month_more_events, remainingEvents); mEventExtrasPaint.setAntiAlias(true); mEventExtrasPaint.setFakeBoldText(true); canvas.drawText(String.format(text, remainingEvents), x, y, mEventExtrasPaint); mEventExtrasPaint.setFakeBoldText(false); } /** * Draws a line showing busy times in each day of week The method draws * non-conflicting times in the event color and times with conflicting * events in the dna conflict color defined in colors. * * @param canvas */ protected void drawDNA(Canvas canvas) { // Draw event and conflict times if (mDna != null) { for (Utils.DNAStrand strand : mDna.values()) { if (strand.color == CONFLICT_COLOR || strand.points == null || strand.points.length == 0) { continue; } mDNATimePaint.setColor(strand.color); canvas.drawLines(strand.points, mDNATimePaint); } // Draw black last to make sure it's on top Utils.DNAStrand strand = mDna.get(CONFLICT_COLOR); if (strand != null && strand.points != null && strand.points.length != 0) { mDNATimePaint.setColor(strand.color); canvas.drawLines(strand.points, mDNATimePaint); } if (mDayXs == null) { return; } int numDays = mDayXs.length; int xOffset = (DNA_ALL_DAY_WIDTH - DNA_WIDTH) / 2; if (strand != null && strand.allDays != null && strand.allDays.length == numDays) { for (int i = 0; i < numDays; i++) { // this adds at most 7 draws. We could sort it by color and // build an array instead but this is easier. if (strand.allDays[i] != 0) { mDNAAllDayPaint.setColor(strand.allDays[i]); canvas.drawLine(mDayXs[i] + xOffset, DNA_MARGIN, mDayXs[i] + xOffset, DNA_MARGIN + DNA_ALL_DAY_HEIGHT, mDNAAllDayPaint); } } } } } @Override protected void updateSelectionPositions() { if (mHasSelectedDay) { int selectedPosition = mSelectedDay - mWeekStart; if (selectedPosition < 0) { selectedPosition += 7; } int effectiveWidth = mWidth - mPadding * 2; effectiveWidth -= SPACING_WEEK_NUMBER; mSelectedLeft = selectedPosition * effectiveWidth / mNumDays + mPadding; mSelectedRight = (selectedPosition + 1) * effectiveWidth / mNumDays + mPadding; mSelectedLeft += SPACING_WEEK_NUMBER; mSelectedRight += SPACING_WEEK_NUMBER; } } public int getDayIndexFromLocation(float x) { int dayStart = mShowWeekNum ? SPACING_WEEK_NUMBER + mPadding : mPadding; if (x < dayStart || x > mWidth - mPadding) { return -1; } // Selection is (x - start) / (pixels/day) == (x -s) * day / pixels return ((int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding))); } @Override public Time getDayFromLocation(float x) { int dayPosition = getDayIndexFromLocation(x); if (dayPosition == -1) { return null; } int day = mFirstJulianDay + dayPosition; Time time = new Time(mTimeZone); if (mWeek == 0) { // This week is weird... if (day < Time.EPOCH_JULIAN_DAY) { day++; } else if (day == Time.EPOCH_JULIAN_DAY) { time.set(1, 0, 1970); time.normalize(true); return time; } } time.setJulianDay(day); return time; } @Override public boolean onHoverEvent(MotionEvent event) { Context context = getContext(); // only send accessibility events if accessibility and exploration are // on. AccessibilityManager am = (AccessibilityManager) context .getSystemService(Service.ACCESSIBILITY_SERVICE); if (!am.isEnabled() || !am.isTouchExplorationEnabled()) { return super.onHoverEvent(event); } if (event.getAction() != MotionEvent.ACTION_HOVER_EXIT) { Time hover = getDayFromLocation(event.getX()); if (hover != null && (mLastHoverTime == null || Time.compare(hover, mLastHoverTime) != 0)) { Long millis = hover.toMillis(true); String date = Utils.formatDateRange(context, millis, millis, DateUtils.FORMAT_SHOW_DATE); AccessibilityEvent accessEvent = AccessibilityEvent .obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED); accessEvent.getText().add(date); if (mShowDetailsInMonth && mEvents != null) { int dayStart = SPACING_WEEK_NUMBER + mPadding; int dayPosition = (int) ((event.getX() - dayStart) * mNumDays / (mWidth - dayStart - mPadding)); ArrayList<Event> events = mEvents.get(dayPosition); List<CharSequence> text = accessEvent.getText(); for (Event e : events) { text.add(e.getTitleAndLocation() + ". "); int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR; if (!e.allDay) { flags |= DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(context)) { flags |= DateUtils.FORMAT_24HOUR; } } else { flags |= DateUtils.FORMAT_UTC; } text.add(Utils.formatDateRange(context, e.startMillis, e.endMillis, flags) + ". "); } } sendAccessibilityEventUnchecked(accessEvent); mLastHoverTime = hover; } } return true; } public void setClickedDay(float xLocation) { mClickedDayIndex = getDayIndexFromLocation(xLocation); invalidate(); } public void clearClickedDay() { mClickedDayIndex = -1; invalidate(); } }
true
true
protected void initView() { super.initView(); if (!mInitialized) { Resources resources = getContext().getResources(); mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month); TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number); SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin); CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color); EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color); if (mScale != 1) { TOP_PADDING_MONTH_NUMBER *= mScale; TOP_PADDING_WEEK_NUMBER *= mScale; SIDE_PADDING_MONTH_NUMBER *= mScale; SIDE_PADDING_WEEK_NUMBER *= mScale; SPACING_WEEK_NUMBER *= mScale; TEXT_SIZE_MONTH_NUMBER *= mScale; TEXT_SIZE_EVENT *= mScale; TEXT_SIZE_EVENT_TITLE *= mScale; TEXT_SIZE_MORE_EVENTS *= mScale; TEXT_SIZE_MONTH_NAME *= mScale; TEXT_SIZE_WEEK_NUM *= mScale; DAY_SEPARATOR_OUTER_WIDTH *= mScale; DAY_SEPARATOR_INNER_WIDTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale; EVENT_X_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_PORTRAIT *= mScale; EVENT_SQUARE_WIDTH *= mScale; EVENT_SQUARE_BORDER *= mScale; EVENT_LINE_PADDING *= mScale; EVENT_BOTTOM_PADDING *= mScale; EVENT_RIGHT_PADDING *= mScale; DNA_MARGIN *= mScale; DNA_WIDTH *= mScale; DNA_ALL_DAY_HEIGHT *= mScale; DNA_MIN_SEGMENT_HEIGHT *= mScale; DNA_SIDE_PADDING *= mScale; DEFAULT_EDGE_SPACING *= mScale; DNA_ALL_DAY_WIDTH *= mScale; TODAY_HIGHLIGHT_WIDTH *= mScale; } if (!mShowDetailsInMonth) { TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN; } mInitialized = true; } mPadding = DEFAULT_EDGE_SPACING; loadColors(getContext()); // TODO modify paint properties depending on isMini mMonthNumPaint = new Paint(); mMonthNumPaint.setFakeBoldText(false); mMonthNumPaint.setAntiAlias(true); mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER); mMonthNumPaint.setColor(mMonthNumColor); mMonthNumPaint.setStyle(Style.FILL); mMonthNumPaint.setTextAlign(Align.RIGHT); mMonthNumPaint.setTypeface(Typeface.DEFAULT); mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f); mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f); mEventPaint = new TextPaint(); mEventPaint.setFakeBoldText(true); mEventPaint.setAntiAlias(true); mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mEventPaint.setColor(mMonthEventColor); mSolidBackgroundEventPaint = new TextPaint(mEventPaint); mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR); mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint); mDeclinedEventPaint = new TextPaint(); mDeclinedEventPaint.setFakeBoldText(true); mDeclinedEventPaint.setAntiAlias(true); mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mDeclinedEventPaint.setColor(mMonthDeclinedEventColor); mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f); mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f); mEventExtrasPaint = new TextPaint(); mEventExtrasPaint.setFakeBoldText(false); mEventExtrasPaint.setAntiAlias(true); mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventExtrasPaint.setColor(mMonthEventExtraColor); mEventExtrasPaint.setStyle(Style.FILL); mEventExtrasPaint.setTextAlign(Align.LEFT); mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f); mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f); mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f); mEventDeclinedExtrasPaint = new TextPaint(); mEventDeclinedExtrasPaint.setFakeBoldText(false); mEventDeclinedExtrasPaint.setAntiAlias(true); mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor); mEventDeclinedExtrasPaint.setStyle(Style.FILL); mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT); mWeekNumPaint = new Paint(); mWeekNumPaint.setFakeBoldText(false); mWeekNumPaint.setAntiAlias(true); mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM); mWeekNumPaint.setColor(mWeekNumColor); mWeekNumPaint.setStyle(Style.FILL); mWeekNumPaint.setTextAlign(Align.RIGHT); mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f); mDNAAllDayPaint = new Paint(); mDNATimePaint = new Paint(); mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor); mDNATimePaint.setStyle(Style.FILL_AND_STROKE); mDNATimePaint.setStrokeWidth(DNA_WIDTH); mDNATimePaint.setAntiAlias(false); mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor); mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE); mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH); mDNAAllDayPaint.setAntiAlias(false); mEventSquarePaint = new Paint(); mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventSquarePaint.setAntiAlias(false); if (DEBUG_LAYOUT) { Log.d("EXTRA", "mScale=" + mScale); Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent() + " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight); Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent() + " descent=" + mEventPaint.descent() + " int height=" + mEventHeight + " int ascent=" + mEventAscentHeight); Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent() + " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight); Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent() + " descent=" + mWeekNumPaint.descent()); } }
protected void initView() { super.initView(); if (!mInitialized) { Resources resources = getContext().getResources(); mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month); TEXT_SIZE_EVENT_TITLE = resources.getInteger(R.integer.text_size_event_title); TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number); SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin); CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color); EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color); if (mScale != 1) { TOP_PADDING_MONTH_NUMBER *= mScale; TOP_PADDING_WEEK_NUMBER *= mScale; SIDE_PADDING_MONTH_NUMBER *= mScale; SIDE_PADDING_WEEK_NUMBER *= mScale; SPACING_WEEK_NUMBER *= mScale; TEXT_SIZE_MONTH_NUMBER *= mScale; TEXT_SIZE_EVENT *= mScale; TEXT_SIZE_EVENT_TITLE *= mScale; TEXT_SIZE_MORE_EVENTS *= mScale; TEXT_SIZE_MONTH_NAME *= mScale; TEXT_SIZE_WEEK_NUM *= mScale; DAY_SEPARATOR_OUTER_WIDTH *= mScale; DAY_SEPARATOR_INNER_WIDTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGTH *= mScale; DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale; EVENT_X_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_LANDSCAPE *= mScale; EVENT_Y_OFFSET_PORTRAIT *= mScale; EVENT_SQUARE_WIDTH *= mScale; EVENT_SQUARE_BORDER *= mScale; EVENT_LINE_PADDING *= mScale; EVENT_BOTTOM_PADDING *= mScale; EVENT_RIGHT_PADDING *= mScale; DNA_MARGIN *= mScale; DNA_WIDTH *= mScale; DNA_ALL_DAY_HEIGHT *= mScale; DNA_MIN_SEGMENT_HEIGHT *= mScale; DNA_SIDE_PADDING *= mScale; DEFAULT_EDGE_SPACING *= mScale; DNA_ALL_DAY_WIDTH *= mScale; TODAY_HIGHLIGHT_WIDTH *= mScale; } if (!mShowDetailsInMonth) { TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN; } mInitialized = true; } mPadding = DEFAULT_EDGE_SPACING; loadColors(getContext()); // TODO modify paint properties depending on isMini mMonthNumPaint = new Paint(); mMonthNumPaint.setFakeBoldText(false); mMonthNumPaint.setAntiAlias(true); mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER); mMonthNumPaint.setColor(mMonthNumColor); mMonthNumPaint.setStyle(Style.FILL); mMonthNumPaint.setTextAlign(Align.RIGHT); mMonthNumPaint.setTypeface(Typeface.DEFAULT); mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f); mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f); mEventPaint = new TextPaint(); mEventPaint.setFakeBoldText(true); mEventPaint.setAntiAlias(true); mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mEventPaint.setColor(mMonthEventColor); mSolidBackgroundEventPaint = new TextPaint(mEventPaint); mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR); mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint); mDeclinedEventPaint = new TextPaint(); mDeclinedEventPaint.setFakeBoldText(true); mDeclinedEventPaint.setAntiAlias(true); mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE); mDeclinedEventPaint.setColor(mMonthDeclinedEventColor); mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f); mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f); mEventExtrasPaint = new TextPaint(); mEventExtrasPaint.setFakeBoldText(false); mEventExtrasPaint.setAntiAlias(true); mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventExtrasPaint.setColor(mMonthEventExtraColor); mEventExtrasPaint.setStyle(Style.FILL); mEventExtrasPaint.setTextAlign(Align.LEFT); mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f); mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f); mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f); mEventDeclinedExtrasPaint = new TextPaint(); mEventDeclinedExtrasPaint.setFakeBoldText(false); mEventDeclinedExtrasPaint.setAntiAlias(true); mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT); mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor); mEventDeclinedExtrasPaint.setStyle(Style.FILL); mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT); mWeekNumPaint = new Paint(); mWeekNumPaint.setFakeBoldText(false); mWeekNumPaint.setAntiAlias(true); mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM); mWeekNumPaint.setColor(mWeekNumColor); mWeekNumPaint.setStyle(Style.FILL); mWeekNumPaint.setTextAlign(Align.RIGHT); mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f); mDNAAllDayPaint = new Paint(); mDNATimePaint = new Paint(); mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor); mDNATimePaint.setStyle(Style.FILL_AND_STROKE); mDNATimePaint.setStrokeWidth(DNA_WIDTH); mDNATimePaint.setAntiAlias(false); mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor); mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE); mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH); mDNAAllDayPaint.setAntiAlias(false); mEventSquarePaint = new Paint(); mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER); mEventSquarePaint.setAntiAlias(false); if (DEBUG_LAYOUT) { Log.d("EXTRA", "mScale=" + mScale); Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent() + " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight); Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent() + " descent=" + mEventPaint.descent() + " int height=" + mEventHeight + " int ascent=" + mEventAscentHeight); Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent() + " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight); Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent() + " descent=" + mWeekNumPaint.descent()); } }
diff --git a/test/src/org/omegat/core/TestCore.java b/test/src/org/omegat/core/TestCore.java index 62459e3a..0fdc3423 100644 --- a/test/src/org/omegat/core/TestCore.java +++ b/test/src/org/omegat/core/TestCore.java @@ -1,81 +1,81 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2008 Alex Buloichik Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **************************************************************************/ package org.omegat.core; import java.awt.Font; import javax.swing.JFrame; import org.omegat.core.data.NotLoadedProject; import org.omegat.gui.main.IMainWindow; import com.vlsolutions.swing.docking.Dockable; import junit.framework.TestCase; /** * Core setup for unit tests. * * @author Alexander_Buloichik */ public abstract class TestCore extends TestCase { protected void setUp() throws Exception { Core.setMainWindow(new IMainWindow() { public void addDockable(Dockable pane) { } public void displayErrorRB(Throwable ex, String errorKey, Object... params) { } public Font getApplicationFont() { return new Font("Dialog", Font.PLAIN, 12); } public JFrame getApplicationFrame() { return null; } public void lockUI() { } public void showLengthMessage(String messageText) { } public void showProgressMessage(String messageText) { } public void showStatusMessageRB(String messageKey, Object... params) { } - public void showErrorDialogRB(String message, String title) { + public void showErrorDialogRB(String message, Object[] args, String title) { } public void unlockUI() { } }); Core.setCurrentProject(new NotLoadedProject()); } }
true
true
protected void setUp() throws Exception { Core.setMainWindow(new IMainWindow() { public void addDockable(Dockable pane) { } public void displayErrorRB(Throwable ex, String errorKey, Object... params) { } public Font getApplicationFont() { return new Font("Dialog", Font.PLAIN, 12); } public JFrame getApplicationFrame() { return null; } public void lockUI() { } public void showLengthMessage(String messageText) { } public void showProgressMessage(String messageText) { } public void showStatusMessageRB(String messageKey, Object... params) { } public void showErrorDialogRB(String message, String title) { } public void unlockUI() { } }); Core.setCurrentProject(new NotLoadedProject()); }
protected void setUp() throws Exception { Core.setMainWindow(new IMainWindow() { public void addDockable(Dockable pane) { } public void displayErrorRB(Throwable ex, String errorKey, Object... params) { } public Font getApplicationFont() { return new Font("Dialog", Font.PLAIN, 12); } public JFrame getApplicationFrame() { return null; } public void lockUI() { } public void showLengthMessage(String messageText) { } public void showProgressMessage(String messageText) { } public void showStatusMessageRB(String messageKey, Object... params) { } public void showErrorDialogRB(String message, Object[] args, String title) { } public void unlockUI() { } }); Core.setCurrentProject(new NotLoadedProject()); }
diff --git a/hot-deploy/opentaps-common/src/prebuild/org/opentaps/domain/container/PojoGeneratorContainer.java b/hot-deploy/opentaps-common/src/prebuild/org/opentaps/domain/container/PojoGeneratorContainer.java index b34e4fbb9..cbd03e034 100644 --- a/hot-deploy/opentaps-common/src/prebuild/org/opentaps/domain/container/PojoGeneratorContainer.java +++ b/hot-deploy/opentaps-common/src/prebuild/org/opentaps/domain/container/PojoGeneratorContainer.java @@ -1,954 +1,956 @@ /* * Copyright (c) 2008 - 2009 Open Source Strategies, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Honest Public License. * * 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 * Honest Public License for more details. * * You should have received a copy of the Honest Public License * along with this program; if not, write to Funambol, * 643 Bair Island Road, Suite 305 - Redwood City, CA 94063, USA */ /******************************************************************************* * 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. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.opentaps.domain.container; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.io.FileUtils; import org.jvnet.inflector.Noun; import org.ofbiz.base.container.Container; import org.ofbiz.base.container.ContainerConfig; import org.ofbiz.base.container.ContainerException; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.ObjectType; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.base.util.template.FreeMarkerWorker; import org.ofbiz.entity.GenericDelegator; import org.ofbiz.entity.GenericEntityException; import org.ofbiz.entity.model.ModelEntity; import org.ofbiz.entity.model.ModelField; import org.ofbiz.entity.model.ModelFieldType; import org.ofbiz.entity.model.ModelKeyMap; import org.ofbiz.entity.model.ModelReader; import org.ofbiz.entity.model.ModelRelation; import org.ofbiz.entity.model.ModelUtil; import org.ofbiz.entity.model.ModelViewEntity; import org.ofbiz.entity.model.ModelViewEntity.ModelAlias; import org.ofbiz.entity.model.ModelViewEntity.ModelMemberEntity; import org.ofbiz.entity.model.ModelViewEntity.ModelViewLink; import org.ofbiz.service.ServiceDispatcher; import freemarker.template.TemplateException; /** * Some utility routines for loading seed data. */ public class PojoGeneratorContainer implements Container { private static final String MODULE = PojoGeneratorContainer.class.getName(); private static final String containerName = "pojo-generator-container"; private static final String fileExtension = ".java"; private static final List<String> extendClassNames = new ArrayList<String>(); static { extendClassNames.add("Person"); extendClassNames.add("PartyGroup"); } /** Config file. */ private String configFile = null; /** The path of output. */ private String outputPath = null; /** Java class FTL Template. */ private String template = null; /** Hibernate IdClass FTL Template. */ private String pkTemplate = null; /** Hibernate Search PkBridge FTL Template. */ private String pkBridgeTemplate = null; /** Hibernate configuration FTL Template. */ private String hibernateCfgTemplate = null; /** * Creates a new <code>PojoGeneratorContainer</code> instance. */ public PojoGeneratorContainer() { super(); } /** {@inheritDoc} */ public void init(String[] args, String configFile) throws ContainerException { this.configFile = configFile; // disable job scheduler, JMS listener and startup services ServiceDispatcher.enableJM(false); ServiceDispatcher.enableJMS(false); ServiceDispatcher.enableSvcs(false); // parse arguments here if needed } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public boolean start() throws ContainerException { ContainerConfig.Container cfg = ContainerConfig.getContainer(containerName, configFile); ContainerConfig.Container.Property delegatorNameProp = cfg.getProperty("delegator-name"); ContainerConfig.Container.Property outputPathProp = cfg.getProperty("output-path"); ContainerConfig.Container.Property templateProp = cfg.getProperty("template"); ContainerConfig.Container.Property pkTemplateProp = cfg.getProperty("pkTemplate"); ContainerConfig.Container.Property pkBridgeTemplateProp = cfg.getProperty("pkBridgeTemplate"); ContainerConfig.Container.Property hibernateCfgTemplateProp = cfg.getProperty("hibernateCfgTemplate"); ContainerConfig.Container.Property hibernateCfgProp = cfg.getProperty("hibernateCfgPath"); Properties entitySearchProperties = UtilProperties.getProperties("entitysearch.properties"); String delegatorNameToUse = null; // get delegator to use from the container configuration if (delegatorNameProp == null || delegatorNameProp.value == null || delegatorNameProp.value.length() == 0) { throw new ContainerException("Invalid delegator-name defined in container configuration"); } else { delegatorNameToUse = delegatorNameProp.value; } // get the delegator GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorNameToUse); if (delegator == null) { throw new ContainerException("Invalid delegator name: " + delegatorNameToUse); } // get output path to use from the container configuration if (outputPathProp == null || outputPathProp.value == null || outputPathProp.value.length() == 0) { throw new ContainerException("Invalid output-name defined in container configuration"); } else { outputPath = outputPathProp.value; } // check the output path File outputDir = new File(outputPath); if (!outputDir.canWrite()) { throw new ContainerException("Unable to use output path: [" + outputPath + "], it is not writable"); } // get the template file to use from the container configuration if (templateProp == null || templateProp.value == null || templateProp.value.length() == 0) { throw new ContainerException("Invalid template defined in container configuration"); } else { template = templateProp.value; } // check the template file File templateFile = new File(template); if (!templateFile.canRead()) { throw new ContainerException("Unable to read template file: [" + template + "]"); } // get the primay key template file to use from the container configuration if (pkTemplateProp == null || pkTemplateProp.value == null || pkTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk template defined in container configuration"); } else { pkTemplate = pkTemplateProp.value; } // check the pk template file File pkTemplateFile = new File(pkTemplate); if (!pkTemplateFile.canRead()) { throw new ContainerException("Unable to read pk template file: [" + pkTemplate + "]"); } // get the primay key template file to use from the container configuration if (hibernateCfgTemplateProp == null || hibernateCfgTemplateProp.value == null || hibernateCfgTemplateProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg template defined in container configuration"); } else { hibernateCfgTemplate = hibernateCfgTemplateProp.value; } // check the pk template file File cfgTemplateFile = new File(hibernateCfgTemplate); if (!cfgTemplateFile.canRead()) { throw new ContainerException("Unable to read hibernate cfg template file: [" + hibernateCfgTemplate + "]"); } // get the primay key bridge template file to use from the container configuration if (pkBridgeTemplateProp == null || pkBridgeTemplateProp.value == null || pkBridgeTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk bridge template defined in container configuration"); } else { pkBridgeTemplate = pkBridgeTemplateProp.value; } // check the pk template file File pkBridgeTemplateFile = new File(pkBridgeTemplate); if (!pkBridgeTemplateFile.canRead()) { throw new ContainerException("Unable to read pk bridge template file: [" + pkBridgeTemplate + "]"); } // get entities list ModelReader modelReader = delegator.getModelReader(); Collection<String> entities = null; try { entities = modelReader.getEntityNames(); } catch (GenericEntityException e) { Debug.logError(e, "Error getting the entities list from delegator " + delegatorNameToUse, MODULE); } // record errors for summary List<String> errorEntities = new LinkedList<String>(); // record view entities List<String> viewEntities = new LinkedList<String>(); int totalGeneratedClasses = 0; if (entities != null && entities.size() > 0) { Debug.logImportant("=-=-=-=-=-=-= Generating the POJO entities ...", MODULE); for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); if (modelEntity != null && modelEntity instanceof ModelViewEntity) { viewEntities.add(entityName); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } List<String> needIndexEntities = new LinkedList<String>(); for (String entityName : entities) { //retrieve entityName if (entitySearchProperties.containsKey(entityName)) { if (entitySearchProperties.getProperty(entityName).equals("index")) { needIndexEntities.add(entityName); } } } for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } if (modelEntity == null) { errorEntities.add(entityName); Debug.logError("Error getting the entity model from delegator " + delegatorNameToUse + " and entity " + entityName, MODULE); continue; } // could be an object, but is just a Map for simplicity Map<String, Object> entityInfo = new HashMap<String, Object>(); // entity columns what used in entity field List<String> entityColumns = new ArrayList<String>(); boolean isView = false; // justify the entity whether need index or not boolean isNeedIndex = needIndexEntities.contains(entityName); if ((modelEntity instanceof ModelViewEntity)) { isView = true; // the view entity cannot index isNeedIndex = false; } // get name of the entity entityName = modelEntity.getEntityName(); entityInfo.put("name", entityName); entityInfo.put("tableName", modelEntity.getPlainTableName()); entityInfo.put("isView", isView); entityInfo.put("isNeedIndex", isNeedIndex); entityInfo.put("needIndexEntities", needIndexEntities); entityInfo.put("resourceName", modelEntity.getDefaultResourceName()); entityInfo.put("primaryKeys", modelEntity.getPkFieldNames()); entityInfo.put("viewEntities" , viewEntities); // get all the fields of the entity which become members of the class List<String> fieldNames = modelEntity.getAllFieldNames(); entityInfo.put("fields", fieldNames); //get all the columns of the entity Map<String, String> columnNames = new TreeMap<String, String>(); for (String fieldName : fieldNames) { String columnName = modelEntity.getColNameOrAlias(fieldName); columnNames.put(fieldName, columnName); entityColumns.add(columnName); } entityInfo.put("columnNames", columnNames); // distinct types for the import section Set<String> types = new TreeSet<String>(); // a type for each field during declarations Map<String, String> fieldTypes = new TreeMap<String, String>(); // indicate declarations Map<String, String> indexWeights = new TreeMap<String, String>(); Map<String, String> tokenTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getMethodNames = new TreeMap<String, String>(); Map<String, String> setMethodNames = new TreeMap<String, String>(); Map<String, List<String>> validatorMaps = new TreeMap<String, List<String>>(); // now go through all the fields boolean hasError = false; for (String fieldName : fieldNames) { // use the model field to figure out the Java type ModelField modelField = modelEntity.getField(fieldName); String type = null; try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. ModelFieldType fieldType = delegator.getEntityFieldType(modelEntity, modelField.getType()); if (fieldType == null) { throw new GenericEntityException("No helper defined for entity " + entityName + ". Check if this entity has an entitygroup.xml definition"); } type = ObjectType.loadClass(fieldType.getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + fieldName + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } // make all Object field to byte[] if ("java.lang.Object".equals(type)) { type = "byte[]"; } else { types.add(type); } // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } fieldTypes.put(fieldName, shortType); // if entitysearch.properties contain the field, then add boost annotation to set index weight String indexFieldKey = entityName + "." + fieldName; if (entitySearchProperties.containsKey(indexFieldKey)) { String[] indexValue = entitySearchProperties.getProperty(indexFieldKey).split(","); String weight = indexValue[0]; String tokenType = indexValue.length > 1 ? indexValue[1] : "TOKENIZED"; indexWeights.put(fieldName, weight); tokenTypes.put(fieldName, tokenType); } // accessor method names try { getMethodNames.put(fieldName, getterName(fieldName)); setMethodNames.put(fieldName, setterName(fieldName)); } catch (IllegalArgumentException e) { errorEntities.add(entityName); Debug.logError(e, MODULE); hasError = true; break; } if (modelField.getValidatorsSize() > 0) { List<String> validators = new ArrayList<String>(); for (int i = 0; i < modelField.getValidatorsSize(); i++) { String validator = modelField.getValidator(i); validators.add(validator); } validatorMaps.put(fieldName, validators); } } if (hasError) { continue; } // get the relations List<Map<String, String>> relations = new ArrayList<Map<String, String>>(); Iterator<ModelRelation> relationsIter = modelEntity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); Map<String, String> relationInfo = new TreeMap<String, String>(); relationInfo.put("entityName", modelRelation.getRelEntityName()); // the string to put in the getRelated() method, title is "" if null relationInfo.put("relationName", modelRelation.getTitle() + modelRelation.getRelEntityName()); // the names are pluralized for relation of type many String accessorName = modelRelation.getTitle() + modelRelation.getRelEntityName(); + // title may have white spaces, remove them to use as an attribute in the java class + accessorName = accessorName.replaceAll(" ", ""); // justify if need create hibernate mapping annotation String isNeedMapping = "Y"; if ("many".equals(modelRelation.getType())) { relationInfo.put("type", "many"); try { accessorName = Noun.pluralOf(accessorName, Locale.ENGLISH); } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the plural of " + accessorName + ", falling back to " + accessorName + "s.", MODULE); accessorName = accessorName + "s"; } // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(entityName)) { isNeedMapping = "N"; } } else { // we do not care about the difference between one and one-nofk types, because we can use one-to-one to cascade relationInfo.put("type", "one"); // mark isOneToOne field for Entity ftl, this is useful for hibernate search feature try { String joinField = modelRelation.getKeyMap(0).getFieldName(); ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); if (modelRelation.isAutoRelation() && refEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().size() == 1 && (refEntity.getPkFieldNames().contains(modelEntity.getPkFieldNames()) || modelEntity.getPkFieldNames().contains(joinField))) { relationInfo.put("isOneToOne", "Y"); } else { relationInfo.put("isOneToOne", "N"); // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(modelRelation.getRelEntityName())) { isNeedMapping = "N"; } } } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the relative Entity " + modelRelation.getRelEntityName() + ".", MODULE); accessorName = accessorName + "s"; } } // check if the accessor conflicts with an already defined field String fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); if (fieldNames.contains(fieldName)) { String oldFieldName = fieldName; accessorName = "Related" + accessorName; fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); Debug.logWarning("For entity " + entityName + ", field " + oldFieldName + " already defined, using " + fieldName + " instead.", MODULE); } String fkName = modelRelation.getFkName(); relationInfo.put("accessorName", accessorName); relationInfo.put("fieldName", fieldName); relationInfo.put("fkName", fkName); relationInfo.put("isNeedMapping", isNeedMapping); if (modelRelation.getKeyMapsSize() == 1) { //relation child Entity field String joinField = ""; //relation parent Entity field String mappedByFieldId = ""; String columnName = ""; if ("many".equals(modelRelation.getType())) { joinField = modelRelation.getKeyMap(0).getRelFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getFieldName(); try { // get relative column name ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); columnName = refEntity.getColNameOrAlias(joinField); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { joinField = modelRelation.getKeyMap(0).getFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getRelFieldName(); // get joinField column columnName = modelEntity.getColNameOrAlias(joinField); } //adjust this column if use for other relation, if used we should mapped with insert="false" update="false" if (!entityColumns.contains(columnName)) { entityColumns.add(columnName); relationInfo.put("isRepeated", "N"); } else { relationInfo.put("isRepeated", "Y"); } relationInfo.put("joinColumn", columnName); //if this property is collection, and have only one primary key, and find it in child property // this is useful for hibernate's cascading feature if ("many".equals(modelRelation.getType()) && modelEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().contains(mappedByFieldId)) { try { ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); // manyToOne field String refField = ""; Iterator it = refEntity.getRelationsIterator(); while (it.hasNext()) { ModelRelation relation = (ModelRelation) it.next(); //if relation map modelRelation if (relation.getRelEntityName().equals(entityName) && relation.getKeyMapsSize() == 1 && relation.getKeyMap(0).getFieldName().equals(joinField)) { //get access name String aName = relation.getTitle() + relation.getRelEntityName(); //get ref field name refField = aName.substring(0, 1).toLowerCase() + aName.substring(1); break; } } if (refEntity.getPkFieldNames().contains(joinField) && !refField.equals("")) { // if this collection should be a cascade collection property relationInfo.put("itemName", itemName(fieldName)); relationInfo.put("refField", refField); //put add item method of collection relationInfo.put("addMethodName", addName(fieldName)); //put remove item method of collection relationInfo.put("removeMethodName", removeName(fieldName)); //put clear item method of collection relationInfo.put("clearMethodName", clearName(fieldName)); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } } relations.add(relationInfo); } entityInfo.put("relations", relations); entityInfo.put("types", types); entityInfo.put("fieldTypes", fieldTypes); entityInfo.put("getMethodNames", getMethodNames); entityInfo.put("setMethodNames", setMethodNames); entityInfo.put("validatorMaps", validatorMaps); entityInfo.put("indexWeights", indexWeights); entityInfo.put("tokenTypes", tokenTypes); // map view-entity to @NamedNativeQuery if (isView) { //pk fields of the first entity as view-entity pk List<String> viewEntityPks = new LinkedList<String>(); StringBuffer query = new StringBuffer(); query.append("SELECT "); // field <-> column alias mapping Map<String, String> fieldMapAlias = new TreeMap<String, String>(); // field <-> column name mapping Map<String, String> fieldMapColumns = new TreeMap<String, String>(); List<String> relationAlias = new LinkedList<String>(); ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity; Iterator aliasIter = modelViewEntity.getAliasesIterator(); // iterate all fields, construct select sentence while (aliasIter.hasNext()) { ModelAlias alias = (ModelAlias) aliasIter.next(); String columnName = ModelUtil.javaNameToDbName(alias.getField()); if (fieldMapAlias.size() > 0) { query.append(","); } //iterator field, such as "P.PARTY_ID \"partyId\" query.append(alias.getEntityAlias() + "." + columnName + " AS \\\"" + alias.getField() + "\\\""); String colAlias = alias.getColAlias(); String field = ModelUtil.dbNameToVarName(alias.getColAlias()); // put field-colAlias mapping fieldMapAlias.put(field, colAlias); // put field-column mapping fieldMapColumns.put(field, alias.getEntityAlias() + "." + columnName); } // iterate all entities, construct from sentence for (int i = 0; i < modelViewEntity.getAllModelMemberEntities().size(); i++) { ModelMemberEntity modelMemberEntity = (ModelMemberEntity) modelViewEntity.getAllModelMemberEntities().get(i); String tableName = ModelUtil.javaNameToDbName(modelMemberEntity.getEntityName()); String tableAlias = modelMemberEntity.getEntityAlias(); relationAlias.add(tableAlias); if (i == 0) { // main table query.append(" FROM " + tableName + " " + tableAlias); // get all the pk fields of the first entity which become members of the class try { ModelEntity firstEntity = modelReader.getModelEntity(modelMemberEntity.getEntityName()); Iterator it = firstEntity.getPksIterator(); while (it.hasNext()) { ModelField field = (ModelField) it.next(); //just need one pk, else secondary pk would be null if (fieldMapAlias.containsKey(field.getName()) && viewEntityPks.size()==0) { viewEntityPks.add(field.getName()); } } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { // join table Iterator viewLinkIter = modelViewEntity.getViewLinksIterator(); while (viewLinkIter.hasNext()) { ModelViewLink modelViewLink = (ModelViewLink) viewLinkIter.next(); if (relationAlias.contains(modelViewLink.getEntityAlias()) && relationAlias.contains(modelViewLink.getRelEntityAlias()) && (tableAlias.equals(modelViewLink.getEntityAlias()) || tableAlias.equals(modelViewLink.getRelEntityAlias())) ) { // adjust if left join or inner join String joinType = modelViewLink.isRelOptional() ? " LEFT JOIN " : " INNER JOIN "; query.append(joinType + tableName + " " + tableAlias); for (int k = 0; k < modelViewLink.getKeyMapsSize(); k++) { ModelKeyMap modelKeyMap = modelViewLink.getKeyMap(k); //get join conditions String joinCondition = modelViewLink.getEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getFieldName()) + " = " + modelViewLink.getRelEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getRelFieldName()); if (k == 0) { // if it is first join condition query.append(" ON " + joinCondition); } else { // if it isn't first join condition query.append(" AND " + joinCondition); } } } } } } // if no pk for this viewEntity, then give a random field, because hibernate annotation need at least one pk filed. if (viewEntityPks.size() == 0) { viewEntityPks.add(fieldNames.get(0)); } entityInfo.put("query", query.toString()); entityInfo.put("fieldMapAlias", fieldMapAlias); entityInfo.put("fieldMapColumns", fieldMapColumns); entityInfo.put("viewEntityPks", viewEntityPks); } // render it as FTL Writer writer = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(template, entityInfo, writer); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file File file = new File(outputPath + entityName + fileExtension); try { FileUtils.writeStringToFile(file, writer.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + fileExtension, MODULE); errorEntities.add(entityName); break; } // pk class info Map<String, Object> pkInfo = null; if (!isView && modelEntity.getPkFieldNames().size() > 1) { //if entity has more than one pk pkInfo = new TreeMap<String, Object>(); // get all the pk fields of the entity which become members of the class List<String> primaryKeys = modelEntity.getPkFieldNames(); // a type for each pk during declarations Map<String, String> pkTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getPkMethodNames = new TreeMap<String, String>(); Map<String, String> setPkMethodNames = new TreeMap<String, String>(); // distinct types for the import section Set<String> pkFieldTypes = new TreeSet<String>(); Iterator<ModelField> pksIter = modelEntity.getPksIterator(); while (pksIter.hasNext()) { String type = null; ModelField modelField = pksIter.next(); getPkMethodNames.put(modelField.getName(), getterName(modelField.getName())); setPkMethodNames.put(modelField.getName(), setterName(modelField.getName())); try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. type = ObjectType.loadClass(delegator.getEntityFieldType(modelEntity, modelField.getType()).getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + modelField.getName() + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } pkFieldTypes.add(type); // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } pkTypes.put(modelField.getName(), shortType); } pkInfo.put("pkName", modelEntity.getEntityName() + "Pk"); pkInfo.put("entityName", modelEntity.getEntityName()); pkInfo.put("primaryKeys", primaryKeys); pkInfo.put("pkTypes", pkTypes); pkInfo.put("getPkMethodNames", getPkMethodNames); pkInfo.put("setPkMethodNames", setPkMethodNames); pkInfo.put("pkFieldTypes", pkFieldTypes); pkInfo.put("columnNames", columnNames); } if (pkInfo != null) { // render pk class as FTL Writer pkWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkTemplate, pkInfo, pkWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkFile = new File(outputPath + entityName + "Pk" + fileExtension); try { FileUtils.writeStringToFile(pkFile, pkWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + "Pk" + fileExtension, MODULE); errorEntities.add(entityName); break; } // render pk bridge class as FTL Writer pkBridgeWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkBridgeTemplate, pkInfo, pkBridgeWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkBridgeFile = new File(outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension); try { FileUtils.writeStringToFile(pkBridgeFile, pkBridgeWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension, MODULE); errorEntities.add(entityName); break; } } // increment counter totalGeneratedClasses++; } // render hibernate.cfg.xml by FTL Writer cfgWriter = new StringWriter(); Map<String, Object> cfgInfo = new HashMap<String, Object>(); cfgInfo.put("entities", entities); try { FreeMarkerWorker.renderTemplateAtLocation(hibernateCfgTemplate, cfgInfo, cfgWriter); } catch (MalformedURLException e1) { Debug.logError(e1, MODULE); } catch (TemplateException e1) { Debug.logError(e1, MODULE); } catch (IOException e1) { Debug.logError(e1, MODULE); } // get hibernate.cfg.xml output path to use from the container configuration String hibernateCfgPath = null; if (hibernateCfgProp == null || hibernateCfgProp.value == null || hibernateCfgProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg path defined in container configuration"); } else { hibernateCfgPath = hibernateCfgProp.value; } // write it as a hibernate.cfg.xml File hibernateFile = new File(hibernateCfgPath); try { FileUtils.writeStringToFile(hibernateFile, cfgWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + hibernateCfgPath, MODULE); } } else { Debug.logImportant("=-=-=-=-=-=-= No entity found.", MODULE); } // error summary if (errorEntities.size() > 0) { Debug.logImportant("The following entities could not be generated:", MODULE); for (String name : errorEntities) { Debug.logImportant(name, MODULE); } } Debug.logImportant("=-=-=-=-=-=-= Finished the POJO entities generation with " + totalGeneratedClasses + " classes generated.", MODULE); if (errorEntities.size() > 0) { return false; } return true; } /** {@inheritDoc} */ public void stop() throws ContainerException { } /** * Standardize accessor method names. If fieldName is orderId, will return "prefix" + OrderId. * * @param prefix prefix to the method name, for example "get" or "set" * @param fieldName name of the field the accessor method access * @return the accessor method name */ public static String accessorMethodName(String prefix, String fieldName) { if (UtilValidate.isEmpty(fieldName)) { throw new IllegalArgumentException("methodName called for null or empty fieldName"); } else { return prefix + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); } } /** * Standardize accessor collection method names. If fieldName is items, will return "prefix" + Item. * * @param prefix prefix to the method name, for example "add" or "remove" * @param fieldName name of the field the accessor method access * @return the accessor method name */ public static String accessorCollectionMethodName(String prefix, String fieldName) { if (UtilValidate.isEmpty(fieldName)) { throw new IllegalArgumentException("methodName called for null or empty fieldName"); } else { return prefix + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1, fieldName.length() - 1); } } /** * Standardize getter method names. * * @param fieldName name of the field the accessor method access * @return the getter method name */ public static String getterName(String fieldName) { return accessorMethodName("get", fieldName); } /** * Standardize setter method names. * * @param fieldName name of the field the accessor method access * @return the setter method name */ public static String setterName(String fieldName) { return accessorMethodName("set", fieldName); } /** * Standardize add method of Collection property names. * * @param fieldName name of the field the add method access * @return the method name */ public static String addName(String fieldName) { return accessorCollectionMethodName("add", fieldName); } /** * Standardize remove method of Collection property names. * * @param fieldName name of the field the remove method access * @return the method name */ public static String removeName(String fieldName) { return accessorCollectionMethodName("remove", fieldName); } /** * Standardize clear method of Collection property names. * * @param fieldName name of the field the clear method access * @return the method name */ public static String clearName(String fieldName) { return accessorCollectionMethodName("clear", fieldName); } /** * get item of Collection property names. * * @param fieldName name of the field the clear method access * @return the item field name */ public static String itemName(String fieldName) { if (UtilValidate.isEmpty(fieldName)) { throw new IllegalArgumentException("methodName called for null or empty fieldName"); } else { return fieldName.substring(0, fieldName.length() - 1); } } /** * get Pk name of Entity. * * @param entityName name of the Entity * @return the Pk field name */ public static String getEntityPkName(String entityName) { if (entityName == null || entityName.equals("")) { return entityName; } String pkName = Character.toLowerCase(entityName.charAt(0)) + entityName.substring(1, entityName.length()) + "Id"; return pkName; } }
true
true
public boolean start() throws ContainerException { ContainerConfig.Container cfg = ContainerConfig.getContainer(containerName, configFile); ContainerConfig.Container.Property delegatorNameProp = cfg.getProperty("delegator-name"); ContainerConfig.Container.Property outputPathProp = cfg.getProperty("output-path"); ContainerConfig.Container.Property templateProp = cfg.getProperty("template"); ContainerConfig.Container.Property pkTemplateProp = cfg.getProperty("pkTemplate"); ContainerConfig.Container.Property pkBridgeTemplateProp = cfg.getProperty("pkBridgeTemplate"); ContainerConfig.Container.Property hibernateCfgTemplateProp = cfg.getProperty("hibernateCfgTemplate"); ContainerConfig.Container.Property hibernateCfgProp = cfg.getProperty("hibernateCfgPath"); Properties entitySearchProperties = UtilProperties.getProperties("entitysearch.properties"); String delegatorNameToUse = null; // get delegator to use from the container configuration if (delegatorNameProp == null || delegatorNameProp.value == null || delegatorNameProp.value.length() == 0) { throw new ContainerException("Invalid delegator-name defined in container configuration"); } else { delegatorNameToUse = delegatorNameProp.value; } // get the delegator GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorNameToUse); if (delegator == null) { throw new ContainerException("Invalid delegator name: " + delegatorNameToUse); } // get output path to use from the container configuration if (outputPathProp == null || outputPathProp.value == null || outputPathProp.value.length() == 0) { throw new ContainerException("Invalid output-name defined in container configuration"); } else { outputPath = outputPathProp.value; } // check the output path File outputDir = new File(outputPath); if (!outputDir.canWrite()) { throw new ContainerException("Unable to use output path: [" + outputPath + "], it is not writable"); } // get the template file to use from the container configuration if (templateProp == null || templateProp.value == null || templateProp.value.length() == 0) { throw new ContainerException("Invalid template defined in container configuration"); } else { template = templateProp.value; } // check the template file File templateFile = new File(template); if (!templateFile.canRead()) { throw new ContainerException("Unable to read template file: [" + template + "]"); } // get the primay key template file to use from the container configuration if (pkTemplateProp == null || pkTemplateProp.value == null || pkTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk template defined in container configuration"); } else { pkTemplate = pkTemplateProp.value; } // check the pk template file File pkTemplateFile = new File(pkTemplate); if (!pkTemplateFile.canRead()) { throw new ContainerException("Unable to read pk template file: [" + pkTemplate + "]"); } // get the primay key template file to use from the container configuration if (hibernateCfgTemplateProp == null || hibernateCfgTemplateProp.value == null || hibernateCfgTemplateProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg template defined in container configuration"); } else { hibernateCfgTemplate = hibernateCfgTemplateProp.value; } // check the pk template file File cfgTemplateFile = new File(hibernateCfgTemplate); if (!cfgTemplateFile.canRead()) { throw new ContainerException("Unable to read hibernate cfg template file: [" + hibernateCfgTemplate + "]"); } // get the primay key bridge template file to use from the container configuration if (pkBridgeTemplateProp == null || pkBridgeTemplateProp.value == null || pkBridgeTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk bridge template defined in container configuration"); } else { pkBridgeTemplate = pkBridgeTemplateProp.value; } // check the pk template file File pkBridgeTemplateFile = new File(pkBridgeTemplate); if (!pkBridgeTemplateFile.canRead()) { throw new ContainerException("Unable to read pk bridge template file: [" + pkBridgeTemplate + "]"); } // get entities list ModelReader modelReader = delegator.getModelReader(); Collection<String> entities = null; try { entities = modelReader.getEntityNames(); } catch (GenericEntityException e) { Debug.logError(e, "Error getting the entities list from delegator " + delegatorNameToUse, MODULE); } // record errors for summary List<String> errorEntities = new LinkedList<String>(); // record view entities List<String> viewEntities = new LinkedList<String>(); int totalGeneratedClasses = 0; if (entities != null && entities.size() > 0) { Debug.logImportant("=-=-=-=-=-=-= Generating the POJO entities ...", MODULE); for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); if (modelEntity != null && modelEntity instanceof ModelViewEntity) { viewEntities.add(entityName); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } List<String> needIndexEntities = new LinkedList<String>(); for (String entityName : entities) { //retrieve entityName if (entitySearchProperties.containsKey(entityName)) { if (entitySearchProperties.getProperty(entityName).equals("index")) { needIndexEntities.add(entityName); } } } for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } if (modelEntity == null) { errorEntities.add(entityName); Debug.logError("Error getting the entity model from delegator " + delegatorNameToUse + " and entity " + entityName, MODULE); continue; } // could be an object, but is just a Map for simplicity Map<String, Object> entityInfo = new HashMap<String, Object>(); // entity columns what used in entity field List<String> entityColumns = new ArrayList<String>(); boolean isView = false; // justify the entity whether need index or not boolean isNeedIndex = needIndexEntities.contains(entityName); if ((modelEntity instanceof ModelViewEntity)) { isView = true; // the view entity cannot index isNeedIndex = false; } // get name of the entity entityName = modelEntity.getEntityName(); entityInfo.put("name", entityName); entityInfo.put("tableName", modelEntity.getPlainTableName()); entityInfo.put("isView", isView); entityInfo.put("isNeedIndex", isNeedIndex); entityInfo.put("needIndexEntities", needIndexEntities); entityInfo.put("resourceName", modelEntity.getDefaultResourceName()); entityInfo.put("primaryKeys", modelEntity.getPkFieldNames()); entityInfo.put("viewEntities" , viewEntities); // get all the fields of the entity which become members of the class List<String> fieldNames = modelEntity.getAllFieldNames(); entityInfo.put("fields", fieldNames); //get all the columns of the entity Map<String, String> columnNames = new TreeMap<String, String>(); for (String fieldName : fieldNames) { String columnName = modelEntity.getColNameOrAlias(fieldName); columnNames.put(fieldName, columnName); entityColumns.add(columnName); } entityInfo.put("columnNames", columnNames); // distinct types for the import section Set<String> types = new TreeSet<String>(); // a type for each field during declarations Map<String, String> fieldTypes = new TreeMap<String, String>(); // indicate declarations Map<String, String> indexWeights = new TreeMap<String, String>(); Map<String, String> tokenTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getMethodNames = new TreeMap<String, String>(); Map<String, String> setMethodNames = new TreeMap<String, String>(); Map<String, List<String>> validatorMaps = new TreeMap<String, List<String>>(); // now go through all the fields boolean hasError = false; for (String fieldName : fieldNames) { // use the model field to figure out the Java type ModelField modelField = modelEntity.getField(fieldName); String type = null; try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. ModelFieldType fieldType = delegator.getEntityFieldType(modelEntity, modelField.getType()); if (fieldType == null) { throw new GenericEntityException("No helper defined for entity " + entityName + ". Check if this entity has an entitygroup.xml definition"); } type = ObjectType.loadClass(fieldType.getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + fieldName + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } // make all Object field to byte[] if ("java.lang.Object".equals(type)) { type = "byte[]"; } else { types.add(type); } // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } fieldTypes.put(fieldName, shortType); // if entitysearch.properties contain the field, then add boost annotation to set index weight String indexFieldKey = entityName + "." + fieldName; if (entitySearchProperties.containsKey(indexFieldKey)) { String[] indexValue = entitySearchProperties.getProperty(indexFieldKey).split(","); String weight = indexValue[0]; String tokenType = indexValue.length > 1 ? indexValue[1] : "TOKENIZED"; indexWeights.put(fieldName, weight); tokenTypes.put(fieldName, tokenType); } // accessor method names try { getMethodNames.put(fieldName, getterName(fieldName)); setMethodNames.put(fieldName, setterName(fieldName)); } catch (IllegalArgumentException e) { errorEntities.add(entityName); Debug.logError(e, MODULE); hasError = true; break; } if (modelField.getValidatorsSize() > 0) { List<String> validators = new ArrayList<String>(); for (int i = 0; i < modelField.getValidatorsSize(); i++) { String validator = modelField.getValidator(i); validators.add(validator); } validatorMaps.put(fieldName, validators); } } if (hasError) { continue; } // get the relations List<Map<String, String>> relations = new ArrayList<Map<String, String>>(); Iterator<ModelRelation> relationsIter = modelEntity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); Map<String, String> relationInfo = new TreeMap<String, String>(); relationInfo.put("entityName", modelRelation.getRelEntityName()); // the string to put in the getRelated() method, title is "" if null relationInfo.put("relationName", modelRelation.getTitle() + modelRelation.getRelEntityName()); // the names are pluralized for relation of type many String accessorName = modelRelation.getTitle() + modelRelation.getRelEntityName(); // justify if need create hibernate mapping annotation String isNeedMapping = "Y"; if ("many".equals(modelRelation.getType())) { relationInfo.put("type", "many"); try { accessorName = Noun.pluralOf(accessorName, Locale.ENGLISH); } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the plural of " + accessorName + ", falling back to " + accessorName + "s.", MODULE); accessorName = accessorName + "s"; } // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(entityName)) { isNeedMapping = "N"; } } else { // we do not care about the difference between one and one-nofk types, because we can use one-to-one to cascade relationInfo.put("type", "one"); // mark isOneToOne field for Entity ftl, this is useful for hibernate search feature try { String joinField = modelRelation.getKeyMap(0).getFieldName(); ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); if (modelRelation.isAutoRelation() && refEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().size() == 1 && (refEntity.getPkFieldNames().contains(modelEntity.getPkFieldNames()) || modelEntity.getPkFieldNames().contains(joinField))) { relationInfo.put("isOneToOne", "Y"); } else { relationInfo.put("isOneToOne", "N"); // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(modelRelation.getRelEntityName())) { isNeedMapping = "N"; } } } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the relative Entity " + modelRelation.getRelEntityName() + ".", MODULE); accessorName = accessorName + "s"; } } // check if the accessor conflicts with an already defined field String fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); if (fieldNames.contains(fieldName)) { String oldFieldName = fieldName; accessorName = "Related" + accessorName; fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); Debug.logWarning("For entity " + entityName + ", field " + oldFieldName + " already defined, using " + fieldName + " instead.", MODULE); } String fkName = modelRelation.getFkName(); relationInfo.put("accessorName", accessorName); relationInfo.put("fieldName", fieldName); relationInfo.put("fkName", fkName); relationInfo.put("isNeedMapping", isNeedMapping); if (modelRelation.getKeyMapsSize() == 1) { //relation child Entity field String joinField = ""; //relation parent Entity field String mappedByFieldId = ""; String columnName = ""; if ("many".equals(modelRelation.getType())) { joinField = modelRelation.getKeyMap(0).getRelFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getFieldName(); try { // get relative column name ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); columnName = refEntity.getColNameOrAlias(joinField); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { joinField = modelRelation.getKeyMap(0).getFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getRelFieldName(); // get joinField column columnName = modelEntity.getColNameOrAlias(joinField); } //adjust this column if use for other relation, if used we should mapped with insert="false" update="false" if (!entityColumns.contains(columnName)) { entityColumns.add(columnName); relationInfo.put("isRepeated", "N"); } else { relationInfo.put("isRepeated", "Y"); } relationInfo.put("joinColumn", columnName); //if this property is collection, and have only one primary key, and find it in child property // this is useful for hibernate's cascading feature if ("many".equals(modelRelation.getType()) && modelEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().contains(mappedByFieldId)) { try { ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); // manyToOne field String refField = ""; Iterator it = refEntity.getRelationsIterator(); while (it.hasNext()) { ModelRelation relation = (ModelRelation) it.next(); //if relation map modelRelation if (relation.getRelEntityName().equals(entityName) && relation.getKeyMapsSize() == 1 && relation.getKeyMap(0).getFieldName().equals(joinField)) { //get access name String aName = relation.getTitle() + relation.getRelEntityName(); //get ref field name refField = aName.substring(0, 1).toLowerCase() + aName.substring(1); break; } } if (refEntity.getPkFieldNames().contains(joinField) && !refField.equals("")) { // if this collection should be a cascade collection property relationInfo.put("itemName", itemName(fieldName)); relationInfo.put("refField", refField); //put add item method of collection relationInfo.put("addMethodName", addName(fieldName)); //put remove item method of collection relationInfo.put("removeMethodName", removeName(fieldName)); //put clear item method of collection relationInfo.put("clearMethodName", clearName(fieldName)); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } } relations.add(relationInfo); } entityInfo.put("relations", relations); entityInfo.put("types", types); entityInfo.put("fieldTypes", fieldTypes); entityInfo.put("getMethodNames", getMethodNames); entityInfo.put("setMethodNames", setMethodNames); entityInfo.put("validatorMaps", validatorMaps); entityInfo.put("indexWeights", indexWeights); entityInfo.put("tokenTypes", tokenTypes); // map view-entity to @NamedNativeQuery if (isView) { //pk fields of the first entity as view-entity pk List<String> viewEntityPks = new LinkedList<String>(); StringBuffer query = new StringBuffer(); query.append("SELECT "); // field <-> column alias mapping Map<String, String> fieldMapAlias = new TreeMap<String, String>(); // field <-> column name mapping Map<String, String> fieldMapColumns = new TreeMap<String, String>(); List<String> relationAlias = new LinkedList<String>(); ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity; Iterator aliasIter = modelViewEntity.getAliasesIterator(); // iterate all fields, construct select sentence while (aliasIter.hasNext()) { ModelAlias alias = (ModelAlias) aliasIter.next(); String columnName = ModelUtil.javaNameToDbName(alias.getField()); if (fieldMapAlias.size() > 0) { query.append(","); } //iterator field, such as "P.PARTY_ID \"partyId\" query.append(alias.getEntityAlias() + "." + columnName + " AS \\\"" + alias.getField() + "\\\""); String colAlias = alias.getColAlias(); String field = ModelUtil.dbNameToVarName(alias.getColAlias()); // put field-colAlias mapping fieldMapAlias.put(field, colAlias); // put field-column mapping fieldMapColumns.put(field, alias.getEntityAlias() + "." + columnName); } // iterate all entities, construct from sentence for (int i = 0; i < modelViewEntity.getAllModelMemberEntities().size(); i++) { ModelMemberEntity modelMemberEntity = (ModelMemberEntity) modelViewEntity.getAllModelMemberEntities().get(i); String tableName = ModelUtil.javaNameToDbName(modelMemberEntity.getEntityName()); String tableAlias = modelMemberEntity.getEntityAlias(); relationAlias.add(tableAlias); if (i == 0) { // main table query.append(" FROM " + tableName + " " + tableAlias); // get all the pk fields of the first entity which become members of the class try { ModelEntity firstEntity = modelReader.getModelEntity(modelMemberEntity.getEntityName()); Iterator it = firstEntity.getPksIterator(); while (it.hasNext()) { ModelField field = (ModelField) it.next(); //just need one pk, else secondary pk would be null if (fieldMapAlias.containsKey(field.getName()) && viewEntityPks.size()==0) { viewEntityPks.add(field.getName()); } } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { // join table Iterator viewLinkIter = modelViewEntity.getViewLinksIterator(); while (viewLinkIter.hasNext()) { ModelViewLink modelViewLink = (ModelViewLink) viewLinkIter.next(); if (relationAlias.contains(modelViewLink.getEntityAlias()) && relationAlias.contains(modelViewLink.getRelEntityAlias()) && (tableAlias.equals(modelViewLink.getEntityAlias()) || tableAlias.equals(modelViewLink.getRelEntityAlias())) ) { // adjust if left join or inner join String joinType = modelViewLink.isRelOptional() ? " LEFT JOIN " : " INNER JOIN "; query.append(joinType + tableName + " " + tableAlias); for (int k = 0; k < modelViewLink.getKeyMapsSize(); k++) { ModelKeyMap modelKeyMap = modelViewLink.getKeyMap(k); //get join conditions String joinCondition = modelViewLink.getEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getFieldName()) + " = " + modelViewLink.getRelEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getRelFieldName()); if (k == 0) { // if it is first join condition query.append(" ON " + joinCondition); } else { // if it isn't first join condition query.append(" AND " + joinCondition); } } } } } } // if no pk for this viewEntity, then give a random field, because hibernate annotation need at least one pk filed. if (viewEntityPks.size() == 0) { viewEntityPks.add(fieldNames.get(0)); } entityInfo.put("query", query.toString()); entityInfo.put("fieldMapAlias", fieldMapAlias); entityInfo.put("fieldMapColumns", fieldMapColumns); entityInfo.put("viewEntityPks", viewEntityPks); } // render it as FTL Writer writer = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(template, entityInfo, writer); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file File file = new File(outputPath + entityName + fileExtension); try { FileUtils.writeStringToFile(file, writer.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + fileExtension, MODULE); errorEntities.add(entityName); break; } // pk class info Map<String, Object> pkInfo = null; if (!isView && modelEntity.getPkFieldNames().size() > 1) { //if entity has more than one pk pkInfo = new TreeMap<String, Object>(); // get all the pk fields of the entity which become members of the class List<String> primaryKeys = modelEntity.getPkFieldNames(); // a type for each pk during declarations Map<String, String> pkTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getPkMethodNames = new TreeMap<String, String>(); Map<String, String> setPkMethodNames = new TreeMap<String, String>(); // distinct types for the import section Set<String> pkFieldTypes = new TreeSet<String>(); Iterator<ModelField> pksIter = modelEntity.getPksIterator(); while (pksIter.hasNext()) { String type = null; ModelField modelField = pksIter.next(); getPkMethodNames.put(modelField.getName(), getterName(modelField.getName())); setPkMethodNames.put(modelField.getName(), setterName(modelField.getName())); try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. type = ObjectType.loadClass(delegator.getEntityFieldType(modelEntity, modelField.getType()).getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + modelField.getName() + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } pkFieldTypes.add(type); // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } pkTypes.put(modelField.getName(), shortType); } pkInfo.put("pkName", modelEntity.getEntityName() + "Pk"); pkInfo.put("entityName", modelEntity.getEntityName()); pkInfo.put("primaryKeys", primaryKeys); pkInfo.put("pkTypes", pkTypes); pkInfo.put("getPkMethodNames", getPkMethodNames); pkInfo.put("setPkMethodNames", setPkMethodNames); pkInfo.put("pkFieldTypes", pkFieldTypes); pkInfo.put("columnNames", columnNames); } if (pkInfo != null) { // render pk class as FTL Writer pkWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkTemplate, pkInfo, pkWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkFile = new File(outputPath + entityName + "Pk" + fileExtension); try { FileUtils.writeStringToFile(pkFile, pkWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + "Pk" + fileExtension, MODULE); errorEntities.add(entityName); break; } // render pk bridge class as FTL Writer pkBridgeWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkBridgeTemplate, pkInfo, pkBridgeWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkBridgeFile = new File(outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension); try { FileUtils.writeStringToFile(pkBridgeFile, pkBridgeWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension, MODULE); errorEntities.add(entityName); break; } } // increment counter totalGeneratedClasses++; } // render hibernate.cfg.xml by FTL Writer cfgWriter = new StringWriter(); Map<String, Object> cfgInfo = new HashMap<String, Object>(); cfgInfo.put("entities", entities); try { FreeMarkerWorker.renderTemplateAtLocation(hibernateCfgTemplate, cfgInfo, cfgWriter); } catch (MalformedURLException e1) { Debug.logError(e1, MODULE); } catch (TemplateException e1) { Debug.logError(e1, MODULE); } catch (IOException e1) { Debug.logError(e1, MODULE); } // get hibernate.cfg.xml output path to use from the container configuration String hibernateCfgPath = null; if (hibernateCfgProp == null || hibernateCfgProp.value == null || hibernateCfgProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg path defined in container configuration"); } else { hibernateCfgPath = hibernateCfgProp.value; } // write it as a hibernate.cfg.xml File hibernateFile = new File(hibernateCfgPath); try { FileUtils.writeStringToFile(hibernateFile, cfgWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + hibernateCfgPath, MODULE); } } else { Debug.logImportant("=-=-=-=-=-=-= No entity found.", MODULE); } // error summary if (errorEntities.size() > 0) { Debug.logImportant("The following entities could not be generated:", MODULE); for (String name : errorEntities) { Debug.logImportant(name, MODULE); } } Debug.logImportant("=-=-=-=-=-=-= Finished the POJO entities generation with " + totalGeneratedClasses + " classes generated.", MODULE); if (errorEntities.size() > 0) { return false; } return true; }
public boolean start() throws ContainerException { ContainerConfig.Container cfg = ContainerConfig.getContainer(containerName, configFile); ContainerConfig.Container.Property delegatorNameProp = cfg.getProperty("delegator-name"); ContainerConfig.Container.Property outputPathProp = cfg.getProperty("output-path"); ContainerConfig.Container.Property templateProp = cfg.getProperty("template"); ContainerConfig.Container.Property pkTemplateProp = cfg.getProperty("pkTemplate"); ContainerConfig.Container.Property pkBridgeTemplateProp = cfg.getProperty("pkBridgeTemplate"); ContainerConfig.Container.Property hibernateCfgTemplateProp = cfg.getProperty("hibernateCfgTemplate"); ContainerConfig.Container.Property hibernateCfgProp = cfg.getProperty("hibernateCfgPath"); Properties entitySearchProperties = UtilProperties.getProperties("entitysearch.properties"); String delegatorNameToUse = null; // get delegator to use from the container configuration if (delegatorNameProp == null || delegatorNameProp.value == null || delegatorNameProp.value.length() == 0) { throw new ContainerException("Invalid delegator-name defined in container configuration"); } else { delegatorNameToUse = delegatorNameProp.value; } // get the delegator GenericDelegator delegator = GenericDelegator.getGenericDelegator(delegatorNameToUse); if (delegator == null) { throw new ContainerException("Invalid delegator name: " + delegatorNameToUse); } // get output path to use from the container configuration if (outputPathProp == null || outputPathProp.value == null || outputPathProp.value.length() == 0) { throw new ContainerException("Invalid output-name defined in container configuration"); } else { outputPath = outputPathProp.value; } // check the output path File outputDir = new File(outputPath); if (!outputDir.canWrite()) { throw new ContainerException("Unable to use output path: [" + outputPath + "], it is not writable"); } // get the template file to use from the container configuration if (templateProp == null || templateProp.value == null || templateProp.value.length() == 0) { throw new ContainerException("Invalid template defined in container configuration"); } else { template = templateProp.value; } // check the template file File templateFile = new File(template); if (!templateFile.canRead()) { throw new ContainerException("Unable to read template file: [" + template + "]"); } // get the primay key template file to use from the container configuration if (pkTemplateProp == null || pkTemplateProp.value == null || pkTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk template defined in container configuration"); } else { pkTemplate = pkTemplateProp.value; } // check the pk template file File pkTemplateFile = new File(pkTemplate); if (!pkTemplateFile.canRead()) { throw new ContainerException("Unable to read pk template file: [" + pkTemplate + "]"); } // get the primay key template file to use from the container configuration if (hibernateCfgTemplateProp == null || hibernateCfgTemplateProp.value == null || hibernateCfgTemplateProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg template defined in container configuration"); } else { hibernateCfgTemplate = hibernateCfgTemplateProp.value; } // check the pk template file File cfgTemplateFile = new File(hibernateCfgTemplate); if (!cfgTemplateFile.canRead()) { throw new ContainerException("Unable to read hibernate cfg template file: [" + hibernateCfgTemplate + "]"); } // get the primay key bridge template file to use from the container configuration if (pkBridgeTemplateProp == null || pkBridgeTemplateProp.value == null || pkBridgeTemplateProp.value.length() == 0) { throw new ContainerException("Invalid pk bridge template defined in container configuration"); } else { pkBridgeTemplate = pkBridgeTemplateProp.value; } // check the pk template file File pkBridgeTemplateFile = new File(pkBridgeTemplate); if (!pkBridgeTemplateFile.canRead()) { throw new ContainerException("Unable to read pk bridge template file: [" + pkBridgeTemplate + "]"); } // get entities list ModelReader modelReader = delegator.getModelReader(); Collection<String> entities = null; try { entities = modelReader.getEntityNames(); } catch (GenericEntityException e) { Debug.logError(e, "Error getting the entities list from delegator " + delegatorNameToUse, MODULE); } // record errors for summary List<String> errorEntities = new LinkedList<String>(); // record view entities List<String> viewEntities = new LinkedList<String>(); int totalGeneratedClasses = 0; if (entities != null && entities.size() > 0) { Debug.logImportant("=-=-=-=-=-=-= Generating the POJO entities ...", MODULE); for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); if (modelEntity != null && modelEntity instanceof ModelViewEntity) { viewEntities.add(entityName); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } List<String> needIndexEntities = new LinkedList<String>(); for (String entityName : entities) { //retrieve entityName if (entitySearchProperties.containsKey(entityName)) { if (entitySearchProperties.getProperty(entityName).equals("index")) { needIndexEntities.add(entityName); } } } for (String entityName : entities) { ModelEntity modelEntity = null; try { modelEntity = modelReader.getModelEntity(entityName); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } if (modelEntity == null) { errorEntities.add(entityName); Debug.logError("Error getting the entity model from delegator " + delegatorNameToUse + " and entity " + entityName, MODULE); continue; } // could be an object, but is just a Map for simplicity Map<String, Object> entityInfo = new HashMap<String, Object>(); // entity columns what used in entity field List<String> entityColumns = new ArrayList<String>(); boolean isView = false; // justify the entity whether need index or not boolean isNeedIndex = needIndexEntities.contains(entityName); if ((modelEntity instanceof ModelViewEntity)) { isView = true; // the view entity cannot index isNeedIndex = false; } // get name of the entity entityName = modelEntity.getEntityName(); entityInfo.put("name", entityName); entityInfo.put("tableName", modelEntity.getPlainTableName()); entityInfo.put("isView", isView); entityInfo.put("isNeedIndex", isNeedIndex); entityInfo.put("needIndexEntities", needIndexEntities); entityInfo.put("resourceName", modelEntity.getDefaultResourceName()); entityInfo.put("primaryKeys", modelEntity.getPkFieldNames()); entityInfo.put("viewEntities" , viewEntities); // get all the fields of the entity which become members of the class List<String> fieldNames = modelEntity.getAllFieldNames(); entityInfo.put("fields", fieldNames); //get all the columns of the entity Map<String, String> columnNames = new TreeMap<String, String>(); for (String fieldName : fieldNames) { String columnName = modelEntity.getColNameOrAlias(fieldName); columnNames.put(fieldName, columnName); entityColumns.add(columnName); } entityInfo.put("columnNames", columnNames); // distinct types for the import section Set<String> types = new TreeSet<String>(); // a type for each field during declarations Map<String, String> fieldTypes = new TreeMap<String, String>(); // indicate declarations Map<String, String> indexWeights = new TreeMap<String, String>(); Map<String, String> tokenTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getMethodNames = new TreeMap<String, String>(); Map<String, String> setMethodNames = new TreeMap<String, String>(); Map<String, List<String>> validatorMaps = new TreeMap<String, List<String>>(); // now go through all the fields boolean hasError = false; for (String fieldName : fieldNames) { // use the model field to figure out the Java type ModelField modelField = modelEntity.getField(fieldName); String type = null; try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. ModelFieldType fieldType = delegator.getEntityFieldType(modelEntity, modelField.getType()); if (fieldType == null) { throw new GenericEntityException("No helper defined for entity " + entityName + ". Check if this entity has an entitygroup.xml definition"); } type = ObjectType.loadClass(fieldType.getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + fieldName + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } // make all Object field to byte[] if ("java.lang.Object".equals(type)) { type = "byte[]"; } else { types.add(type); } // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } fieldTypes.put(fieldName, shortType); // if entitysearch.properties contain the field, then add boost annotation to set index weight String indexFieldKey = entityName + "." + fieldName; if (entitySearchProperties.containsKey(indexFieldKey)) { String[] indexValue = entitySearchProperties.getProperty(indexFieldKey).split(","); String weight = indexValue[0]; String tokenType = indexValue.length > 1 ? indexValue[1] : "TOKENIZED"; indexWeights.put(fieldName, weight); tokenTypes.put(fieldName, tokenType); } // accessor method names try { getMethodNames.put(fieldName, getterName(fieldName)); setMethodNames.put(fieldName, setterName(fieldName)); } catch (IllegalArgumentException e) { errorEntities.add(entityName); Debug.logError(e, MODULE); hasError = true; break; } if (modelField.getValidatorsSize() > 0) { List<String> validators = new ArrayList<String>(); for (int i = 0; i < modelField.getValidatorsSize(); i++) { String validator = modelField.getValidator(i); validators.add(validator); } validatorMaps.put(fieldName, validators); } } if (hasError) { continue; } // get the relations List<Map<String, String>> relations = new ArrayList<Map<String, String>>(); Iterator<ModelRelation> relationsIter = modelEntity.getRelationsIterator(); while (relationsIter.hasNext()) { ModelRelation modelRelation = relationsIter.next(); Map<String, String> relationInfo = new TreeMap<String, String>(); relationInfo.put("entityName", modelRelation.getRelEntityName()); // the string to put in the getRelated() method, title is "" if null relationInfo.put("relationName", modelRelation.getTitle() + modelRelation.getRelEntityName()); // the names are pluralized for relation of type many String accessorName = modelRelation.getTitle() + modelRelation.getRelEntityName(); // title may have white spaces, remove them to use as an attribute in the java class accessorName = accessorName.replaceAll(" ", ""); // justify if need create hibernate mapping annotation String isNeedMapping = "Y"; if ("many".equals(modelRelation.getType())) { relationInfo.put("type", "many"); try { accessorName = Noun.pluralOf(accessorName, Locale.ENGLISH); } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the plural of " + accessorName + ", falling back to " + accessorName + "s.", MODULE); accessorName = accessorName + "s"; } // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(entityName)) { isNeedMapping = "N"; } } else { // we do not care about the difference between one and one-nofk types, because we can use one-to-one to cascade relationInfo.put("type", "one"); // mark isOneToOne field for Entity ftl, this is useful for hibernate search feature try { String joinField = modelRelation.getKeyMap(0).getFieldName(); ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); if (modelRelation.isAutoRelation() && refEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().size() == 1 && (refEntity.getPkFieldNames().contains(modelEntity.getPkFieldNames()) || modelEntity.getPkFieldNames().contains(joinField))) { relationInfo.put("isOneToOne", "Y"); } else { relationInfo.put("isOneToOne", "N"); // if the relation class is extendClass, such as PartyGroup and not oneToOne relation, then don't mapping this relation for hibernate if (extendClassNames.contains(modelRelation.getRelEntityName())) { isNeedMapping = "N"; } } } catch (Exception e) { Debug.logWarning("For entity " + entityName + ", could not get the relative Entity " + modelRelation.getRelEntityName() + ".", MODULE); accessorName = accessorName + "s"; } } // check if the accessor conflicts with an already defined field String fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); if (fieldNames.contains(fieldName)) { String oldFieldName = fieldName; accessorName = "Related" + accessorName; fieldName = accessorName.substring(0, 1).toLowerCase() + accessorName.substring(1); Debug.logWarning("For entity " + entityName + ", field " + oldFieldName + " already defined, using " + fieldName + " instead.", MODULE); } String fkName = modelRelation.getFkName(); relationInfo.put("accessorName", accessorName); relationInfo.put("fieldName", fieldName); relationInfo.put("fkName", fkName); relationInfo.put("isNeedMapping", isNeedMapping); if (modelRelation.getKeyMapsSize() == 1) { //relation child Entity field String joinField = ""; //relation parent Entity field String mappedByFieldId = ""; String columnName = ""; if ("many".equals(modelRelation.getType())) { joinField = modelRelation.getKeyMap(0).getRelFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getFieldName(); try { // get relative column name ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); columnName = refEntity.getColNameOrAlias(joinField); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { joinField = modelRelation.getKeyMap(0).getFieldName(); mappedByFieldId = modelRelation.getKeyMap(0).getRelFieldName(); // get joinField column columnName = modelEntity.getColNameOrAlias(joinField); } //adjust this column if use for other relation, if used we should mapped with insert="false" update="false" if (!entityColumns.contains(columnName)) { entityColumns.add(columnName); relationInfo.put("isRepeated", "N"); } else { relationInfo.put("isRepeated", "Y"); } relationInfo.put("joinColumn", columnName); //if this property is collection, and have only one primary key, and find it in child property // this is useful for hibernate's cascading feature if ("many".equals(modelRelation.getType()) && modelEntity.getPkFieldNames().size() == 1 && modelEntity.getPkFieldNames().contains(mappedByFieldId)) { try { ModelEntity refEntity = modelReader.getModelEntity(modelRelation.getRelEntityName()); // manyToOne field String refField = ""; Iterator it = refEntity.getRelationsIterator(); while (it.hasNext()) { ModelRelation relation = (ModelRelation) it.next(); //if relation map modelRelation if (relation.getRelEntityName().equals(entityName) && relation.getKeyMapsSize() == 1 && relation.getKeyMap(0).getFieldName().equals(joinField)) { //get access name String aName = relation.getTitle() + relation.getRelEntityName(); //get ref field name refField = aName.substring(0, 1).toLowerCase() + aName.substring(1); break; } } if (refEntity.getPkFieldNames().contains(joinField) && !refField.equals("")) { // if this collection should be a cascade collection property relationInfo.put("itemName", itemName(fieldName)); relationInfo.put("refField", refField); //put add item method of collection relationInfo.put("addMethodName", addName(fieldName)); //put remove item method of collection relationInfo.put("removeMethodName", removeName(fieldName)); //put clear item method of collection relationInfo.put("clearMethodName", clearName(fieldName)); } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } } relations.add(relationInfo); } entityInfo.put("relations", relations); entityInfo.put("types", types); entityInfo.put("fieldTypes", fieldTypes); entityInfo.put("getMethodNames", getMethodNames); entityInfo.put("setMethodNames", setMethodNames); entityInfo.put("validatorMaps", validatorMaps); entityInfo.put("indexWeights", indexWeights); entityInfo.put("tokenTypes", tokenTypes); // map view-entity to @NamedNativeQuery if (isView) { //pk fields of the first entity as view-entity pk List<String> viewEntityPks = new LinkedList<String>(); StringBuffer query = new StringBuffer(); query.append("SELECT "); // field <-> column alias mapping Map<String, String> fieldMapAlias = new TreeMap<String, String>(); // field <-> column name mapping Map<String, String> fieldMapColumns = new TreeMap<String, String>(); List<String> relationAlias = new LinkedList<String>(); ModelViewEntity modelViewEntity = (ModelViewEntity) modelEntity; Iterator aliasIter = modelViewEntity.getAliasesIterator(); // iterate all fields, construct select sentence while (aliasIter.hasNext()) { ModelAlias alias = (ModelAlias) aliasIter.next(); String columnName = ModelUtil.javaNameToDbName(alias.getField()); if (fieldMapAlias.size() > 0) { query.append(","); } //iterator field, such as "P.PARTY_ID \"partyId\" query.append(alias.getEntityAlias() + "." + columnName + " AS \\\"" + alias.getField() + "\\\""); String colAlias = alias.getColAlias(); String field = ModelUtil.dbNameToVarName(alias.getColAlias()); // put field-colAlias mapping fieldMapAlias.put(field, colAlias); // put field-column mapping fieldMapColumns.put(field, alias.getEntityAlias() + "." + columnName); } // iterate all entities, construct from sentence for (int i = 0; i < modelViewEntity.getAllModelMemberEntities().size(); i++) { ModelMemberEntity modelMemberEntity = (ModelMemberEntity) modelViewEntity.getAllModelMemberEntities().get(i); String tableName = ModelUtil.javaNameToDbName(modelMemberEntity.getEntityName()); String tableAlias = modelMemberEntity.getEntityAlias(); relationAlias.add(tableAlias); if (i == 0) { // main table query.append(" FROM " + tableName + " " + tableAlias); // get all the pk fields of the first entity which become members of the class try { ModelEntity firstEntity = modelReader.getModelEntity(modelMemberEntity.getEntityName()); Iterator it = firstEntity.getPksIterator(); while (it.hasNext()) { ModelField field = (ModelField) it.next(); //just need one pk, else secondary pk would be null if (fieldMapAlias.containsKey(field.getName()) && viewEntityPks.size()==0) { viewEntityPks.add(field.getName()); } } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } else { // join table Iterator viewLinkIter = modelViewEntity.getViewLinksIterator(); while (viewLinkIter.hasNext()) { ModelViewLink modelViewLink = (ModelViewLink) viewLinkIter.next(); if (relationAlias.contains(modelViewLink.getEntityAlias()) && relationAlias.contains(modelViewLink.getRelEntityAlias()) && (tableAlias.equals(modelViewLink.getEntityAlias()) || tableAlias.equals(modelViewLink.getRelEntityAlias())) ) { // adjust if left join or inner join String joinType = modelViewLink.isRelOptional() ? " LEFT JOIN " : " INNER JOIN "; query.append(joinType + tableName + " " + tableAlias); for (int k = 0; k < modelViewLink.getKeyMapsSize(); k++) { ModelKeyMap modelKeyMap = modelViewLink.getKeyMap(k); //get join conditions String joinCondition = modelViewLink.getEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getFieldName()) + " = " + modelViewLink.getRelEntityAlias() + "." + ModelUtil.javaNameToDbName(modelKeyMap.getRelFieldName()); if (k == 0) { // if it is first join condition query.append(" ON " + joinCondition); } else { // if it isn't first join condition query.append(" AND " + joinCondition); } } } } } } // if no pk for this viewEntity, then give a random field, because hibernate annotation need at least one pk filed. if (viewEntityPks.size() == 0) { viewEntityPks.add(fieldNames.get(0)); } entityInfo.put("query", query.toString()); entityInfo.put("fieldMapAlias", fieldMapAlias); entityInfo.put("fieldMapColumns", fieldMapColumns); entityInfo.put("viewEntityPks", viewEntityPks); } // render it as FTL Writer writer = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(template, entityInfo, writer); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file File file = new File(outputPath + entityName + fileExtension); try { FileUtils.writeStringToFile(file, writer.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + fileExtension, MODULE); errorEntities.add(entityName); break; } // pk class info Map<String, Object> pkInfo = null; if (!isView && modelEntity.getPkFieldNames().size() > 1) { //if entity has more than one pk pkInfo = new TreeMap<String, Object>(); // get all the pk fields of the entity which become members of the class List<String> primaryKeys = modelEntity.getPkFieldNames(); // a type for each pk during declarations Map<String, String> pkTypes = new TreeMap<String, String>(); // names of the get and set methods Map<String, String> getPkMethodNames = new TreeMap<String, String>(); Map<String, String> setPkMethodNames = new TreeMap<String, String>(); // distinct types for the import section Set<String> pkFieldTypes = new TreeSet<String>(); Iterator<ModelField> pksIter = modelEntity.getPksIterator(); while (pksIter.hasNext()) { String type = null; ModelField modelField = pksIter.next(); getPkMethodNames.put(modelField.getName(), getterName(modelField.getName())); setPkMethodNames.put(modelField.getName(), setterName(modelField.getName())); try { // this converts String to java.lang.String, Timestamp to java.sql.Timestamp, etc. type = ObjectType.loadClass(delegator.getEntityFieldType(modelEntity, modelField.getType()).getJavaType()).getName(); } catch (Exception e) { Debug.logError(e, MODULE); } if (type == null) { errorEntities.add(entityName); Debug.logError("Error getting the type of the field " + modelField.getName() + " of entity " + entityName + " for delegator " + delegatorNameToUse, MODULE); hasError = true; break; } // make all Doubles BigDecimals -- in the entity model fieldtype XML files, all floating points are defined as Doubles // and there is a GenericEntity.getBigDecimal method which converts them to BigDecimal. We will make them all BigDecimals // and then use the Entity.convertToBigDecimal method if ("java.lang.Double".equals(type)) { type = "java.math.BigDecimal"; } pkFieldTypes.add(type); // this is the short type: ie, java.lang.String -> String; java.util.HashMap -> HashMap, etc. String shortType = type; int idx = type.lastIndexOf("."); if (idx > 0) { shortType = type.substring(idx + 1); } pkTypes.put(modelField.getName(), shortType); } pkInfo.put("pkName", modelEntity.getEntityName() + "Pk"); pkInfo.put("entityName", modelEntity.getEntityName()); pkInfo.put("primaryKeys", primaryKeys); pkInfo.put("pkTypes", pkTypes); pkInfo.put("getPkMethodNames", getPkMethodNames); pkInfo.put("setPkMethodNames", setPkMethodNames); pkInfo.put("pkFieldTypes", pkFieldTypes); pkInfo.put("columnNames", columnNames); } if (pkInfo != null) { // render pk class as FTL Writer pkWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkTemplate, pkInfo, pkWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkFile = new File(outputPath + entityName + "Pk" + fileExtension); try { FileUtils.writeStringToFile(pkFile, pkWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + entityName + "Pk" + fileExtension, MODULE); errorEntities.add(entityName); break; } // render pk bridge class as FTL Writer pkBridgeWriter = new StringWriter(); try { FreeMarkerWorker.renderTemplateAtLocation(pkBridgeTemplate, pkInfo, pkBridgeWriter); } catch (MalformedURLException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (TemplateException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IOException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } catch (IllegalArgumentException e) { Debug.logError(e, MODULE); errorEntities.add(entityName); break; } // write it as a Java file (PK) File pkBridgeFile = new File(outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension); try { FileUtils.writeStringToFile(pkBridgeFile, pkBridgeWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + outputPath + "/bridge/" + entityName + "PkBridge" + fileExtension, MODULE); errorEntities.add(entityName); break; } } // increment counter totalGeneratedClasses++; } // render hibernate.cfg.xml by FTL Writer cfgWriter = new StringWriter(); Map<String, Object> cfgInfo = new HashMap<String, Object>(); cfgInfo.put("entities", entities); try { FreeMarkerWorker.renderTemplateAtLocation(hibernateCfgTemplate, cfgInfo, cfgWriter); } catch (MalformedURLException e1) { Debug.logError(e1, MODULE); } catch (TemplateException e1) { Debug.logError(e1, MODULE); } catch (IOException e1) { Debug.logError(e1, MODULE); } // get hibernate.cfg.xml output path to use from the container configuration String hibernateCfgPath = null; if (hibernateCfgProp == null || hibernateCfgProp.value == null || hibernateCfgProp.value.length() == 0) { throw new ContainerException("Invalid hibernate cfg path defined in container configuration"); } else { hibernateCfgPath = hibernateCfgProp.value; } // write it as a hibernate.cfg.xml File hibernateFile = new File(hibernateCfgPath); try { FileUtils.writeStringToFile(hibernateFile, cfgWriter.toString(), "UTF-8"); } catch (IOException e) { Debug.logError(e, "Aborting, error writing file " + hibernateCfgPath, MODULE); } } else { Debug.logImportant("=-=-=-=-=-=-= No entity found.", MODULE); } // error summary if (errorEntities.size() > 0) { Debug.logImportant("The following entities could not be generated:", MODULE); for (String name : errorEntities) { Debug.logImportant(name, MODULE); } } Debug.logImportant("=-=-=-=-=-=-= Finished the POJO entities generation with " + totalGeneratedClasses + " classes generated.", MODULE); if (errorEntities.size() > 0) { return false; } return true; }
diff --git a/core/pog/src/main/java/org/overture/pog/obligation/SubTypeObligation.java b/core/pog/src/main/java/org/overture/pog/obligation/SubTypeObligation.java index a507092fd9..76bdbc499c 100644 --- a/core/pog/src/main/java/org/overture/pog/obligation/SubTypeObligation.java +++ b/core/pog/src/main/java/org/overture/pog/obligation/SubTypeObligation.java @@ -1,587 +1,587 @@ /******************************************************************************* * * Copyright (C) 2008 Fujitsu Services Ltd. * * Author: Nick Battle * * This file is part of VDMJ. * * VDMJ 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. * * VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ package org.overture.pog.obligation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.overture.ast.definitions.AExplicitFunctionDefinition; import org.overture.ast.definitions.AExplicitOperationDefinition; import org.overture.ast.definitions.AImplicitFunctionDefinition; import org.overture.ast.definitions.AImplicitOperationDefinition; import org.overture.ast.expressions.ABooleanConstExp; import org.overture.ast.expressions.ACharLiteralExp; import org.overture.ast.expressions.AGreaterEqualNumericBinaryExp; import org.overture.ast.expressions.AGreaterNumericBinaryExp; import org.overture.ast.expressions.AIsExp; import org.overture.ast.expressions.ALenUnaryExp; import org.overture.ast.expressions.ALessEqualNumericBinaryExp; import org.overture.ast.expressions.AMapEnumMapExp; import org.overture.ast.expressions.AMapletExp; import org.overture.ast.expressions.AMkTypeExp; import org.overture.ast.expressions.ANotEqualBinaryExp; import org.overture.ast.expressions.ANotYetSpecifiedExp; import org.overture.ast.expressions.ASeqEnumSeqExp; import org.overture.ast.expressions.ASetEnumSetExp; import org.overture.ast.expressions.ASetRangeSetExp; import org.overture.ast.expressions.ASubclassResponsibilityExp; import org.overture.ast.expressions.ASubseqExp; import org.overture.ast.expressions.ATupleExp; import org.overture.ast.expressions.AVariableExp; import org.overture.ast.expressions.PExp; import org.overture.ast.factory.AstFactory; import org.overture.ast.lex.LexKeywordToken; import org.overture.ast.lex.LexNameToken; import org.overture.ast.lex.VDMToken; import org.overture.ast.patterns.AIdentifierPattern; import org.overture.ast.patterns.APatternListTypePair; import org.overture.ast.patterns.ATuplePattern; import org.overture.ast.patterns.PPattern; import org.overture.ast.types.ABooleanBasicType; import org.overture.ast.types.ACharBasicType; import org.overture.ast.types.AFieldField; import org.overture.ast.types.ANamedInvariantType; import org.overture.ast.types.ANatNumericBasicType; import org.overture.ast.types.ANatOneNumericBasicType; import org.overture.ast.types.AOperationType; import org.overture.ast.types.AProductType; import org.overture.ast.types.ARecordInvariantType; import org.overture.ast.types.ASeq1SeqType; import org.overture.ast.types.ASetType; import org.overture.ast.types.AUnionType; import org.overture.ast.types.PType; import org.overture.ast.types.SBasicType; import org.overture.ast.types.SInvariantType; import org.overture.ast.types.SMapType; import org.overture.ast.types.SNumericBasicType; import org.overture.ast.types.SSeqType; import org.overture.ast.util.PTypeSet; import org.overture.pog.pub.IPOContextStack; import org.overture.pog.pub.POType; import org.overture.typechecker.TypeComparator; import org.overture.typechecker.assistant.pattern.PPatternAssistantTC; import org.overture.typechecker.assistant.type.PTypeAssistantTC; import org.overture.typechecker.assistant.type.SNumericBasicTypeAssistantTC; public class SubTypeObligation extends ProofObligation { private static final long serialVersionUID = 1108478780469068741L; public SubTypeObligation(PExp exp, PType etype, PType atype, IPOContextStack ctxt) { super(exp, POType.SUB_TYPE, ctxt); // valuetree.setContext(ctxt.getContextNodeList()); valuetree.setPredicate(ctxt.getPredWithContext(oneType(false, exp.clone(), etype.clone(), atype.clone()))); } public SubTypeObligation(AExplicitFunctionDefinition func, PType etype, PType atype, IPOContextStack ctxt) { super(func, POType.SUB_TYPE, ctxt); PExp body = null; if (func.getBody() instanceof ANotYetSpecifiedExp || func.getBody() instanceof ASubclassResponsibilityExp) { // We have to say "f(a)" because we have no body PExp root = AstFactory.newAVariableExp(func.getName()); List<PExp> args = new ArrayList<PExp>(); for (PPattern p : func.getParamPatternList().get(0)) { args.add(PPatternAssistantTC.getMatchingExpression(p)); } body = AstFactory.newAApplyExp(root, args); } else { body = func.getBody().clone(); } // valuetree.setContext(ctxt.getContextNodeList()); valuetree.setPredicate(ctxt.getPredWithContext(oneType(false, body, etype.clone(), atype.clone()))); } public SubTypeObligation(AImplicitFunctionDefinition func, PType etype, PType atype, IPOContextStack ctxt) { super(func, POType.SUB_TYPE, ctxt); PExp body = null; if (func.getBody() instanceof ANotYetSpecifiedExp || func.getBody() instanceof ASubclassResponsibilityExp) { // We have to say "f(a)" because we have no body PExp root = AstFactory.newAVariableExp(func.getName()); List<PExp> args = new ArrayList<PExp>(); for (APatternListTypePair pltp : func.getParamPatterns()) { for (PPattern p : pltp.getPatterns()) { args.add(PPatternAssistantTC.getMatchingExpression(p)); } } body = AstFactory.newAApplyExp(root, args); } else { body = func.getBody().clone(); } // valuetree.setContext(ctxt.getContextNodeList()); valuetree.setPredicate(ctxt.getPredWithContext(oneType(false, body, etype.clone(), atype.clone()))); } public SubTypeObligation(AExplicitOperationDefinition def, PType actualResult, IPOContextStack ctxt) { super(def, POType.SUB_TYPE, ctxt); AVariableExp result = AstFactory.newAVariableExp( new LexNameToken(def.getName().getModule(), "RESULT", def.getLocation())); // valuetree.setContext(ctxt.getContextNodeList()); valuetree.setPredicate(ctxt.getPredWithContext( oneType(false, result, ((AOperationType) def.getType()).getResult().clone(), actualResult.clone()))); } public SubTypeObligation(AImplicitOperationDefinition def, PType actualResult, IPOContextStack ctxt) { super(def, POType.SUB_TYPE, ctxt); PExp result = null; if (def.getResult().getPattern() instanceof AIdentifierPattern) { AIdentifierPattern ip = (AIdentifierPattern) def.getResult().getPattern(); result = AstFactory.newAVariableExp(ip.getName()); } else { ATuplePattern tp = (ATuplePattern) def.getResult().getPattern(); List<PExp> args = new ArrayList<PExp>(); for (PPattern p : tp.getPlist()) { AIdentifierPattern ip = (AIdentifierPattern) p; args.add(AstFactory.newAVariableExp(ip.getName())); } result = AstFactory.newATupleExp(def.getLocation(), args); } // valuetree.setContext(ctxt.getContextNodeList()); valuetree.setPredicate(ctxt.getPredWithContext( oneType(false, result, ((AOperationType) def.getType()).getResult().clone(), actualResult.clone()))); } private PExp oneType(boolean rec, PExp exp, PType etype, PType atype) { if (atype != null && rec) { if (TypeComparator.isSubType(atype, etype)) { return null; // Means a sub-comparison is OK without PO checks } } PExp po = null; etype = PTypeAssistantTC.deBracket(etype); if (etype instanceof AUnionType) { AUnionType ut = (AUnionType) etype; PTypeSet possibles = new PTypeSet(); for (PType pos : ut.getTypes()) { if (atype == null || TypeComparator.compatible(pos, atype)) { possibles.add(pos); } } po = null; for (PType poss : possibles) { PExp s = oneType(true, exp, poss, null); PExp e = addIs(exp, poss); if (s != null && !(s instanceof AIsExp)) { e = makeAnd(e, s); } po = makeOr(po, e); } } else if (etype instanceof SInvariantType) { SInvariantType et = (SInvariantType) etype; po = null; if (et.getInvDef() != null) { AVariableExp root = getVarExp(et.getInvDef().getName()); // This needs to be put back if/when we change the inv_R signature to take // the record fields as arguments, rather than one R value. // // if (exp instanceof MkTypeExpression) // { // MkTypeExpression mk = (MkTypeExpression)exp; // sb.append(Utils.listToString(mk.args)); // } // else // { // ab.append(exp); // } po = getApplyExp(root, exp); } if (etype instanceof ANamedInvariantType) { ANamedInvariantType nt = (ANamedInvariantType) etype; if (atype instanceof ANamedInvariantType) { atype = ((ANamedInvariantType) atype).getType(); } else { atype = null; } PExp s = oneType(true, exp, nt.getType(), atype); if (s != null) { po = makeAnd(po, s); } } else if (etype instanceof ARecordInvariantType) { if (exp instanceof AMkTypeExp) { ARecordInvariantType rt = (ARecordInvariantType) etype; AMkTypeExp mk = (AMkTypeExp) exp; if (rt.getFields().size() == mk.getArgs().size()) { Iterator<AFieldField> fit = rt.getFields().iterator(); Iterator<PType> ait = mk.getArgTypes().iterator(); for (PExp e : mk.getArgs()) { PExp s = oneType(true, e, fit.next().getType(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } } else { po = makeAnd(po, addIs(exp, etype)); } } else { po = makeAnd(po, addIs(exp, etype)); } } else if (etype instanceof SSeqType) { po = null; if (etype instanceof ASeq1SeqType) { ANotEqualBinaryExp ne = new ANotEqualBinaryExp(); ne.setLeft(exp); ASeqEnumSeqExp empty = new ASeqEnumSeqExp(); empty.setMembers(new Vector<PExp>()); ne.setRight(empty); } if (exp instanceof ASeqEnumSeqExp) { SSeqType stype = (SSeqType) etype; ASeqEnumSeqExp seq = (ASeqEnumSeqExp) exp; Iterator<PType> it = seq.getTypes().iterator(); for (PExp m : seq.getMembers()) { - PExp s = oneType(true, m, stype.getSeqof(), it.next()); + PExp s = oneType(true, m.clone(), stype.getSeqof().clone(), it.next().clone()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASubseqExp) { ASubseqExp subseq = (ASubseqExp) exp; PType itype = AstFactory.newANatOneNumericBasicType(exp.getLocation()); PExp s = oneType(true, subseq.getFrom(), itype, subseq.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, subseq.getTo(), itype, subseq.getTtype()); if (s != null) { po = makeAnd(po, s); } ALessEqualNumericBinaryExp le = new ALessEqualNumericBinaryExp(); le.setLeft(subseq.getTo()); ALenUnaryExp len = new ALenUnaryExp(); len.setExp(subseq.getSeq()); le.setRight(len); po = makeAnd(po, le); po = makeAnd(po, addIs(exp, etype)); // Like set range does } else { po = addIs(exp, etype); // remove any "x <> []" } } else if (etype instanceof SMapType) { if (exp instanceof AMapEnumMapExp) { SMapType mtype = (SMapType) etype; AMapEnumMapExp seq = (AMapEnumMapExp) exp; Iterator<PType> dit = seq.getDomTypes().iterator(); Iterator<PType> rit = seq.getRngTypes().iterator(); po = null; for (AMapletExp m : seq.getMembers()) { PExp s = oneType(true, m.getLeft(), mtype.getFrom(), dit.next()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, m.getRight(), mtype.getTo(), rit.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof ASetType) { po = null; if (exp instanceof ASetEnumSetExp) { ASetType stype = (ASetType) etype; ASetEnumSetExp set = (ASetEnumSetExp) exp; Iterator<PType> it = set.getTypes().iterator(); for (PExp m : set.getMembers()) { PExp s = oneType(true, m, stype.getSetof(), it.next()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASetRangeSetExp) { ASetType stype = (ASetType) etype; ASetRangeSetExp range = (ASetRangeSetExp) exp; PType itype = AstFactory.newAIntNumericBasicType(exp.getLocation()); PExp s = oneType(true, range.getFirst(), itype, range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getFirst(), stype.getSetof(), range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), itype, range.getLtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), stype.getSetof(), range.getLtype()); if (s != null) { po = makeAnd(po, s); } } po = makeAnd(po, addIs(exp, etype)); } else if (etype instanceof AProductType) { if (exp instanceof ATupleExp) { AProductType pt = (AProductType) etype; ATupleExp te = (ATupleExp) exp; Iterator<PType> eit = pt.getTypes().iterator(); Iterator<PType> ait = te.getTypes().iterator(); po = null; for (PExp e : te.getArgs()) { PExp s = oneType(true, e, eit.next(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof SBasicType) { if (etype instanceof SNumericBasicType) { SNumericBasicType ent = (SNumericBasicType) etype; if (atype instanceof SNumericBasicType) { SNumericBasicType ant = (SNumericBasicType) atype; if (SNumericBasicTypeAssistantTC.getWeight(ant) > SNumericBasicTypeAssistantTC.getWeight(ent)) { boolean isWhole = SNumericBasicTypeAssistantTC.getWeight(ant) < 3; if (isWhole && ent instanceof ANatOneNumericBasicType) { AGreaterNumericBinaryExp gt = new AGreaterNumericBinaryExp(); gt.setLeft(exp); gt.setOp(new LexKeywordToken(VDMToken.GT, exp.getLocation())); gt.setRight(getIntLiteral(0)); po = gt; } else if (isWhole && ent instanceof ANatNumericBasicType) { AGreaterEqualNumericBinaryExp ge = new AGreaterEqualNumericBinaryExp(); ge.setLeft(exp); ge.setOp(new LexKeywordToken(VDMToken.GE, exp.getLocation())); ge.setRight(getIntLiteral(0)); po = ge; } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } else if (etype instanceof ABooleanBasicType) { if (!(exp instanceof ABooleanConstExp)) { po = addIs(exp, etype); } } else if (etype instanceof ACharBasicType) { if (!(exp instanceof ACharLiteralExp)) { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } return po; } /** * Just produce one is_(<expression>, <type>) node. */ private PExp addIs(PExp exp, PType type) { AIsExp isExp = new AIsExp(); isExp.setBasicType(type); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); return isExp; } }
true
true
private PExp oneType(boolean rec, PExp exp, PType etype, PType atype) { if (atype != null && rec) { if (TypeComparator.isSubType(atype, etype)) { return null; // Means a sub-comparison is OK without PO checks } } PExp po = null; etype = PTypeAssistantTC.deBracket(etype); if (etype instanceof AUnionType) { AUnionType ut = (AUnionType) etype; PTypeSet possibles = new PTypeSet(); for (PType pos : ut.getTypes()) { if (atype == null || TypeComparator.compatible(pos, atype)) { possibles.add(pos); } } po = null; for (PType poss : possibles) { PExp s = oneType(true, exp, poss, null); PExp e = addIs(exp, poss); if (s != null && !(s instanceof AIsExp)) { e = makeAnd(e, s); } po = makeOr(po, e); } } else if (etype instanceof SInvariantType) { SInvariantType et = (SInvariantType) etype; po = null; if (et.getInvDef() != null) { AVariableExp root = getVarExp(et.getInvDef().getName()); // This needs to be put back if/when we change the inv_R signature to take // the record fields as arguments, rather than one R value. // // if (exp instanceof MkTypeExpression) // { // MkTypeExpression mk = (MkTypeExpression)exp; // sb.append(Utils.listToString(mk.args)); // } // else // { // ab.append(exp); // } po = getApplyExp(root, exp); } if (etype instanceof ANamedInvariantType) { ANamedInvariantType nt = (ANamedInvariantType) etype; if (atype instanceof ANamedInvariantType) { atype = ((ANamedInvariantType) atype).getType(); } else { atype = null; } PExp s = oneType(true, exp, nt.getType(), atype); if (s != null) { po = makeAnd(po, s); } } else if (etype instanceof ARecordInvariantType) { if (exp instanceof AMkTypeExp) { ARecordInvariantType rt = (ARecordInvariantType) etype; AMkTypeExp mk = (AMkTypeExp) exp; if (rt.getFields().size() == mk.getArgs().size()) { Iterator<AFieldField> fit = rt.getFields().iterator(); Iterator<PType> ait = mk.getArgTypes().iterator(); for (PExp e : mk.getArgs()) { PExp s = oneType(true, e, fit.next().getType(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } } else { po = makeAnd(po, addIs(exp, etype)); } } else { po = makeAnd(po, addIs(exp, etype)); } } else if (etype instanceof SSeqType) { po = null; if (etype instanceof ASeq1SeqType) { ANotEqualBinaryExp ne = new ANotEqualBinaryExp(); ne.setLeft(exp); ASeqEnumSeqExp empty = new ASeqEnumSeqExp(); empty.setMembers(new Vector<PExp>()); ne.setRight(empty); } if (exp instanceof ASeqEnumSeqExp) { SSeqType stype = (SSeqType) etype; ASeqEnumSeqExp seq = (ASeqEnumSeqExp) exp; Iterator<PType> it = seq.getTypes().iterator(); for (PExp m : seq.getMembers()) { PExp s = oneType(true, m, stype.getSeqof(), it.next()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASubseqExp) { ASubseqExp subseq = (ASubseqExp) exp; PType itype = AstFactory.newANatOneNumericBasicType(exp.getLocation()); PExp s = oneType(true, subseq.getFrom(), itype, subseq.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, subseq.getTo(), itype, subseq.getTtype()); if (s != null) { po = makeAnd(po, s); } ALessEqualNumericBinaryExp le = new ALessEqualNumericBinaryExp(); le.setLeft(subseq.getTo()); ALenUnaryExp len = new ALenUnaryExp(); len.setExp(subseq.getSeq()); le.setRight(len); po = makeAnd(po, le); po = makeAnd(po, addIs(exp, etype)); // Like set range does } else { po = addIs(exp, etype); // remove any "x <> []" } } else if (etype instanceof SMapType) { if (exp instanceof AMapEnumMapExp) { SMapType mtype = (SMapType) etype; AMapEnumMapExp seq = (AMapEnumMapExp) exp; Iterator<PType> dit = seq.getDomTypes().iterator(); Iterator<PType> rit = seq.getRngTypes().iterator(); po = null; for (AMapletExp m : seq.getMembers()) { PExp s = oneType(true, m.getLeft(), mtype.getFrom(), dit.next()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, m.getRight(), mtype.getTo(), rit.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof ASetType) { po = null; if (exp instanceof ASetEnumSetExp) { ASetType stype = (ASetType) etype; ASetEnumSetExp set = (ASetEnumSetExp) exp; Iterator<PType> it = set.getTypes().iterator(); for (PExp m : set.getMembers()) { PExp s = oneType(true, m, stype.getSetof(), it.next()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASetRangeSetExp) { ASetType stype = (ASetType) etype; ASetRangeSetExp range = (ASetRangeSetExp) exp; PType itype = AstFactory.newAIntNumericBasicType(exp.getLocation()); PExp s = oneType(true, range.getFirst(), itype, range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getFirst(), stype.getSetof(), range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), itype, range.getLtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), stype.getSetof(), range.getLtype()); if (s != null) { po = makeAnd(po, s); } } po = makeAnd(po, addIs(exp, etype)); } else if (etype instanceof AProductType) { if (exp instanceof ATupleExp) { AProductType pt = (AProductType) etype; ATupleExp te = (ATupleExp) exp; Iterator<PType> eit = pt.getTypes().iterator(); Iterator<PType> ait = te.getTypes().iterator(); po = null; for (PExp e : te.getArgs()) { PExp s = oneType(true, e, eit.next(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof SBasicType) { if (etype instanceof SNumericBasicType) { SNumericBasicType ent = (SNumericBasicType) etype; if (atype instanceof SNumericBasicType) { SNumericBasicType ant = (SNumericBasicType) atype; if (SNumericBasicTypeAssistantTC.getWeight(ant) > SNumericBasicTypeAssistantTC.getWeight(ent)) { boolean isWhole = SNumericBasicTypeAssistantTC.getWeight(ant) < 3; if (isWhole && ent instanceof ANatOneNumericBasicType) { AGreaterNumericBinaryExp gt = new AGreaterNumericBinaryExp(); gt.setLeft(exp); gt.setOp(new LexKeywordToken(VDMToken.GT, exp.getLocation())); gt.setRight(getIntLiteral(0)); po = gt; } else if (isWhole && ent instanceof ANatNumericBasicType) { AGreaterEqualNumericBinaryExp ge = new AGreaterEqualNumericBinaryExp(); ge.setLeft(exp); ge.setOp(new LexKeywordToken(VDMToken.GE, exp.getLocation())); ge.setRight(getIntLiteral(0)); po = ge; } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } else if (etype instanceof ABooleanBasicType) { if (!(exp instanceof ABooleanConstExp)) { po = addIs(exp, etype); } } else if (etype instanceof ACharBasicType) { if (!(exp instanceof ACharLiteralExp)) { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } return po; }
private PExp oneType(boolean rec, PExp exp, PType etype, PType atype) { if (atype != null && rec) { if (TypeComparator.isSubType(atype, etype)) { return null; // Means a sub-comparison is OK without PO checks } } PExp po = null; etype = PTypeAssistantTC.deBracket(etype); if (etype instanceof AUnionType) { AUnionType ut = (AUnionType) etype; PTypeSet possibles = new PTypeSet(); for (PType pos : ut.getTypes()) { if (atype == null || TypeComparator.compatible(pos, atype)) { possibles.add(pos); } } po = null; for (PType poss : possibles) { PExp s = oneType(true, exp, poss, null); PExp e = addIs(exp, poss); if (s != null && !(s instanceof AIsExp)) { e = makeAnd(e, s); } po = makeOr(po, e); } } else if (etype instanceof SInvariantType) { SInvariantType et = (SInvariantType) etype; po = null; if (et.getInvDef() != null) { AVariableExp root = getVarExp(et.getInvDef().getName()); // This needs to be put back if/when we change the inv_R signature to take // the record fields as arguments, rather than one R value. // // if (exp instanceof MkTypeExpression) // { // MkTypeExpression mk = (MkTypeExpression)exp; // sb.append(Utils.listToString(mk.args)); // } // else // { // ab.append(exp); // } po = getApplyExp(root, exp); } if (etype instanceof ANamedInvariantType) { ANamedInvariantType nt = (ANamedInvariantType) etype; if (atype instanceof ANamedInvariantType) { atype = ((ANamedInvariantType) atype).getType(); } else { atype = null; } PExp s = oneType(true, exp, nt.getType(), atype); if (s != null) { po = makeAnd(po, s); } } else if (etype instanceof ARecordInvariantType) { if (exp instanceof AMkTypeExp) { ARecordInvariantType rt = (ARecordInvariantType) etype; AMkTypeExp mk = (AMkTypeExp) exp; if (rt.getFields().size() == mk.getArgs().size()) { Iterator<AFieldField> fit = rt.getFields().iterator(); Iterator<PType> ait = mk.getArgTypes().iterator(); for (PExp e : mk.getArgs()) { PExp s = oneType(true, e, fit.next().getType(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } } else { po = makeAnd(po, addIs(exp, etype)); } } else { po = makeAnd(po, addIs(exp, etype)); } } else if (etype instanceof SSeqType) { po = null; if (etype instanceof ASeq1SeqType) { ANotEqualBinaryExp ne = new ANotEqualBinaryExp(); ne.setLeft(exp); ASeqEnumSeqExp empty = new ASeqEnumSeqExp(); empty.setMembers(new Vector<PExp>()); ne.setRight(empty); } if (exp instanceof ASeqEnumSeqExp) { SSeqType stype = (SSeqType) etype; ASeqEnumSeqExp seq = (ASeqEnumSeqExp) exp; Iterator<PType> it = seq.getTypes().iterator(); for (PExp m : seq.getMembers()) { PExp s = oneType(true, m.clone(), stype.getSeqof().clone(), it.next().clone()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASubseqExp) { ASubseqExp subseq = (ASubseqExp) exp; PType itype = AstFactory.newANatOneNumericBasicType(exp.getLocation()); PExp s = oneType(true, subseq.getFrom(), itype, subseq.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, subseq.getTo(), itype, subseq.getTtype()); if (s != null) { po = makeAnd(po, s); } ALessEqualNumericBinaryExp le = new ALessEqualNumericBinaryExp(); le.setLeft(subseq.getTo()); ALenUnaryExp len = new ALenUnaryExp(); len.setExp(subseq.getSeq()); le.setRight(len); po = makeAnd(po, le); po = makeAnd(po, addIs(exp, etype)); // Like set range does } else { po = addIs(exp, etype); // remove any "x <> []" } } else if (etype instanceof SMapType) { if (exp instanceof AMapEnumMapExp) { SMapType mtype = (SMapType) etype; AMapEnumMapExp seq = (AMapEnumMapExp) exp; Iterator<PType> dit = seq.getDomTypes().iterator(); Iterator<PType> rit = seq.getRngTypes().iterator(); po = null; for (AMapletExp m : seq.getMembers()) { PExp s = oneType(true, m.getLeft(), mtype.getFrom(), dit.next()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, m.getRight(), mtype.getTo(), rit.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof ASetType) { po = null; if (exp instanceof ASetEnumSetExp) { ASetType stype = (ASetType) etype; ASetEnumSetExp set = (ASetEnumSetExp) exp; Iterator<PType> it = set.getTypes().iterator(); for (PExp m : set.getMembers()) { PExp s = oneType(true, m, stype.getSetof(), it.next()); if (s != null) { po = makeAnd(po, s); } } } else if (exp instanceof ASetRangeSetExp) { ASetType stype = (ASetType) etype; ASetRangeSetExp range = (ASetRangeSetExp) exp; PType itype = AstFactory.newAIntNumericBasicType(exp.getLocation()); PExp s = oneType(true, range.getFirst(), itype, range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getFirst(), stype.getSetof(), range.getFtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), itype, range.getLtype()); if (s != null) { po = makeAnd(po, s); } s = oneType(true, range.getLast(), stype.getSetof(), range.getLtype()); if (s != null) { po = makeAnd(po, s); } } po = makeAnd(po, addIs(exp, etype)); } else if (etype instanceof AProductType) { if (exp instanceof ATupleExp) { AProductType pt = (AProductType) etype; ATupleExp te = (ATupleExp) exp; Iterator<PType> eit = pt.getTypes().iterator(); Iterator<PType> ait = te.getTypes().iterator(); po = null; for (PExp e : te.getArgs()) { PExp s = oneType(true, e, eit.next(), ait.next()); if (s != null) { po = makeAnd(po, s); } } } else { po = addIs(exp, etype); } } else if (etype instanceof SBasicType) { if (etype instanceof SNumericBasicType) { SNumericBasicType ent = (SNumericBasicType) etype; if (atype instanceof SNumericBasicType) { SNumericBasicType ant = (SNumericBasicType) atype; if (SNumericBasicTypeAssistantTC.getWeight(ant) > SNumericBasicTypeAssistantTC.getWeight(ent)) { boolean isWhole = SNumericBasicTypeAssistantTC.getWeight(ant) < 3; if (isWhole && ent instanceof ANatOneNumericBasicType) { AGreaterNumericBinaryExp gt = new AGreaterNumericBinaryExp(); gt.setLeft(exp); gt.setOp(new LexKeywordToken(VDMToken.GT, exp.getLocation())); gt.setRight(getIntLiteral(0)); po = gt; } else if (isWhole && ent instanceof ANatNumericBasicType) { AGreaterEqualNumericBinaryExp ge = new AGreaterEqualNumericBinaryExp(); ge.setLeft(exp); ge.setOp(new LexKeywordToken(VDMToken.GE, exp.getLocation())); ge.setRight(getIntLiteral(0)); po = ge; } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } } else { AIsExp isExp = new AIsExp(); isExp.setBasicType(ent); isExp.setType(new ABooleanBasicType()); isExp.setTest(exp); po = isExp; } } else if (etype instanceof ABooleanBasicType) { if (!(exp instanceof ABooleanConstExp)) { po = addIs(exp, etype); } } else if (etype instanceof ACharBasicType) { if (!(exp instanceof ACharLiteralExp)) { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } } else { po = addIs(exp, etype); } return po; }
diff --git a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityProgramSupportedFeed.java b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityProgramSupportedFeed.java index 64d0be5985..ab34b02501 100644 --- a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityProgramSupportedFeed.java +++ b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityProgramSupportedFeed.java @@ -1,153 +1,154 @@ /* * Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.openlmis.functional; import org.openlmis.UiUtils.HttpClient; import org.openlmis.UiUtils.ResponseEntity; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.*; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertFalse; import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertTrue; public class FacilityProgramSupportedFeed extends TestCaseHelper { public WebDriver driver; @BeforeMethod(groups = {"webservice"}) public void setUp() throws Exception { super.setup(); super.setupDataExternalVendor(true); } @AfterMethod(groups = {"webservice"}) public void tearDown() throws Exception { HomePage homePage = new HomePage(testWebDriver); homePage.logout(baseUrlGlobal); dbWrapper.deleteData(); dbWrapper.closeConnection(); } @Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Positive") public void testFacilityProgramSupportedFeed_Upload(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); UploadPage uploadPage = homePage.navigateUploads(); uploadPage.uploadProgramSupportedByFacilities("QA_program_supported_WebService.csv"); Thread.sleep(5000); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); String expected = "{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":true,\"startDate\":1296585000000}"; assertTrue(responseEntity.getResponse().contains(expected)); uploadPage.uploadProgramSupportedByFacilities("QA_program_supported_Subsequent_WebService.csv"); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); expected = "{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":false,\"startDate\":1296585000000}"; String expected1 = "{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":true,\"startDate\":1304533800000}"; assertTrue(feedJSONList.get(1).contains(expected)); assertTrue(feedJSONList.get(2).contains(expected1)); } @Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Positive") public void testFacilityProgramSupportedFeed(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, ""); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); String str_date = date_time.split("-")[0].substring(0, 6) + "25"; DateFormat formatter; Date d; formatter = new SimpleDateFormat("yyyyMMdd"); d = (Date) formatter.parse(str_date); long dateLong = d.getTime(); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); String expected = "\"facilityCode\":\"" + facilityCodePrefix + date_time + "\",\"programsSupported\":[{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":true,\"startDate\":" + dateLong; assertTrue(responseEntity.getResponse().contains(expected)); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); - assertTrue(feedJSONList.get(1).contains("\"active\":true")); - assertTrue(feedJSONList.get(1).contains("\"active\":false")); + assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(1).contains("\"active\":true")); + assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(1).contains("\"active\":false")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); + responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); - assertTrue(feedJSONList.get(2).contains("\"active\":false")); - assertFalse(feedJSONList.get(2).contains("\"active\":true")); + assertTrue("feedJSONList.get(2) : "+feedJSONList.get(2),feedJSONList.get(2).contains("\"active\":false")); + assertFalse("feedJSONList.get(2) : "+feedJSONList.get(2),feedJSONList.get(2).contains("\"active\":true")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.activeInactiveFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); - assertTrue(feedJSONList.get(3).contains("\"active\":true")); - assertFalse(feedJSONList.get(3).contains("\"active\":false")); + assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(3).contains("\"active\":true")); + assertFalse("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(3).contains("\"active\":false")); } @DataProvider(name = "Data-Provider-Function-Positive") public Object[][] parameterIntTestProviderPositive() { return new Object[][]{ {"User123", "HIV", new String[]{"Admin123", "Admin123"}} }; } }
false
true
public void testFacilityProgramSupportedFeed(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, ""); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); String str_date = date_time.split("-")[0].substring(0, 6) + "25"; DateFormat formatter; Date d; formatter = new SimpleDateFormat("yyyyMMdd"); d = (Date) formatter.parse(str_date); long dateLong = d.getTime(); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); String expected = "\"facilityCode\":\"" + facilityCodePrefix + date_time + "\",\"programsSupported\":[{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":true,\"startDate\":" + dateLong; assertTrue(responseEntity.getResponse().contains(expected)); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue(feedJSONList.get(1).contains("\"active\":true")); assertTrue(feedJSONList.get(1).contains("\"active\":false")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue(feedJSONList.get(2).contains("\"active\":false")); assertFalse(feedJSONList.get(2).contains("\"active\":true")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.activeInactiveFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue(feedJSONList.get(3).contains("\"active\":true")); assertFalse(feedJSONList.get(3).contains("\"active\":false")); }
public void testFacilityProgramSupportedFeed(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, ""); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); String str_date = date_time.split("-")[0].substring(0, 6) + "25"; DateFormat formatter; Date d; formatter = new SimpleDateFormat("yyyyMMdd"); d = (Date) formatter.parse(str_date); long dateLong = d.getTime(); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); String expected = "\"facilityCode\":\"" + facilityCodePrefix + date_time + "\",\"programsSupported\":[{\"code\":\"" + program + "\",\"name\":\"" + program + "\",\"active\":true,\"startDate\":" + dateLong; assertTrue(responseEntity.getResponse().contains(expected)); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(1).contains("\"active\":true")); assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(1).contains("\"active\":false")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("feedJSONList.get(2) : "+feedJSONList.get(2),feedJSONList.get(2).contains("\"active\":false")); assertFalse("feedJSONList.get(2) : "+feedJSONList.get(2),feedJSONList.get(2).contains("\"active\":true")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.activeInactiveFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/programSupported/recent", "GET", "", ""); feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(3).contains("\"active\":true")); assertFalse("responseEntity.getResponse() : "+responseEntity.getResponse(),feedJSONList.get(3).contains("\"active\":false")); }
diff --git a/src/com/herocraftonline/dev/heroes/skill/skills/SkillTrack.java b/src/com/herocraftonline/dev/heroes/skill/skills/SkillTrack.java index 3c3e78a6..ff1d01cb 100644 --- a/src/com/herocraftonline/dev/heroes/skill/skills/SkillTrack.java +++ b/src/com/herocraftonline/dev/heroes/skill/skills/SkillTrack.java @@ -1,51 +1,51 @@ package com.herocraftonline.dev.heroes.skill.skills; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.util.config.Configuration; import org.bukkit.util.config.ConfigurationNode; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.persistence.Hero; import com.herocraftonline.dev.heroes.skill.ActiveSkill; import com.herocraftonline.dev.heroes.util.Messaging; public class SkillTrack extends ActiveSkill { public SkillTrack(Heroes plugin) { super(plugin); name = "Track"; description = "Locates a player"; usage = "/skill track <player>"; minArgs = 1; maxArgs = 1; identifiers.add("skill track"); } @Override public void init() { } @Override public ConfigurationNode getDefaultConfig() { return Configuration.getEmptyNode(); } @Override public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); Player target = plugin.getServer().getPlayer(args[0]); if (target == null) { Messaging.send(player, "Target not found."); return false; } Location location = target.getLocation(); - Messaging.send(player, "Tracked $1: $2 in $3", target.getName(), "(" + location.getBlockX() + ", " + location.getBlockY() + ", " + location.getBlockZ() + ")", location.getWorld().getName()); + Messaging.send(player, "Tracked $1: $2:$3:$4", target.getName(), Double.toString(location.getX()), Double.toString(location.getY()),Double.toString(location.getZ()) ); player.setCompassTarget(location); notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name); return true; } }
true
true
public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); Player target = plugin.getServer().getPlayer(args[0]); if (target == null) { Messaging.send(player, "Target not found."); return false; } Location location = target.getLocation(); Messaging.send(player, "Tracked $1: $2 in $3", target.getName(), "(" + location.getBlockX() + ", " + location.getBlockY() + ", " + location.getBlockZ() + ")", location.getWorld().getName()); player.setCompassTarget(location); notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name); return true; }
public boolean use(Hero hero, String[] args) { Player player = hero.getPlayer(); Player target = plugin.getServer().getPlayer(args[0]); if (target == null) { Messaging.send(player, "Target not found."); return false; } Location location = target.getLocation(); Messaging.send(player, "Tracked $1: $2:$3:$4", target.getName(), Double.toString(location.getX()), Double.toString(location.getY()),Double.toString(location.getZ()) ); player.setCompassTarget(location); notifyNearbyPlayers(player.getLocation(), useText, player.getName(), name); return true; }
diff --git a/src/app/configuration/validators/MetricValidator.java b/src/app/configuration/validators/MetricValidator.java index 4718bb3..232a11c 100644 --- a/src/app/configuration/validators/MetricValidator.java +++ b/src/app/configuration/validators/MetricValidator.java @@ -1,23 +1,23 @@ package app.configuration.validators; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; import lib.comparators.Metric; /** * validate the given value is a Metric * * @see Metric */ public class MetricValidator implements IParameterValidator { @Override public void validate(String arg, String val) throws ParameterException { try { - Metric.valueOf(val); + Metric.valueOf(val.toUpperCase()); } catch (IllegalArgumentException iae) { throw new ParameterException(String.format("Parameter %s has an invalid value: %s", arg, val)); } } }
true
true
public void validate(String arg, String val) throws ParameterException { try { Metric.valueOf(val); } catch (IllegalArgumentException iae) { throw new ParameterException(String.format("Parameter %s has an invalid value: %s", arg, val)); } }
public void validate(String arg, String val) throws ParameterException { try { Metric.valueOf(val.toUpperCase()); } catch (IllegalArgumentException iae) { throw new ParameterException(String.format("Parameter %s has an invalid value: %s", arg, val)); } }
diff --git a/src/org/fbreader/formats/fb2/FB2Reader.java b/src/org/fbreader/formats/fb2/FB2Reader.java index c7b8853c..393104ab 100644 --- a/src/org/fbreader/formats/fb2/FB2Reader.java +++ b/src/org/fbreader/formats/fb2/FB2Reader.java @@ -1,266 +1,266 @@ package org.fbreader.formats.fb2; import org.fbreader.bookmodel.BookModel; import org.fbreader.bookmodel.BookReader; import org.fbreader.bookmodel.FBTextKind; import org.zlibrary.core.xml.ZLXMLReader; import org.zlibrary.text.model.ZLTextParagraph; public class FB2Reader extends ZLXMLReader { private BookReader myModelReader = new BookReader(new BookModel()); // private String myFileName; private boolean myInsidePoem = false; private boolean myInsideTitle = false; private int myBodyCounter = 0; private boolean myReadMainText = false; private int mySectionDepth = 0; private boolean mySectionStarted = false; private byte myHyperlinkType; private FB2Tag getTag(String s) { if (s.contains("-")) { s = s.replace('-', '_'); } return FB2Tag.valueOf(s.toUpperCase()); } private byte getKind(String s) { return (byte) FBTextKind.valueOf(s.toUpperCase()).Index; } private String reference(String[] attributes) { int length = attributes.length-1; for (int i = 0; i < length; i+=2) { if (attributes[i].endsWith(":href")) { return attributes[i+1]; } } return ""; } // private BookModel myBookModel = new BookModel(); @Override public void characterDataHandler(char[] ch, int start, int length) { myModelReader.addData(String.valueOf(ch, start, length)); } @Override public void endElementHandler(String tagName) { FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: myModelReader.endParagraph(); break; case SUB: case SUP: case CODE: case EMPHASIS: case STRONG: case STRIKETHROUGH: myModelReader.addControl(getKind(tagName), false); break; case V: case SUBTITLE: case TEXT_AUTHOR: case DATE: myModelReader.popKind(); myModelReader.endParagraph(); break; case CITE: case EPIGRAPH: myModelReader.popKind(); break; case POEM: myInsidePoem = false; break; case STANZA: myModelReader.beginParagraph(ZLTextParagraph.Kind.AFTER_SKIP_PARAGRAPH); myModelReader.endParagraph(); myModelReader.popKind(); break; case SECTION: if (myReadMainText) { myModelReader.endContentsParagraph(); --mySectionDepth; mySectionStarted = false; } else { myModelReader.unsetCurrentTextModel(); } break; case ANNOTATION: myModelReader.popKind(); if (myBodyCounter == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.unsetCurrentTextModel(); } break; case TITLE: myModelReader.popKind(); myModelReader.exitTitle(); myInsideTitle = false; break; case BODY: myModelReader.popKind(); myReadMainText = false; myModelReader.unsetCurrentTextModel(); break; case A: myModelReader.addControl(myHyperlinkType, false); break; default: break; } } @Override public void startElementHandler(String tagName, String[] attributes) { String id = ZLXMLReader.attributeValue(attributes, "id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: case SUP: case CODE: case EMPHASIS: case STRONG: case STRIKETHROUGH: myModelReader.addControl(getKind(tagName), true); break; case V: myModelReader.pushKind((byte) FBTextKind.VERSE.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind((byte) FBTextKind.AUTHOR.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: case DATE: myModelReader.pushKind(getKind(tagName)); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: case EPIGRAPH: myModelReader.pushKind(getKind(tagName)); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind((byte) FBTextKind.STANZA.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind((byte) FBTextKind.ANNOTATION.Index); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind((byte) FBTextKind.POEM_TITLE.Index); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); - myModelReader.pushKind((byte) tag.ordinal()); + myModelReader.pushKind((byte) FBTextKind.TITLE.Index); } else { myModelReader.pushKind((byte) FBTextKind.SECTION_TITLE.Index); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; if ((myBodyCounter == 1) || (ZLXMLReader.attributeValue(attributes, "name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind((byte) FBTextKind.REGULAR.Index); break; case A: String ref = reference(attributes); if (ref != "") { if (ref.charAt(0) == '#') { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; ref = ref.substring(1); } else { myHyperlinkType = (byte) FBTextKind.EXTERNAL_HYPERLINK.Index; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; myModelReader.addControl(myHyperlinkType, true); } break; default: break; } } public BookModel readBook(String fileName) { return read(fileName) ? myModelReader.getModel() : null; } }
true
true
public void startElementHandler(String tagName, String[] attributes) { String id = ZLXMLReader.attributeValue(attributes, "id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: case SUP: case CODE: case EMPHASIS: case STRONG: case STRIKETHROUGH: myModelReader.addControl(getKind(tagName), true); break; case V: myModelReader.pushKind((byte) FBTextKind.VERSE.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind((byte) FBTextKind.AUTHOR.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: case DATE: myModelReader.pushKind(getKind(tagName)); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: case EPIGRAPH: myModelReader.pushKind(getKind(tagName)); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind((byte) FBTextKind.STANZA.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind((byte) FBTextKind.ANNOTATION.Index); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind((byte) FBTextKind.POEM_TITLE.Index); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.pushKind((byte) tag.ordinal()); } else { myModelReader.pushKind((byte) FBTextKind.SECTION_TITLE.Index); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; if ((myBodyCounter == 1) || (ZLXMLReader.attributeValue(attributes, "name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind((byte) FBTextKind.REGULAR.Index); break; case A: String ref = reference(attributes); if (ref != "") { if (ref.charAt(0) == '#') { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; ref = ref.substring(1); } else { myHyperlinkType = (byte) FBTextKind.EXTERNAL_HYPERLINK.Index; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; myModelReader.addControl(myHyperlinkType, true); } break; default: break; } }
public void startElementHandler(String tagName, String[] attributes) { String id = ZLXMLReader.attributeValue(attributes, "id"); if (id != null) { if (!myReadMainText) { myModelReader.setFootnoteTextModel(id); } myModelReader.addHyperlinkLabel(id); } FB2Tag tag; try { tag = getTag(tagName); } catch (IllegalArgumentException e) { return; } switch (tag) { case P: if (mySectionStarted) { mySectionStarted = false; } else if (myInsideTitle) { myModelReader.addContentsData(" "); } myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUB: case SUP: case CODE: case EMPHASIS: case STRONG: case STRIKETHROUGH: myModelReader.addControl(getKind(tagName), true); break; case V: myModelReader.pushKind((byte) FBTextKind.VERSE.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case TEXT_AUTHOR: myModelReader.pushKind((byte) FBTextKind.AUTHOR.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case SUBTITLE: case DATE: myModelReader.pushKind(getKind(tagName)); myModelReader.beginParagraph(ZLTextParagraph.Kind.TEXT_PARAGRAPH); break; case EMPTY_LINE: myModelReader.beginParagraph(ZLTextParagraph.Kind.EMPTY_LINE_PARAGRAPH); myModelReader.endParagraph(); break; case CITE: case EPIGRAPH: myModelReader.pushKind(getKind(tagName)); break; case POEM: myInsidePoem = true; break; case STANZA: myModelReader.pushKind((byte) FBTextKind.STANZA.Index); myModelReader.beginParagraph(ZLTextParagraph.Kind.BEFORE_SKIP_PARAGRAPH); myModelReader.endParagraph(); break; case SECTION: if (myReadMainText) { myModelReader.insertEndOfSectionParagraph(); ++mySectionDepth; myModelReader.beginContentsParagraph(); mySectionStarted = true; } break; case ANNOTATION: if (myBodyCounter == 0) { myModelReader.setMainTextModel(); } myModelReader.pushKind((byte) FBTextKind.ANNOTATION.Index); break; case TITLE: if (myInsidePoem) { myModelReader.pushKind((byte) FBTextKind.POEM_TITLE.Index); } else if (mySectionDepth == 0) { myModelReader.insertEndOfSectionParagraph(); myModelReader.pushKind((byte) FBTextKind.TITLE.Index); } else { myModelReader.pushKind((byte) FBTextKind.SECTION_TITLE.Index); myInsideTitle = true; myModelReader.enterTitle(); } break; case BODY: ++myBodyCounter; if ((myBodyCounter == 1) || (ZLXMLReader.attributeValue(attributes, "name") == null)) { myModelReader.setMainTextModel(); myReadMainText = true; } myModelReader.pushKind((byte) FBTextKind.REGULAR.Index); break; case A: String ref = reference(attributes); if (ref != "") { if (ref.charAt(0) == '#') { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; ref = ref.substring(1); } else { myHyperlinkType = (byte) FBTextKind.EXTERNAL_HYPERLINK.Index; } myModelReader.addHyperlinkControl(myHyperlinkType, ref); } else { myHyperlinkType = (byte) FBTextKind.FOOTNOTE.Index; myModelReader.addControl(myHyperlinkType, true); } break; default: break; } }
diff --git a/CodenameG/src/edu/chl/codenameg/controller/LevelState.java b/CodenameG/src/edu/chl/codenameg/controller/LevelState.java index 724abf0..794e8f7 100644 --- a/CodenameG/src/edu/chl/codenameg/controller/LevelState.java +++ b/CodenameG/src/edu/chl/codenameg/controller/LevelState.java @@ -1,127 +1,131 @@ package edu.chl.codenameg.controller; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import edu.chl.codenameg.model.Action; import edu.chl.codenameg.model.GameModel; import edu.chl.codenameg.view.LevelView; public class LevelState extends BasicGameState { LevelView view; GameModel model; boolean player1LeftKeyPressed; boolean player1RightKeyPressed; boolean player2LeftKeyPressed; boolean player2RightKeyPressed; public LevelState(GameModel model) { this.view = new LevelView(model); this.model = model; player1LeftKeyPressed = false; player1RightKeyPressed = false; player2LeftKeyPressed = false; player2RightKeyPressed = false; } @Override public void init(GameContainer arg0, StateBasedGame arg1) throws SlickException { // TODO Auto-generated method stub } @Override public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException { view.repaint(g); } @Override public void update(GameContainer container, StateBasedGame game, int elapsedTime) throws SlickException { // TODO Auto-generated method stub model.update(elapsedTime); } @Override public int getID() { // TODO Auto-generated method stub return 2; } @Override public void keyPressed(int key, char c) { Action action = KeyBindings.getAction(key); switch (action) { case PLAYER_1_MOVE_LEFT: player1LeftKeyPressed = true; break; case PLAYER_1_MOVE_RIGHT: player1RightKeyPressed = true; break; case PLAYER_2_MOVE_LEFT: player2LeftKeyPressed = true; break; case PLAYER_2_MOVE_RIGHT: player2RightKeyPressed = true; break; default: break; } model.performAction(action); } @Override public void keyReleased(int key, char c) { Action action = KeyBindings.getAction(key); switch (action) { case PLAYER_1_MOVE_LEFT: player1LeftKeyPressed = false; if (player1RightKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_RIGHT); + } else { + model.stopAction(action); } - model.stopAction(action); break; case PLAYER_1_MOVE_RIGHT: player1RightKeyPressed = false; if (player1LeftKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_LEFT); + }else { + model.stopAction(action); } - model.stopAction(action); break; case PLAYER_2_MOVE_LEFT: player2LeftKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); + }else { + model.stopAction(action); } - model.stopAction(action); break; case PLAYER_2_MOVE_RIGHT: player2RightKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); + }else { + model.stopAction(action); } - model.stopAction(action); break; default: model.stopAction(action); break; } // Doesn't matter if I send both stopActions or not if (!player1LeftKeyPressed && !player1RightKeyPressed) { model.stopAction(Action.PLAYER_1_MOVE_LEFT); } else if (!player2LeftKeyPressed && !player2RightKeyPressed) { model.stopAction(Action.PLAYER_2_MOVE_LEFT); } } }
false
true
public void keyReleased(int key, char c) { Action action = KeyBindings.getAction(key); switch (action) { case PLAYER_1_MOVE_LEFT: player1LeftKeyPressed = false; if (player1RightKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_RIGHT); } model.stopAction(action); break; case PLAYER_1_MOVE_RIGHT: player1RightKeyPressed = false; if (player1LeftKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_LEFT); } model.stopAction(action); break; case PLAYER_2_MOVE_LEFT: player2LeftKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); } model.stopAction(action); break; case PLAYER_2_MOVE_RIGHT: player2RightKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); } model.stopAction(action); break; default: model.stopAction(action); break; } // Doesn't matter if I send both stopActions or not if (!player1LeftKeyPressed && !player1RightKeyPressed) { model.stopAction(Action.PLAYER_1_MOVE_LEFT); } else if (!player2LeftKeyPressed && !player2RightKeyPressed) { model.stopAction(Action.PLAYER_2_MOVE_LEFT); } }
public void keyReleased(int key, char c) { Action action = KeyBindings.getAction(key); switch (action) { case PLAYER_1_MOVE_LEFT: player1LeftKeyPressed = false; if (player1RightKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_RIGHT); } else { model.stopAction(action); } break; case PLAYER_1_MOVE_RIGHT: player1RightKeyPressed = false; if (player1LeftKeyPressed) { model.performAction(Action.PLAYER_1_MOVE_LEFT); }else { model.stopAction(action); } break; case PLAYER_2_MOVE_LEFT: player2LeftKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); }else { model.stopAction(action); } break; case PLAYER_2_MOVE_RIGHT: player2RightKeyPressed = false; if (player2RightKeyPressed) { model.performAction(Action.PLAYER_2_MOVE_RIGHT); }else { model.stopAction(action); } break; default: model.stopAction(action); break; } // Doesn't matter if I send both stopActions or not if (!player1LeftKeyPressed && !player1RightKeyPressed) { model.stopAction(Action.PLAYER_1_MOVE_LEFT); } else if (!player2LeftKeyPressed && !player2RightKeyPressed) { model.stopAction(Action.PLAYER_2_MOVE_LEFT); } }
diff --git a/src/uk/me/graphe/client/DrawingImpl.java b/src/uk/me/graphe/client/DrawingImpl.java index 5d174da..61d6a7d 100644 --- a/src/uk/me/graphe/client/DrawingImpl.java +++ b/src/uk/me/graphe/client/DrawingImpl.java @@ -1,1688 +1,1687 @@ package uk.me.graphe.client; import java.util.Collection; import com.google.gwt.widgetideas.graphics.client.Color; import com.google.gwt.widgetideas.graphics.client.GWTCanvas; public class DrawingImpl implements Drawing { //used for panning public int offsetX, offsetY; public double zoom; private static native void runJavascript(String script) /*-{ eval(script); }-*/; // JSNI method for WebGL private static native void drawGraph3D() /*-{ var circleCoords = new Array(1000); for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000); var gl; var shaderProgram; var mvMatrix; var mvMatrixStack = []; var colors = [[0.0, 0.0, 0.0], // BLACK 0 [1.0, 1.0, 1.0], // WHITE 1 [1.0, 0.0, 0.0], // RED 2 [0.0, 1.0, 0.0], // GREEN 3 [0.0, 0.0, 1.0], // BLUE 4 [1.0, 1.0, 0.0], // YELLOW 5 [1.0, 0.317, 1.0], // PINK 6 [0.5, 0.5, 0.5], // GREY 7 ]; var hersheyFont=[ [0,16,//Ascii32 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii33 5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii34 4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,21,//Ascii35 11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [26,20,//Ascii36 8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3, 18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0, 8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [31,24,//Ascii37 21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4, 20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4, 14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [34,26,//Ascii38 23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5, 1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21, 9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii39 5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii40 11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii41 3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,16,//Ascii42 8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii43 13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii44 6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,26,//Ascii45 4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,10,//Ascii46 5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,22,//Ascii47 20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii48 9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17, 9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [4,20,//Ascii49 6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,20,//Ascii50 4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13, 10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,20,//Ascii51 5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8, 0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,20,//Ascii52 13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii53 15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14, 1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii54 16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11, 0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii55 17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [29,20,//Ascii56 8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16, 2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13, 15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii57 16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9, 21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii58 5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,10,//Ascii59 5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6, -1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii60 20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii61 4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii62 4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,18,//Ascii63 3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13, 12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [55,27,//Ascii64 18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16, 6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8, 17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12, 21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0, 15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,], [8,18,//Ascii65 9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,21,//Ascii66 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,21,//Ascii67 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,21,//Ascii68 4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16, 3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,19,//Ascii69 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,18,//Ascii70 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,21,//Ascii71 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii72 4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii73 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii74 12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,21,//Ascii75 4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii76 4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii77 4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii78 4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [21,22,//Ascii79 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [13,21,//Ascii80 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13, 10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [24,22,//Ascii81 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4, 18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [16,21,//Ascii82 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,20,//Ascii83 17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15, 9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii84 8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,22,//Ascii85 4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,18,//Ascii86 1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii87 2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii88 3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,18,//Ascii89 1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,20,//Ascii90 17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii91 4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,14,//Ascii92 0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii93 9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii94 6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,16,//Ascii95 0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii96 6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii97 15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii98 4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,18,//Ascii99 15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11, 0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii100 15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,18,//Ascii101 3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii102 10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,19,//Ascii103 15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8, 14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii104 4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,8,//Ascii105 3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii106 5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii107 4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii108 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,30,//Ascii109 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15, 10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii110 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii111 8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16, 6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii112 4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii113 15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,13,//Ascii114 4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,17,//Ascii115 14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14, 3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii116 5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii117 4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii118 2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,22,//Ascii119 3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii120 3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [9,16,//Ascii121 2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii122 14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii123 9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7, 24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3, 8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5, -1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii124 4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii125 5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7, 24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3, 6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9, -1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,24,//Ascii126 3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1, -1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,] ]; // Sylvester.js Libary eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{})) // gtUtils.js Libary Matrix.Translation = function (v) { if (v.elements.length == 2) { var r = Matrix.I(3); r.elements[2][0] = v.elements[0]; r.elements[2][1] = v.elements[1]; return r; } if (v.elements.length == 3) { var r = Matrix.I(4); r.elements[0][3] = v.elements[0]; r.elements[1][3] = v.elements[1]; r.elements[2][3] = v.elements[2]; return r; } throw "Invalid length for Translation"; } Matrix.prototype.flatten = function () { var result = []; if (this.elements.length == 0) return []; for (var j = 0; j < this.elements[0].length; j++) for (var i = 0; i < this.elements.length; i++) result.push(this.elements[i][j]); return result; } Matrix.prototype.ensure4x4 = function() { if (this.elements.length == 4 && this.elements[0].length == 4) return this; if (this.elements.length > 4 || this.elements[0].length > 4) return null; for (var i = 0; i < this.elements.length; i++) { for (var j = this.elements[i].length; j < 4; j++) { if (i == j) this.elements[i].push(1); else this.elements[i].push(0); } } for (var i = this.elements.length; i < 4; i++) { if (i == 0) this.elements.push([1, 0, 0, 0]); else if (i == 1) this.elements.push([0, 1, 0, 0]); else if (i == 2) this.elements.push([0, 0, 1, 0]); else if (i == 3) this.elements.push([0, 0, 0, 1]); } return this; }; Matrix.prototype.make3x3 = function() { if (this.elements.length != 4 || this.elements[0].length != 4) return null; return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], [this.elements[1][0], this.elements[1][1], this.elements[1][2]], [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); }; Vector.prototype.flatten = function () { return this.elements; }; function mht(m) { var s = ""; if (m.length == 16) { for (var i = 0; i < 4; i++) { s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>"; } } else if (m.length == 9) { for (var i = 0; i < 3; i++) { s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>"; } } else { return m.toString(); } return s; } function makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz) { var eye = $V([ex, ey, ez]); var center = $V([cx, cy, cz]); var up = $V([ux, uy, uz]); var mag; var z = eye.subtract(center).toUnitVector(); var x = up.cross(z).toUnitVector(); var y = z.cross(x).toUnitVector(); var m = $M([[x.e(1), x.e(2), x.e(3), 0], [y.e(1), y.e(2), y.e(3), 0], [z.e(1), z.e(2), z.e(3), 0], [0, 0, 0, 1]]); var t = $M([[1, 0, 0, -ex], [0, 1, 0, -ey], [0, 0, 1, -ez], [0, 0, 0, 1]]); return m.x(t); } function makePerspective(fovy, aspect, znear, zfar) { var ymax = znear * Math.tan(fovy * Math.PI / 360.0); var ymin = -ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); } function makeFrustum(left, right, bottom, top, znear, zfar) { var X = 2*znear/(right-left); var Y = 2*znear/(top-bottom); var A = (right+left)/(right-left); var B = (top+bottom)/(top-bottom); var C = -(zfar+znear)/(zfar-znear); var D = -2*zfar*znear/(zfar-znear); return $M([[X, 0, A, 0], [0, Y, B, 0], [0, 0, C, D], [0, 0, -1, 0]]); } function makeOrtho(left, right, bottom, top, znear, zfar) { var tx = - (right + left) / (right - left); var ty = - (top + bottom) / (top - bottom); var tz = - (zfar + znear) / (zfar - znear); return $M([[2 / (right - left), 0, 0, tx], [0, 2 / (top - bottom), 0, ty], [0, 0, -2 / (zfar - znear), tz], [0, 0, 0, 1]]); } // End of Libaries function initGL(canvas) { try { gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(e) { } if (!gl) { alert("Could not initialise WebGL"); } } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var str = ""; var k = shaderScript.firstChild; while (k) { if (k.nodeType == 3) { str += k.textContent; } k = k.nextSibling; } var shader; if (shaderScript.type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, str); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } function mvPushMatrix(m) { if (m) { mvMatrixStack.push(m.dup()); mvMatrix = m.dup(); } else { mvMatrixStack.push(mvMatrix.dup()); } } function mvPopMatrix() { if (mvMatrixStack.length == 0) { throw "Invalid popMatrix!"; } mvMatrix = mvMatrixStack.pop(); return mvMatrix; } function loadIdentity() { mvMatrix = Matrix.I(4); } function multMatrix(m) { mvMatrix = mvMatrix.x(m); } function mvTranslate(v) { var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } function mvRotate(ang, v) { var arad = ang * Math.PI / 180.0; var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } var pMatrix; function perspective(fovy, aspect, znear, zfar) { pMatrix = makePerspective(fovy, aspect, znear, zfar); } function setMatrixUniforms() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); } function compareXValue(array1, array2) { var value1 = array1[0]; var value2 = array2[0]; if (value1 > value2) return 1; if (value1 < value2) return -1; return 0; } function setupShaders(){ var headID = document.getElementsByTagName("head")[0]; var fsScript = document.createElement('script'); fsScript.id="shader-fs"; fsScript.type = 'x-shader/x-fragment'; fsScript.text = "#ifdef GL_ES\n\ precision highp float;\n\ #endif\n\ varying vec4 vColor;\n\ void main(void) {\n\ gl_FragColor = vColor;\n\ }"; var vsScript = document.createElement('script'); vsScript.id="shader-vs"; vsScript.type = 'x-shader/x-vertex'; vsScript.text = "attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ uniform mat4 uMVMatrix;\n\ uniform mat4 uPMatrix;\n\ \n\ varying vec4 vColor;\n\ \n\ void main(void) {\n\ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\ vColor = aVertexColor;\n\ }"; headID.appendChild(vsScript); headID.appendChild(fsScript); initShaders(); } function setupCanvas(){ canvas1 = document.getElementsByTagName("canvas")[1]; canvas1.style.position = "absolute"; canvas1.style.zIndex = 10; canvas1.style.opacity = 0.5; canvas = document.getElementsByTagName("canvas")[0]; canvas.style.zIndex = 0; initGL(canvas); } function setupGL(){ setupCanvas(); setupShaders(); gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0); loadIdentity(); var uTop = 2.478; var uLeft = -uTop; mvTranslate([uLeft,uTop, -10.0]) mvPushMatrix(); } // Drawing functions function drawPolygon(pixelVertices,color) { var factor; var glWidth = 4.92; var vertices = new Float32Array(1000); var polygonColors = new Float32Array(1000); var vl = 0; if(canvas.width>=canvas.height) factor = glWidth/canvas.height; else factor = glWidth/canvas.width; for(var i=0;i<pixelVertices.length;i++){ pixelVertices[i] = (pixelVertices[i])*factor; if (i%2){ vertices[vl] = -pixelVertices[i]; vl++; vertices[vl] = (4.0); } else { vertices[vl] = (pixelVertices[i]); } vl++; } vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = vl / 3.0; vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); for(var i=0;i<(vl / 3.0)*4;i+=4){ polygonColors[i] = color[0]; polygonColors[i+1] = color[1]; polygonColors[i+2] = color[2]; polygonColors[i+3] = color[3]; } gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = vl / 3.0; gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0); } function drawLine(left1,top1,left2,top2,width,color) { if(top1 <= top2){ var temp1 = left1; var temp2 = top1; left1 = left2; top1 = top2; left2 = temp1; top2 = temp2; } var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1))); var vHeight = top1-top2; var hWidth = left1-left2; var deg = 180/Math.PI; var angle = Math.atan(vHeight/hWidth); var angle2 = ((Math.PI/2)-angle); var height2 = Math.sin(angle2)*(width/2); var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2)); if(angle*deg<0) { var topRightX = left1-(width2); var topRightY = top1-height2; var topLeftX = left1+(width2); var topLeftY = top1+height2; var bottomRightX = left2-(width2); var bottomRightY = top2-height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2+height2; } else { var topRightX = left1-(width2); var topRightY = top1+height2; var topLeftX = left1+(width2); var topLeftY = top1-height2; var bottomRightX = left2-(width2); var bottomRightY = top2+height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2-height2; } var pvertices = new Float32Array([ topRightX, topRightY, topLeftX, topLeftY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY ]); drawPolygon(pvertices,color); } function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);} function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){ var diam = width/2; var topOffset = Math.round(Math.sin(rotation)*diam); var leftOffset = Math.round(Math.cos(rotation)*diam); drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color); } function drawDiamond(left,top,width,height,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(8); pvertices[0] = left; pvertices[1] = top-halfHeight; pvertices[2] = left-halfWidth; pvertices[3] = top; pvertices[4] = left+halfWidth; pvertices[5] = top; pvertices[6] = left; pvertices[7] = top+halfHeight; drawPolygon(pvertices,color); } function drawTriang(left,top,width,height,rotation,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(6); pvertices[0] = 0; pvertices[1] = 0-halfHeight; pvertices[2] = 0-halfWidth; pvertices[3] = 0+halfHeight; pvertices[4] = 0+halfWidth; pvertices[5] = 0+halfHeight; var j = 0; for (i=0;i<3;i++) { var tempX = pvertices[j]; var tempY = pvertices[j+1]; pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+left); j++; pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+top); j++; } drawPolygon(pvertices,color); } function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)}; function drawCircleDim(left,top,width,height,color){ left = Math.round(left); top = Math.round(top); width = Math.round(width); height = Math.round(height); var w = Math.round(width/2); var h = Math.round(height/2); var numSections; if(width>height)numSections = width*2; else numSections = height*2; if(numSections>33)numSections = 33; if(numSections<10)numSections = 10; var delta_theta = 2.0 * Math.PI / numSections var theta = 0 if(circleCoords[w][h]==undefined) { //alert("make circle "+r); circleCoords[w][h] = new Array(numSections); circleCoords[w][h] = new Array(numSections); for (i = 0; i < numSections ; i++) { circleCoords[w][h][i] = new Array(2); x = (w * Math.cos(theta)); y = (h * Math.sin(theta)); x = Math.round(x*1000)/1000 y = Math.round(y*1000)/1000 circleCoords[w][h][i][1] = x; circleCoords[w][h][i][0] = y; theta += delta_theta } circleCoords[w][h].sort(compareXValue); for(var i = 0;i<numSections-1;i++) { if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1]) { temp = circleCoords[w][h][i]; circleCoords[w][h][i] = circleCoords[w][h][i+1]; circleCoords[w][h][i+1] = temp; } } } var j = 0; var pvertices = new Float32Array(numSections*2); for (i=0;i<numSections;i++) { pvertices[j] = circleCoords[w][h][i][1]+left; j++; pvertices[j] = circleCoords[w][h][i][0]+top; j++; } drawPolygon(pvertices,color); } function drawLineArrow(left1,top1,left2,top2,width,color) { var opp = top1-top2; var adj = left1-left2; var angle = Math.atan(opp/adj)+Math.PI/2; if(left1>left2 )angle+=Math.PI; drawLine(left1,top1,left2,top2,width,color); var triLeft = left1-Math.round(adj/2); var triTop = top1-Math.round(opp/2); drawTriang(triLeft,triTop,20,20,angle,color); } function stringPixelLength(string) { var code; var width = 0; for(i=0;i<string.length;i++) { code = string.charCodeAt(i)-32; width += hersheyFont[code][1]; } return width; } function printChar(left,top,character,color,thickness,size) { var code = character.charCodeAt(0)-32; var verticesNeeded = hersheyFont[code][0]; var width = hersheyFont[code][1]; var lef1; var top1; var left2; var top2; var j = 0; var i = 2; var fHeight = 10*size; while(i<(verticesNeeded*2)+2) { j++; left1 = hersheyFont[code][i]*size+left; top1 = (fHeight-hersheyFont[code][i+1]*size)+top; if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1) { if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1) { drawLine(left2,top2,left1,top1,thickness,color); } if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1) { left2 = hersheyFont[code][i+2]*size+left; top2 = (fHeight-hersheyFont[code][i+3]*size)+top; drawLine(left1,top1,left2,top2,thickness,color); } i+=4; } else { i+=2; } } return width*size; } function printString(left,top,string,color,thickness,size) { var wordArray = string.split(" "); var numWords = wordArray.length; var length = (stringPixelLength(string)/2)*size; var offset = -length; for(i=0;i<string.length;i++) { offset += printChar(left+offset,top,string[i],color,thickness,size); } } //Styling functions function getColor(index) { var temp = new Array(4); temp = [colors[index][0],colors[index][1],colors[index][2],1.0] return temp; } function flowTerminator(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; flowTerminatorNoStroke(left,top,width,height,strokeColor); flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color); } function flowTerminatorNoStroke(left,top,width,height,color) { var cWidth = height; var cOff = (width/2)-(cWidth/2); drawCircle(left-cOff,top,cWidth,color); drawCircle(left+cOff,top,cWidth,color); drawSquare(left,top,cOff*2,height,0,color); } function flowProcess(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawSquare(left,top,width,height,0,strokeColor); drawSquare(left,top,width-sOff,height-sOff,0,color); } function diamondStrokeAlgorithm(width, height, strokeSize) { var angle1 = Math.atan(height/width); var angle2 = Math.PI/2 - angle1; var opp = strokeSize*Math.sin(angle2); var width1Sq = (strokeSize*strokeSize)-(opp*opp); var width1 = Math.sqrt(width1Sq); var width2 = opp/(Math.tan(angle1)); var fWidth = (width1+width2)*2; return fWidth; } function flowDecision(left,top,width,height,color,strokeSize,strokeColor) { var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize); var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize); drawDiamond(left,top,width,height,strokeColor); drawDiamond(left,top,width-wOff,height-hOff,color); } // BLACK 0 // WHITE 1 // RED 2 // GREEN 3 // BLUE 4 // YELLOW 5 // PINK 6 // GREY 7 function drawEdge(left1,top1, left2,top2,style){ switch(style){ case 100: // FLOW CHART // Draw line with Arrow at end drawLineArrow(left1,top1,left2,top2,2,getColor(0)); break; case -100: // Draw line with Arrow at end - HIGHLIGHTED drawLineArrow(left1,top1,left2,top2,2,getColor(6)); break; case -10: drawLine(left1,top1,left2,top2,2,getColor(6)); break; default: //Default edge style: black line drawLine(left1,top1,left2,top2,2,getColor(0)); } } function drawVertex(left,top,width,height,style,text,c1,c2,c3) { var flowStrokeHighColor = getColor(5); var flowStrokeColor = getColor(0); var flowColor = getColor(7); var flowStrokeSize = 2; var flowTextColor = getColor(0); var customColor = [c1,c2,c3,1.0]; switch(style){ case 100: // (100 - 199) FLOW CHART SYMBOLS // Terminator, start stop flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -100: // Terminator, start stop - HIGHLIGHTED flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 101: // Process, process or action step flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -101: // Process, process or action step - HIGHLIGHTED flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 102: // Decision, question or branch flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -102: // Decision, question or branch - HIGHLIGHTED flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case -5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeHighColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case 1: // Smiley Face drawCircle(left,top,width,5); drawCircle(left,top,width*0.7,0); drawCircle(left,top,width*0.5,5); drawSquare(left,top,width*0.7,width*0.2,0,5); drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5); drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5); drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5); drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0); drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0); break; case 2: // Bart Simpson drawSquare(left,top,width*0.9,width*1.1,0,0); drawSquare(left,top,width*0.85,width*1.05,0,5); drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0); drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5); drawCircle(left+width*0.15,top+width*0.45,width*0.6,0); drawCircle(left+width*0.15,top+width*0.45,width*0.545,5); drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5); drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5); drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5); drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0) drawCircle(left+width*0.3,top-width*0.1,width*0.4,0); drawCircle(left+width*0.3,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top+width*0.1,width*0.2,0); drawCircle(left+width*0.3,top+width*0.1,width*0.15,5); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5); drawCircle(left+width*0.05,top-width*0.1,width*0.4,0); drawCircle(left+width*0.05,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top-width*0.1,width*0.05,0); drawCircle(left+width*0.05,top-width*0.1,width*0.05,0); break; case -10: drawCircleDim(left,top,width,height,6); break; default: // Default vertex style: black circle drawCircleDim(left,top,width,height,0); } } function drawGraph() { setupGL(); for(var i=0;i<edgeNumber;i++) { var left1 = parseInt(edgeArray[i][0]); var top1 = parseInt(edgeArray[i][1]); var left2 = parseInt(edgeArray[i][2]); var top2 = parseInt(edgeArray[i][3]); var style = parseInt(edgeArray[i][4]); drawEdge( left1,top1,left2,top2,style); } for(var i=0;i<verticeNumber;i++) { var left = parseInt(verticeArray[i][0]); var top = parseInt(verticeArray[i][1]); var width = parseInt(verticeArray[i][2]); var height = parseInt(verticeArray[i][3]); var style = parseInt(verticeArray[i][4]); var text = verticeArray[i][5]; var c1 = verticeArray[i][6]; var c2 = verticeArray[i][7]; var c3 = verticeArray[i][8]; drawVertex(left,top,width,height,style,text,c1,c2,c3); } } drawGraph(); }-*/; private static native int setupJSNI()/*-{ $wnd.edgeNumber = 0; $wnd.verticeNumber = 0; $wnd.edgeArray = new Array(1000); for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5); $wnd.verticeArray = new Array(1000); for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9); }-*/; private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{ edgeArray[edgeNumber][0] = parseInt(startX); edgeArray[edgeNumber][1] = parseInt(startY); edgeArray[edgeNumber][2] = parseInt(endX); edgeArray[edgeNumber][3] = parseInt(endY); edgeArray[edgeNumber][4] = parseInt(style); edgeNumber++; }-*/; private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{ verticeArray[verticeNumber][0] = parseInt(centreX); verticeArray[verticeNumber][1] = parseInt(centreY); verticeArray[verticeNumber][2] = parseInt(width); verticeArray[verticeNumber][3] = parseInt(height); verticeArray[verticeNumber][4] = parseInt(style); verticeArray[verticeNumber][5] = label; verticeArray[verticeNumber][6] = c1; verticeArray[verticeNumber][7] = c1; verticeArray[verticeNumber][8] = c1; verticeNumber++; }-*/; private static native int webglCheck()/*-{ if (typeof Float32Array != "undefined")return 1; return 0; }-*/; public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { // Do a (kind of reliable) check for webgl if (webglCheck() == 1) { // Can do WebGL // At the moment coordinates are passed to JavaScript as comma // separated strings // This will most probably change in the // future. setupJSNI(); String edgesString = ""; String veticesString = ""; String separator = ","; String label = ""; int vertexStyle; int edgeStyle; for (EdgeDrawable thisEdge : edges) { double startX = (thisEdge.getStartX() + offsetX)*zoom; double startY = (thisEdge.getStartY() + offsetY)*zoom; double endX = (thisEdge.getEndX() + offsetX)*zoom; double endY = (thisEdge.getEndY() + offsetY)*zoom; //edgeStyle = thisEdge.getStyle(); edgeStyle = 100; if(thisEdge.isHilighted())edgeStyle = -100; addEdge(startX,startY,endX,endY,edgeStyle); } for (VertexDrawable thisVertex : vertices) { double centreX = (thisVertex.getCenterX() + offsetX)*zoom; double centreY = (thisVertex.getCenterY() + offsetY)*zoom; double width = (0.5 * thisVertex.getWidth())*zoom; double height = (0.5 * thisVertex.getHeight())*zoom; vertexStyle = thisVertex.getStyle(); switch (vertexStyle) { case VertexDrawable.STROKED_TERM_STYLE: vertexStyle = 100; break; case VertexDrawable.STROKED_SQUARE_STYLE: vertexStyle = 101; break; case VertexDrawable.STROKED_DIAMOND_STYLE: vertexStyle = 102; break; default: vertexStyle = 100; break; } label = thisVertex.getLabel(); int[] customColor = {0,0,0}; if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE) { vertexStyle = 5; customColor = thisVertex.getColor(); } if(thisVertex.isHilighted())vertexStyle = -vertexStyle; - runJavascript("alert("+vertexStyle+")"); addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]); } // JSNI method used to draw webGL graph version drawGraph3D(); } else { // Cant do webGL so draw on 2d Canvas renderGraph2d(canvas, edges, vertices); } } public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { canvas.setLineWidth(1); canvas.setStrokeStyle(Color.BLACK); canvas.setFillStyle(Color.BLACK); canvas.setFillStyle(Color.WHITE); canvas.fillRect(0, 0, 2000, 2000); canvas.setFillStyle(Color.BLACK); drawGraph(edges, vertices, canvas); } // Draws a single vertex, currently only draws circular nodes private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) { double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom; double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom; double radius = (0.25 * vertex.getWidth()) * zoom; canvas.moveTo(centreX, centreY); canvas.beginPath(); canvas.arc(centreX, centreY, radius, 0, 360, false); canvas.closePath(); canvas.stroke(); canvas.fill(); } // Draws a line from coordinates to other coordinates private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) { double startX = (edge.getStartX() + offsetX)*zoom; double startY = (edge.getStartY() + offsetY)*zoom; double endX = (edge.getEndX() + offsetX)*zoom; double endY = (edge.getEndY() + offsetY)*zoom; canvas.beginPath(); canvas.moveTo(startX, startY); canvas.lineTo(endX, endY); canvas.closePath(); canvas.stroke(); } // Takes collections of edges and vertices and draws a graph on a specified // canvas. private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices, GWTCanvas canvas) { for (EdgeDrawable thisEdge : edges) { drawEdge(thisEdge, canvas); } for (VertexDrawable thisVertex : vertices) { drawVertex(thisVertex, canvas); } } // set offset in the event of a pan public void setOffset(int x, int y) { offsetX = x; offsetY = y; } // getters for offsets public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } //set zoom public void setZoom(double z) { zoom = z; } public double getZoom(){ return zoom; } }
true
true
private static native void drawGraph3D() /*-{ var circleCoords = new Array(1000); for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000); var gl; var shaderProgram; var mvMatrix; var mvMatrixStack = []; var colors = [[0.0, 0.0, 0.0], // BLACK 0 [1.0, 1.0, 1.0], // WHITE 1 [1.0, 0.0, 0.0], // RED 2 [0.0, 1.0, 0.0], // GREEN 3 [0.0, 0.0, 1.0], // BLUE 4 [1.0, 1.0, 0.0], // YELLOW 5 [1.0, 0.317, 1.0], // PINK 6 [0.5, 0.5, 0.5], // GREY 7 ]; var hersheyFont=[ [0,16,//Ascii32 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii33 5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii34 4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,21,//Ascii35 11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [26,20,//Ascii36 8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3, 18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0, 8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [31,24,//Ascii37 21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4, 20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4, 14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [34,26,//Ascii38 23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5, 1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21, 9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii39 5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii40 11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii41 3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,16,//Ascii42 8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii43 13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii44 6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,26,//Ascii45 4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,10,//Ascii46 5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,22,//Ascii47 20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii48 9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17, 9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [4,20,//Ascii49 6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,20,//Ascii50 4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13, 10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,20,//Ascii51 5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8, 0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,20,//Ascii52 13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii53 15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14, 1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii54 16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11, 0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii55 17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [29,20,//Ascii56 8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16, 2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13, 15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii57 16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9, 21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii58 5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,10,//Ascii59 5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6, -1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii60 20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii61 4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii62 4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,18,//Ascii63 3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13, 12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [55,27,//Ascii64 18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16, 6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8, 17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12, 21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0, 15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,], [8,18,//Ascii65 9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,21,//Ascii66 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,21,//Ascii67 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,21,//Ascii68 4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16, 3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,19,//Ascii69 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,18,//Ascii70 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,21,//Ascii71 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii72 4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii73 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii74 12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,21,//Ascii75 4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii76 4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii77 4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii78 4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [21,22,//Ascii79 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [13,21,//Ascii80 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13, 10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [24,22,//Ascii81 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4, 18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [16,21,//Ascii82 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,20,//Ascii83 17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15, 9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii84 8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,22,//Ascii85 4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,18,//Ascii86 1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii87 2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii88 3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,18,//Ascii89 1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,20,//Ascii90 17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii91 4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,14,//Ascii92 0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii93 9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii94 6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,16,//Ascii95 0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii96 6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii97 15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii98 4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,18,//Ascii99 15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11, 0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii100 15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,18,//Ascii101 3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii102 10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,19,//Ascii103 15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8, 14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii104 4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,8,//Ascii105 3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii106 5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii107 4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii108 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,30,//Ascii109 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15, 10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii110 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii111 8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16, 6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii112 4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii113 15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,13,//Ascii114 4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,17,//Ascii115 14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14, 3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii116 5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii117 4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii118 2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,22,//Ascii119 3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii120 3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [9,16,//Ascii121 2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii122 14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii123 9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7, 24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3, 8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5, -1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii124 4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii125 5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7, 24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3, 6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9, -1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,24,//Ascii126 3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1, -1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,] ]; // Sylvester.js Libary eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{})) // gtUtils.js Libary Matrix.Translation = function (v) { if (v.elements.length == 2) { var r = Matrix.I(3); r.elements[2][0] = v.elements[0]; r.elements[2][1] = v.elements[1]; return r; } if (v.elements.length == 3) { var r = Matrix.I(4); r.elements[0][3] = v.elements[0]; r.elements[1][3] = v.elements[1]; r.elements[2][3] = v.elements[2]; return r; } throw "Invalid length for Translation"; } Matrix.prototype.flatten = function () { var result = []; if (this.elements.length == 0) return []; for (var j = 0; j < this.elements[0].length; j++) for (var i = 0; i < this.elements.length; i++) result.push(this.elements[i][j]); return result; } Matrix.prototype.ensure4x4 = function() { if (this.elements.length == 4 && this.elements[0].length == 4) return this; if (this.elements.length > 4 || this.elements[0].length > 4) return null; for (var i = 0; i < this.elements.length; i++) { for (var j = this.elements[i].length; j < 4; j++) { if (i == j) this.elements[i].push(1); else this.elements[i].push(0); } } for (var i = this.elements.length; i < 4; i++) { if (i == 0) this.elements.push([1, 0, 0, 0]); else if (i == 1) this.elements.push([0, 1, 0, 0]); else if (i == 2) this.elements.push([0, 0, 1, 0]); else if (i == 3) this.elements.push([0, 0, 0, 1]); } return this; }; Matrix.prototype.make3x3 = function() { if (this.elements.length != 4 || this.elements[0].length != 4) return null; return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], [this.elements[1][0], this.elements[1][1], this.elements[1][2]], [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); }; Vector.prototype.flatten = function () { return this.elements; }; function mht(m) { var s = ""; if (m.length == 16) { for (var i = 0; i < 4; i++) { s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>"; } } else if (m.length == 9) { for (var i = 0; i < 3; i++) { s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>"; } } else { return m.toString(); } return s; } function makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz) { var eye = $V([ex, ey, ez]); var center = $V([cx, cy, cz]); var up = $V([ux, uy, uz]); var mag; var z = eye.subtract(center).toUnitVector(); var x = up.cross(z).toUnitVector(); var y = z.cross(x).toUnitVector(); var m = $M([[x.e(1), x.e(2), x.e(3), 0], [y.e(1), y.e(2), y.e(3), 0], [z.e(1), z.e(2), z.e(3), 0], [0, 0, 0, 1]]); var t = $M([[1, 0, 0, -ex], [0, 1, 0, -ey], [0, 0, 1, -ez], [0, 0, 0, 1]]); return m.x(t); } function makePerspective(fovy, aspect, znear, zfar) { var ymax = znear * Math.tan(fovy * Math.PI / 360.0); var ymin = -ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); } function makeFrustum(left, right, bottom, top, znear, zfar) { var X = 2*znear/(right-left); var Y = 2*znear/(top-bottom); var A = (right+left)/(right-left); var B = (top+bottom)/(top-bottom); var C = -(zfar+znear)/(zfar-znear); var D = -2*zfar*znear/(zfar-znear); return $M([[X, 0, A, 0], [0, Y, B, 0], [0, 0, C, D], [0, 0, -1, 0]]); } function makeOrtho(left, right, bottom, top, znear, zfar) { var tx = - (right + left) / (right - left); var ty = - (top + bottom) / (top - bottom); var tz = - (zfar + znear) / (zfar - znear); return $M([[2 / (right - left), 0, 0, tx], [0, 2 / (top - bottom), 0, ty], [0, 0, -2 / (zfar - znear), tz], [0, 0, 0, 1]]); } // End of Libaries function initGL(canvas) { try { gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(e) { } if (!gl) { alert("Could not initialise WebGL"); } } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var str = ""; var k = shaderScript.firstChild; while (k) { if (k.nodeType == 3) { str += k.textContent; } k = k.nextSibling; } var shader; if (shaderScript.type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, str); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } function mvPushMatrix(m) { if (m) { mvMatrixStack.push(m.dup()); mvMatrix = m.dup(); } else { mvMatrixStack.push(mvMatrix.dup()); } } function mvPopMatrix() { if (mvMatrixStack.length == 0) { throw "Invalid popMatrix!"; } mvMatrix = mvMatrixStack.pop(); return mvMatrix; } function loadIdentity() { mvMatrix = Matrix.I(4); } function multMatrix(m) { mvMatrix = mvMatrix.x(m); } function mvTranslate(v) { var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } function mvRotate(ang, v) { var arad = ang * Math.PI / 180.0; var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } var pMatrix; function perspective(fovy, aspect, znear, zfar) { pMatrix = makePerspective(fovy, aspect, znear, zfar); } function setMatrixUniforms() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); } function compareXValue(array1, array2) { var value1 = array1[0]; var value2 = array2[0]; if (value1 > value2) return 1; if (value1 < value2) return -1; return 0; } function setupShaders(){ var headID = document.getElementsByTagName("head")[0]; var fsScript = document.createElement('script'); fsScript.id="shader-fs"; fsScript.type = 'x-shader/x-fragment'; fsScript.text = "#ifdef GL_ES\n\ precision highp float;\n\ #endif\n\ varying vec4 vColor;\n\ void main(void) {\n\ gl_FragColor = vColor;\n\ }"; var vsScript = document.createElement('script'); vsScript.id="shader-vs"; vsScript.type = 'x-shader/x-vertex'; vsScript.text = "attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ uniform mat4 uMVMatrix;\n\ uniform mat4 uPMatrix;\n\ \n\ varying vec4 vColor;\n\ \n\ void main(void) {\n\ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\ vColor = aVertexColor;\n\ }"; headID.appendChild(vsScript); headID.appendChild(fsScript); initShaders(); } function setupCanvas(){ canvas1 = document.getElementsByTagName("canvas")[1]; canvas1.style.position = "absolute"; canvas1.style.zIndex = 10; canvas1.style.opacity = 0.5; canvas = document.getElementsByTagName("canvas")[0]; canvas.style.zIndex = 0; initGL(canvas); } function setupGL(){ setupCanvas(); setupShaders(); gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0); loadIdentity(); var uTop = 2.478; var uLeft = -uTop; mvTranslate([uLeft,uTop, -10.0]) mvPushMatrix(); } // Drawing functions function drawPolygon(pixelVertices,color) { var factor; var glWidth = 4.92; var vertices = new Float32Array(1000); var polygonColors = new Float32Array(1000); var vl = 0; if(canvas.width>=canvas.height) factor = glWidth/canvas.height; else factor = glWidth/canvas.width; for(var i=0;i<pixelVertices.length;i++){ pixelVertices[i] = (pixelVertices[i])*factor; if (i%2){ vertices[vl] = -pixelVertices[i]; vl++; vertices[vl] = (4.0); } else { vertices[vl] = (pixelVertices[i]); } vl++; } vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = vl / 3.0; vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); for(var i=0;i<(vl / 3.0)*4;i+=4){ polygonColors[i] = color[0]; polygonColors[i+1] = color[1]; polygonColors[i+2] = color[2]; polygonColors[i+3] = color[3]; } gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = vl / 3.0; gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0); } function drawLine(left1,top1,left2,top2,width,color) { if(top1 <= top2){ var temp1 = left1; var temp2 = top1; left1 = left2; top1 = top2; left2 = temp1; top2 = temp2; } var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1))); var vHeight = top1-top2; var hWidth = left1-left2; var deg = 180/Math.PI; var angle = Math.atan(vHeight/hWidth); var angle2 = ((Math.PI/2)-angle); var height2 = Math.sin(angle2)*(width/2); var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2)); if(angle*deg<0) { var topRightX = left1-(width2); var topRightY = top1-height2; var topLeftX = left1+(width2); var topLeftY = top1+height2; var bottomRightX = left2-(width2); var bottomRightY = top2-height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2+height2; } else { var topRightX = left1-(width2); var topRightY = top1+height2; var topLeftX = left1+(width2); var topLeftY = top1-height2; var bottomRightX = left2-(width2); var bottomRightY = top2+height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2-height2; } var pvertices = new Float32Array([ topRightX, topRightY, topLeftX, topLeftY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY ]); drawPolygon(pvertices,color); } function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);} function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){ var diam = width/2; var topOffset = Math.round(Math.sin(rotation)*diam); var leftOffset = Math.round(Math.cos(rotation)*diam); drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color); } function drawDiamond(left,top,width,height,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(8); pvertices[0] = left; pvertices[1] = top-halfHeight; pvertices[2] = left-halfWidth; pvertices[3] = top; pvertices[4] = left+halfWidth; pvertices[5] = top; pvertices[6] = left; pvertices[7] = top+halfHeight; drawPolygon(pvertices,color); } function drawTriang(left,top,width,height,rotation,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(6); pvertices[0] = 0; pvertices[1] = 0-halfHeight; pvertices[2] = 0-halfWidth; pvertices[3] = 0+halfHeight; pvertices[4] = 0+halfWidth; pvertices[5] = 0+halfHeight; var j = 0; for (i=0;i<3;i++) { var tempX = pvertices[j]; var tempY = pvertices[j+1]; pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+left); j++; pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+top); j++; } drawPolygon(pvertices,color); } function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)}; function drawCircleDim(left,top,width,height,color){ left = Math.round(left); top = Math.round(top); width = Math.round(width); height = Math.round(height); var w = Math.round(width/2); var h = Math.round(height/2); var numSections; if(width>height)numSections = width*2; else numSections = height*2; if(numSections>33)numSections = 33; if(numSections<10)numSections = 10; var delta_theta = 2.0 * Math.PI / numSections var theta = 0 if(circleCoords[w][h]==undefined) { //alert("make circle "+r); circleCoords[w][h] = new Array(numSections); circleCoords[w][h] = new Array(numSections); for (i = 0; i < numSections ; i++) { circleCoords[w][h][i] = new Array(2); x = (w * Math.cos(theta)); y = (h * Math.sin(theta)); x = Math.round(x*1000)/1000 y = Math.round(y*1000)/1000 circleCoords[w][h][i][1] = x; circleCoords[w][h][i][0] = y; theta += delta_theta } circleCoords[w][h].sort(compareXValue); for(var i = 0;i<numSections-1;i++) { if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1]) { temp = circleCoords[w][h][i]; circleCoords[w][h][i] = circleCoords[w][h][i+1]; circleCoords[w][h][i+1] = temp; } } } var j = 0; var pvertices = new Float32Array(numSections*2); for (i=0;i<numSections;i++) { pvertices[j] = circleCoords[w][h][i][1]+left; j++; pvertices[j] = circleCoords[w][h][i][0]+top; j++; } drawPolygon(pvertices,color); } function drawLineArrow(left1,top1,left2,top2,width,color) { var opp = top1-top2; var adj = left1-left2; var angle = Math.atan(opp/adj)+Math.PI/2; if(left1>left2 )angle+=Math.PI; drawLine(left1,top1,left2,top2,width,color); var triLeft = left1-Math.round(adj/2); var triTop = top1-Math.round(opp/2); drawTriang(triLeft,triTop,20,20,angle,color); } function stringPixelLength(string) { var code; var width = 0; for(i=0;i<string.length;i++) { code = string.charCodeAt(i)-32; width += hersheyFont[code][1]; } return width; } function printChar(left,top,character,color,thickness,size) { var code = character.charCodeAt(0)-32; var verticesNeeded = hersheyFont[code][0]; var width = hersheyFont[code][1]; var lef1; var top1; var left2; var top2; var j = 0; var i = 2; var fHeight = 10*size; while(i<(verticesNeeded*2)+2) { j++; left1 = hersheyFont[code][i]*size+left; top1 = (fHeight-hersheyFont[code][i+1]*size)+top; if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1) { if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1) { drawLine(left2,top2,left1,top1,thickness,color); } if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1) { left2 = hersheyFont[code][i+2]*size+left; top2 = (fHeight-hersheyFont[code][i+3]*size)+top; drawLine(left1,top1,left2,top2,thickness,color); } i+=4; } else { i+=2; } } return width*size; } function printString(left,top,string,color,thickness,size) { var wordArray = string.split(" "); var numWords = wordArray.length; var length = (stringPixelLength(string)/2)*size; var offset = -length; for(i=0;i<string.length;i++) { offset += printChar(left+offset,top,string[i],color,thickness,size); } } //Styling functions function getColor(index) { var temp = new Array(4); temp = [colors[index][0],colors[index][1],colors[index][2],1.0] return temp; } function flowTerminator(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; flowTerminatorNoStroke(left,top,width,height,strokeColor); flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color); } function flowTerminatorNoStroke(left,top,width,height,color) { var cWidth = height; var cOff = (width/2)-(cWidth/2); drawCircle(left-cOff,top,cWidth,color); drawCircle(left+cOff,top,cWidth,color); drawSquare(left,top,cOff*2,height,0,color); } function flowProcess(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawSquare(left,top,width,height,0,strokeColor); drawSquare(left,top,width-sOff,height-sOff,0,color); } function diamondStrokeAlgorithm(width, height, strokeSize) { var angle1 = Math.atan(height/width); var angle2 = Math.PI/2 - angle1; var opp = strokeSize*Math.sin(angle2); var width1Sq = (strokeSize*strokeSize)-(opp*opp); var width1 = Math.sqrt(width1Sq); var width2 = opp/(Math.tan(angle1)); var fWidth = (width1+width2)*2; return fWidth; } function flowDecision(left,top,width,height,color,strokeSize,strokeColor) { var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize); var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize); drawDiamond(left,top,width,height,strokeColor); drawDiamond(left,top,width-wOff,height-hOff,color); } // BLACK 0 // WHITE 1 // RED 2 // GREEN 3 // BLUE 4 // YELLOW 5 // PINK 6 // GREY 7 function drawEdge(left1,top1, left2,top2,style){ switch(style){ case 100: // FLOW CHART // Draw line with Arrow at end drawLineArrow(left1,top1,left2,top2,2,getColor(0)); break; case -100: // Draw line with Arrow at end - HIGHLIGHTED drawLineArrow(left1,top1,left2,top2,2,getColor(6)); break; case -10: drawLine(left1,top1,left2,top2,2,getColor(6)); break; default: //Default edge style: black line drawLine(left1,top1,left2,top2,2,getColor(0)); } } function drawVertex(left,top,width,height,style,text,c1,c2,c3) { var flowStrokeHighColor = getColor(5); var flowStrokeColor = getColor(0); var flowColor = getColor(7); var flowStrokeSize = 2; var flowTextColor = getColor(0); var customColor = [c1,c2,c3,1.0]; switch(style){ case 100: // (100 - 199) FLOW CHART SYMBOLS // Terminator, start stop flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -100: // Terminator, start stop - HIGHLIGHTED flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 101: // Process, process or action step flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -101: // Process, process or action step - HIGHLIGHTED flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 102: // Decision, question or branch flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -102: // Decision, question or branch - HIGHLIGHTED flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case -5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeHighColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case 1: // Smiley Face drawCircle(left,top,width,5); drawCircle(left,top,width*0.7,0); drawCircle(left,top,width*0.5,5); drawSquare(left,top,width*0.7,width*0.2,0,5); drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5); drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5); drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5); drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0); drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0); break; case 2: // Bart Simpson drawSquare(left,top,width*0.9,width*1.1,0,0); drawSquare(left,top,width*0.85,width*1.05,0,5); drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0); drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5); drawCircle(left+width*0.15,top+width*0.45,width*0.6,0); drawCircle(left+width*0.15,top+width*0.45,width*0.545,5); drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5); drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5); drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5); drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0) drawCircle(left+width*0.3,top-width*0.1,width*0.4,0); drawCircle(left+width*0.3,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top+width*0.1,width*0.2,0); drawCircle(left+width*0.3,top+width*0.1,width*0.15,5); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5); drawCircle(left+width*0.05,top-width*0.1,width*0.4,0); drawCircle(left+width*0.05,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top-width*0.1,width*0.05,0); drawCircle(left+width*0.05,top-width*0.1,width*0.05,0); break; case -10: drawCircleDim(left,top,width,height,6); break; default: // Default vertex style: black circle drawCircleDim(left,top,width,height,0); } } function drawGraph() { setupGL(); for(var i=0;i<edgeNumber;i++) { var left1 = parseInt(edgeArray[i][0]); var top1 = parseInt(edgeArray[i][1]); var left2 = parseInt(edgeArray[i][2]); var top2 = parseInt(edgeArray[i][3]); var style = parseInt(edgeArray[i][4]); drawEdge( left1,top1,left2,top2,style); } for(var i=0;i<verticeNumber;i++) { var left = parseInt(verticeArray[i][0]); var top = parseInt(verticeArray[i][1]); var width = parseInt(verticeArray[i][2]); var height = parseInt(verticeArray[i][3]); var style = parseInt(verticeArray[i][4]); var text = verticeArray[i][5]; var c1 = verticeArray[i][6]; var c2 = verticeArray[i][7]; var c3 = verticeArray[i][8]; drawVertex(left,top,width,height,style,text,c1,c2,c3); } } drawGraph(); }-*/; private static native int setupJSNI()/*-{ $wnd.edgeNumber = 0; $wnd.verticeNumber = 0; $wnd.edgeArray = new Array(1000); for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5); $wnd.verticeArray = new Array(1000); for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9); }-*/; private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{ edgeArray[edgeNumber][0] = parseInt(startX); edgeArray[edgeNumber][1] = parseInt(startY); edgeArray[edgeNumber][2] = parseInt(endX); edgeArray[edgeNumber][3] = parseInt(endY); edgeArray[edgeNumber][4] = parseInt(style); edgeNumber++; }-*/; private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{ verticeArray[verticeNumber][0] = parseInt(centreX); verticeArray[verticeNumber][1] = parseInt(centreY); verticeArray[verticeNumber][2] = parseInt(width); verticeArray[verticeNumber][3] = parseInt(height); verticeArray[verticeNumber][4] = parseInt(style); verticeArray[verticeNumber][5] = label; verticeArray[verticeNumber][6] = c1; verticeArray[verticeNumber][7] = c1; verticeArray[verticeNumber][8] = c1; verticeNumber++; }-*/; private static native int webglCheck()/*-{ if (typeof Float32Array != "undefined")return 1; return 0; }-*/; public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { // Do a (kind of reliable) check for webgl if (webglCheck() == 1) { // Can do WebGL // At the moment coordinates are passed to JavaScript as comma // separated strings // This will most probably change in the // future. setupJSNI(); String edgesString = ""; String veticesString = ""; String separator = ","; String label = ""; int vertexStyle; int edgeStyle; for (EdgeDrawable thisEdge : edges) { double startX = (thisEdge.getStartX() + offsetX)*zoom; double startY = (thisEdge.getStartY() + offsetY)*zoom; double endX = (thisEdge.getEndX() + offsetX)*zoom; double endY = (thisEdge.getEndY() + offsetY)*zoom; //edgeStyle = thisEdge.getStyle(); edgeStyle = 100; if(thisEdge.isHilighted())edgeStyle = -100; addEdge(startX,startY,endX,endY,edgeStyle); } for (VertexDrawable thisVertex : vertices) { double centreX = (thisVertex.getCenterX() + offsetX)*zoom; double centreY = (thisVertex.getCenterY() + offsetY)*zoom; double width = (0.5 * thisVertex.getWidth())*zoom; double height = (0.5 * thisVertex.getHeight())*zoom; vertexStyle = thisVertex.getStyle(); switch (vertexStyle) { case VertexDrawable.STROKED_TERM_STYLE: vertexStyle = 100; break; case VertexDrawable.STROKED_SQUARE_STYLE: vertexStyle = 101; break; case VertexDrawable.STROKED_DIAMOND_STYLE: vertexStyle = 102; break; default: vertexStyle = 100; break; } label = thisVertex.getLabel(); int[] customColor = {0,0,0}; if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE) { vertexStyle = 5; customColor = thisVertex.getColor(); } if(thisVertex.isHilighted())vertexStyle = -vertexStyle; runJavascript("alert("+vertexStyle+")"); addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]); } // JSNI method used to draw webGL graph version drawGraph3D(); } else { // Cant do webGL so draw on 2d Canvas renderGraph2d(canvas, edges, vertices); } } public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { canvas.setLineWidth(1); canvas.setStrokeStyle(Color.BLACK); canvas.setFillStyle(Color.BLACK); canvas.setFillStyle(Color.WHITE); canvas.fillRect(0, 0, 2000, 2000); canvas.setFillStyle(Color.BLACK); drawGraph(edges, vertices, canvas); } // Draws a single vertex, currently only draws circular nodes private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) { double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom; double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom; double radius = (0.25 * vertex.getWidth()) * zoom; canvas.moveTo(centreX, centreY); canvas.beginPath(); canvas.arc(centreX, centreY, radius, 0, 360, false); canvas.closePath(); canvas.stroke(); canvas.fill(); } // Draws a line from coordinates to other coordinates private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) { double startX = (edge.getStartX() + offsetX)*zoom; double startY = (edge.getStartY() + offsetY)*zoom; double endX = (edge.getEndX() + offsetX)*zoom; double endY = (edge.getEndY() + offsetY)*zoom; canvas.beginPath(); canvas.moveTo(startX, startY); canvas.lineTo(endX, endY); canvas.closePath(); canvas.stroke(); } // Takes collections of edges and vertices and draws a graph on a specified // canvas. private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices, GWTCanvas canvas) { for (EdgeDrawable thisEdge : edges) { drawEdge(thisEdge, canvas); } for (VertexDrawable thisVertex : vertices) { drawVertex(thisVertex, canvas); } } // set offset in the event of a pan public void setOffset(int x, int y) { offsetX = x; offsetY = y; } // getters for offsets public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } //set zoom public void setZoom(double z) { zoom = z; } public double getZoom(){ return zoom; } }
private static native void drawGraph3D() /*-{ var circleCoords = new Array(1000); for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000); var gl; var shaderProgram; var mvMatrix; var mvMatrixStack = []; var colors = [[0.0, 0.0, 0.0], // BLACK 0 [1.0, 1.0, 1.0], // WHITE 1 [1.0, 0.0, 0.0], // RED 2 [0.0, 1.0, 0.0], // GREEN 3 [0.0, 0.0, 1.0], // BLUE 4 [1.0, 1.0, 0.0], // YELLOW 5 [1.0, 0.317, 1.0], // PINK 6 [0.5, 0.5, 0.5], // GREY 7 ]; var hersheyFont=[ [0,16,//Ascii32 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii33 5,21,5,7,-1,-1,5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii34 4,21,4,14,-1,-1,12,21,12,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,21,//Ascii35 11,25,4,-7,-1,-1,17,25,10,-7,-1,-1,4,12,18,12,-1,-1,3,6,17,6,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [26,20,//Ascii36 8,25,8,-4,-1,-1,12,25,12,-4,-1,-1,17,18,15,20,12,21,8,21,5,20,3, 18,3,16,4,14,5,13,7,12,13,10,15,9,16,8,17,6,17,3,15,1,12,0, 8,0,5,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [31,24,//Ascii37 21,21,3,0,-1,-1,8,21,10,19,10,17,9,15,7,14,5,14,3,16,3,18,4, 20,6,21,8,21,10,20,13,19,16,19,19,20,21,21,-1,-1,17,7,15,6,14,4, 14,2,16,0,18,0,20,1,21,3,21,5,19,7,17,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [34,26,//Ascii38 23,12,23,13,22,14,21,14,20,13,19,11,17,6,15,3,13,1,11,0,7,0,5, 1,4,2,3,4,3,6,4,8,5,9,12,13,13,14,14,16,14,18,13,20,11,21, 9,20,8,18,8,16,9,13,11,10,16,3,18,1,20,0,22,0,23,1,23,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii39 5,19,4,20,5,21,6,20,6,18,5,16,4,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii40 11,25,9,23,7,20,5,16,4,11,4,7,5,2,7,-2,9,-5,11,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,14,//Ascii41 3,25,5,23,7,20,9,16,10,11,10,7,9,2,7,-2,5,-5,3,-7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,16,//Ascii42 8,21,8,9,-1,-1,3,18,13,12,-1,-1,13,18,3,12,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii43 13,18,13,0,-1,-1,4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,10,//Ascii44 6,1,5,0,4,1,5,2,6,1,6,-1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,26,//Ascii45 4,9,22,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,10,//Ascii46 5,2,4,1,5,0,6,1,5,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,22,//Ascii47 20,25,2,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii48 9,21,6,20,4,17,3,12,3,9,4,4,6,1,9,0,11,0,14,1,16,4,17, 9,17,12,16,17,14,20,11,21,9,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [4,20,//Ascii49 6,17,8,18,11,21,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,20,//Ascii50 4,16,4,17,5,19,6,20,8,21,12,21,14,20,15,19,16,17,16,15,15,13,13, 10,3,0,17,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,20,//Ascii51 5,21,16,21,10,13,13,13,15,12,16,11,17,8,17,6,16,3,14,1,11,0,8, 0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,20,//Ascii52 13,21,3,7,18,7,-1,-1,13,21,13,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,20,//Ascii53 15,21,5,21,4,12,5,13,8,14,11,14,14,13,16,11,17,8,17,6,16,3,14, 1,11,0,8,0,5,1,4,2,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii54 16,18,15,20,12,21,10,21,7,20,5,17,4,12,4,7,5,3,7,1,10,0,11, 0,14,1,16,3,17,6,17,7,16,10,14,12,11,13,10,13,7,12,5,10,4,7, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii55 17,21,7,0,-1,-1,3,21,17,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [29,20,//Ascii56 8,21,5,20,4,18,4,16,5,14,7,13,11,12,14,11,16,9,17,7,17,4,16, 2,15,1,12,0,8,0,5,1,4,2,3,4,3,7,4,9,6,11,9,12,13,13, 15,14,16,16,16,18,15,20,12,21,8,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,20,//Ascii57 16,14,15,11,13,9,10,8,9,8,6,9,4,11,3,14,3,15,4,18,6,20,9, 21,10,21,13,20,15,18,16,14,16,9,15,4,13,1,10,0,8,0,5,1,4,3, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii58 5,14,4,13,5,12,6,13,5,14,-1,-1,5,2,4,1,5,0,6,1,5,2,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,10,//Ascii59 5,14,4,13,5,12,6,13,5,14,-1,-1,6,1,5,0,4,1,5,2,6,1,6, -1,5,-3,4,-4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii60 20,18,4,9,20,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,26,//Ascii61 4,12,22,12,-1,-1,4,6,22,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [3,24,//Ascii62 4,18,20,9,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,18,//Ascii63 3,16,3,17,4,19,5,20,7,21,11,21,13,20,14,19,15,17,15,15,14,13,13, 12,9,10,9,7,-1,-1,9,2,8,1,9,0,10,1,9,2,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [55,27,//Ascii64 18,13,17,15,15,16,12,16,10,15,9,14,8,11,8,8,9,6,11,5,14,5,16, 6,17,8,-1,-1,12,16,10,14,9,11,9,8,10,6,11,5,-1,-1,18,16,17,8, 17,6,19,5,21,5,23,7,24,10,24,12,23,15,22,17,20,19,18,20,15,21,12, 21,9,20,7,19,5,17,4,15,3,12,3,9,4,6,5,4,7,2,9,1,12,0, 15,0,18,1,20,2,21,3,-1,-1,19,16,18,8,18,6,19,5,], [8,18,//Ascii65 9,21,1,0,-1,-1,9,21,17,0,-1,-1,4,7,14,7,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,21,//Ascii66 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,-1,-1,4,11,13,11,16,10,17,9,18,7,18,4,17,2,16,1,13,0,4,0, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,21,//Ascii67 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [15,21,//Ascii68 4,21,4,0,-1,-1,4,21,11,21,14,20,16,18,17,16,18,13,18,8,17,5,16, 3,14,1,11,0,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,19,//Ascii69 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,4,0,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,18,//Ascii70 4,21,4,0,-1,-1,4,21,17,21,-1,-1,4,11,12,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,21,//Ascii71 18,16,17,18,15,20,13,21,9,21,7,20,5,18,4,16,3,13,3,8,4,5,5, 3,7,1,9,0,13,0,15,1,17,3,18,5,18,8,-1,-1,13,8,18,8,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii72 4,21,4,0,-1,-1,18,21,18,0,-1,-1,4,11,18,11,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii73 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii74 12,21,12,5,11,2,10,1,8,0,6,0,4,1,3,2,2,5,2,7,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,21,//Ascii75 4,21,4,0,-1,-1,18,21,4,7,-1,-1,9,12,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii76 4,21,4,0,-1,-1,4,0,16,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii77 4,21,4,0,-1,-1,4,21,12,0,-1,-1,20,21,12,0,-1,-1,20,21,20,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,22,//Ascii78 4,21,4,0,-1,-1,4,21,18,0,-1,-1,18,21,18,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [21,22,//Ascii79 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [13,21,//Ascii80 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,14,17,12,16,11,13, 10,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [24,22,//Ascii81 9,21,7,20,5,18,4,16,3,13,3,8,4,5,5,3,7,1,9,0,13,0,15, 1,17,3,18,5,19,8,19,13,18,16,17,18,15,20,13,21,9,21,-1,-1,12,4, 18,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [16,21,//Ascii82 4,21,4,0,-1,-1,4,21,13,21,16,20,17,19,18,17,18,15,17,13,16,12,13, 11,4,11,-1,-1,11,11,18,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [20,20,//Ascii83 17,18,15,20,12,21,8,21,5,20,3,18,3,16,4,14,5,13,7,12,13,10,15, 9,16,8,17,6,17,3,15,1,12,0,8,0,5,1,3,3,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii84 8,21,8,0,-1,-1,1,21,15,21,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,22,//Ascii85 4,21,4,6,5,3,7,1,10,0,12,0,15,1,17,3,18,6,18,21,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,18,//Ascii86 1,21,9,0,-1,-1,17,21,9,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,24,//Ascii87 2,21,7,0,-1,-1,12,21,7,0,-1,-1,12,21,17,0,-1,-1,22,21,17,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,20,//Ascii88 3,21,17,0,-1,-1,17,21,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [6,18,//Ascii89 1,21,9,11,9,0,-1,-1,17,21,9,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,20,//Ascii90 17,21,3,0,-1,-1,3,21,17,21,-1,-1,3,0,17,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii91 4,25,4,-7,-1,-1,5,25,5,-7,-1,-1,4,25,11,25,-1,-1,4,-7,11,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,14,//Ascii92 0,21,14,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,14,//Ascii93 9,25,9,-7,-1,-1,10,25,10,-7,-1,-1,3,25,10,25,-1,-1,3,-7,10,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,16,//Ascii94 6,15,8,18,10,15,-1,-1,3,12,8,17,13,12,-1,-1,8,17,8,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,16,//Ascii95 0,-2,16,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [7,10,//Ascii96 6,21,5,20,4,18,4,16,5,15,6,16,5,17,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii97 15,14,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii98 4,21,4,0,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [14,18,//Ascii99 15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11, 0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii100 15,21,15,0,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,18,//Ascii101 3,8,15,8,15,10,14,12,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii102 10,21,8,21,6,20,5,17,5,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [22,19,//Ascii103 15,14,15,-2,14,-5,13,-6,11,-7,8,-7,6,-6,-1,-1,15,11,13,13,11,14,8, 14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii104 4,21,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,8,//Ascii105 3,21,4,20,5,21,4,22,3,21,-1,-1,4,14,4,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,10,//Ascii106 5,21,6,20,7,21,6,22,5,21,-1,-1,6,14,6,-3,5,-6,3,-7,1,-7,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii107 4,21,4,0,-1,-1,14,14,4,4,-1,-1,8,8,15,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii108 4,21,4,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [18,30,//Ascii109 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,15, 10,18,13,20,14,23,14,25,13,26,10,26,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii110 4,14,4,0,-1,-1,4,10,7,13,9,14,12,14,14,13,15,10,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii111 8,14,6,13,4,11,3,8,3,6,4,3,6,1,8,0,11,0,13,1,15,3,16, 6,16,8,15,11,13,13,11,14,8,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii112 4,14,4,-7,-1,-1,4,11,6,13,8,14,11,14,13,13,15,11,16,8,16,6,15, 3,13,1,11,0,8,0,6,1,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,19,//Ascii113 15,14,15,-7,-1,-1,15,11,13,13,11,14,8,14,6,13,4,11,3,8,3,6,4, 3,6,1,8,0,11,0,13,1,15,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,13,//Ascii114 4,14,4,0,-1,-1,4,8,5,11,7,13,9,14,12,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [17,17,//Ascii115 14,11,13,13,10,14,7,14,4,13,3,11,4,9,6,8,11,7,13,6,14,4,14, 3,13,1,10,0,7,0,4,1,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,12,//Ascii116 5,21,5,4,6,1,8,0,10,0,-1,-1,2,14,9,14,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [10,19,//Ascii117 4,14,4,4,5,1,7,0,10,0,12,1,15,4,-1,-1,15,14,15,0,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,16,//Ascii118 2,14,8,0,-1,-1,14,14,8,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [11,22,//Ascii119 3,14,7,0,-1,-1,11,14,7,0,-1,-1,11,14,15,0,-1,-1,19,14,15,0,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [5,17,//Ascii120 3,14,14,0,-1,-1,14,14,3,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [9,16,//Ascii121 2,14,8,0,-1,-1,14,14,8,0,6,-4,4,-6,2,-7,1,-7,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [8,17,//Ascii122 14,14,3,0,-1,-1,3,14,14,14,-1,-1,3,0,14,0,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii123 9,25,7,24,6,23,5,21,5,19,6,17,7,16,8,14,8,12,6,10,-1,-1,7, 24,6,22,6,20,7,18,8,17,9,15,9,13,8,11,4,9,8,7,9,5,9,3, 8,1,7,0,6,-2,6,-4,7,-6,-1,-1,6,8,8,6,8,4,7,2,6,1,5, -1,5,-3,6,-5,7,-6,9,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [2,8,//Ascii124 4,25,4,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [39,14,//Ascii125 5,25,7,24,8,23,9,21,9,19,8,17,7,16,6,14,6,12,8,10,-1,-1,7, 24,8,22,8,20,7,18,6,17,5,15,5,13,6,11,10,9,6,7,5,5,5,3, 6,1,7,0,8,-2,8,-4,7,-6,-1,-1,8,8,6,6,6,4,7,2,8,1,9, -1,9,-3,8,-5,7,-6,5,-7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,], [23,24,//Ascii126 3,6,3,8,4,11,6,12,8,12,10,11,14,8,16,7,18,7,20,8,21,10,-1, -1,3,8,4,10,6,11,8,11,10,10,14,7,16,6,18,6,20,7,21,10,21,12, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,] ]; // Sylvester.js Libary eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{})) // gtUtils.js Libary Matrix.Translation = function (v) { if (v.elements.length == 2) { var r = Matrix.I(3); r.elements[2][0] = v.elements[0]; r.elements[2][1] = v.elements[1]; return r; } if (v.elements.length == 3) { var r = Matrix.I(4); r.elements[0][3] = v.elements[0]; r.elements[1][3] = v.elements[1]; r.elements[2][3] = v.elements[2]; return r; } throw "Invalid length for Translation"; } Matrix.prototype.flatten = function () { var result = []; if (this.elements.length == 0) return []; for (var j = 0; j < this.elements[0].length; j++) for (var i = 0; i < this.elements.length; i++) result.push(this.elements[i][j]); return result; } Matrix.prototype.ensure4x4 = function() { if (this.elements.length == 4 && this.elements[0].length == 4) return this; if (this.elements.length > 4 || this.elements[0].length > 4) return null; for (var i = 0; i < this.elements.length; i++) { for (var j = this.elements[i].length; j < 4; j++) { if (i == j) this.elements[i].push(1); else this.elements[i].push(0); } } for (var i = this.elements.length; i < 4; i++) { if (i == 0) this.elements.push([1, 0, 0, 0]); else if (i == 1) this.elements.push([0, 1, 0, 0]); else if (i == 2) this.elements.push([0, 0, 1, 0]); else if (i == 3) this.elements.push([0, 0, 0, 1]); } return this; }; Matrix.prototype.make3x3 = function() { if (this.elements.length != 4 || this.elements[0].length != 4) return null; return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], [this.elements[1][0], this.elements[1][1], this.elements[1][2]], [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); }; Vector.prototype.flatten = function () { return this.elements; }; function mht(m) { var s = ""; if (m.length == 16) { for (var i = 0; i < 4; i++) { s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>"; } } else if (m.length == 9) { for (var i = 0; i < 3; i++) { s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>"; } } else { return m.toString(); } return s; } function makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz) { var eye = $V([ex, ey, ez]); var center = $V([cx, cy, cz]); var up = $V([ux, uy, uz]); var mag; var z = eye.subtract(center).toUnitVector(); var x = up.cross(z).toUnitVector(); var y = z.cross(x).toUnitVector(); var m = $M([[x.e(1), x.e(2), x.e(3), 0], [y.e(1), y.e(2), y.e(3), 0], [z.e(1), z.e(2), z.e(3), 0], [0, 0, 0, 1]]); var t = $M([[1, 0, 0, -ex], [0, 1, 0, -ey], [0, 0, 1, -ez], [0, 0, 0, 1]]); return m.x(t); } function makePerspective(fovy, aspect, znear, zfar) { var ymax = znear * Math.tan(fovy * Math.PI / 360.0); var ymin = -ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); } function makeFrustum(left, right, bottom, top, znear, zfar) { var X = 2*znear/(right-left); var Y = 2*znear/(top-bottom); var A = (right+left)/(right-left); var B = (top+bottom)/(top-bottom); var C = -(zfar+znear)/(zfar-znear); var D = -2*zfar*znear/(zfar-znear); return $M([[X, 0, A, 0], [0, Y, B, 0], [0, 0, C, D], [0, 0, -1, 0]]); } function makeOrtho(left, right, bottom, top, znear, zfar) { var tx = - (right + left) / (right - left); var ty = - (top + bottom) / (top - bottom); var tz = - (zfar + znear) / (zfar - znear); return $M([[2 / (right - left), 0, 0, tx], [0, 2 / (top - bottom), 0, ty], [0, 0, -2 / (zfar - znear), tz], [0, 0, 0, 1]]); } // End of Libaries function initGL(canvas) { try { gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(e) { } if (!gl) { alert("Could not initialise WebGL"); } } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var str = ""; var k = shaderScript.firstChild; while (k) { if (k.nodeType == 3) { str += k.textContent; } k = k.nextSibling; } var shader; if (shaderScript.type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, str); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } function mvPushMatrix(m) { if (m) { mvMatrixStack.push(m.dup()); mvMatrix = m.dup(); } else { mvMatrixStack.push(mvMatrix.dup()); } } function mvPopMatrix() { if (mvMatrixStack.length == 0) { throw "Invalid popMatrix!"; } mvMatrix = mvMatrixStack.pop(); return mvMatrix; } function loadIdentity() { mvMatrix = Matrix.I(4); } function multMatrix(m) { mvMatrix = mvMatrix.x(m); } function mvTranslate(v) { var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } function mvRotate(ang, v) { var arad = ang * Math.PI / 180.0; var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } var pMatrix; function perspective(fovy, aspect, znear, zfar) { pMatrix = makePerspective(fovy, aspect, znear, zfar); } function setMatrixUniforms() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); } function compareXValue(array1, array2) { var value1 = array1[0]; var value2 = array2[0]; if (value1 > value2) return 1; if (value1 < value2) return -1; return 0; } function setupShaders(){ var headID = document.getElementsByTagName("head")[0]; var fsScript = document.createElement('script'); fsScript.id="shader-fs"; fsScript.type = 'x-shader/x-fragment'; fsScript.text = "#ifdef GL_ES\n\ precision highp float;\n\ #endif\n\ varying vec4 vColor;\n\ void main(void) {\n\ gl_FragColor = vColor;\n\ }"; var vsScript = document.createElement('script'); vsScript.id="shader-vs"; vsScript.type = 'x-shader/x-vertex'; vsScript.text = "attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ uniform mat4 uMVMatrix;\n\ uniform mat4 uPMatrix;\n\ \n\ varying vec4 vColor;\n\ \n\ void main(void) {\n\ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\ vColor = aVertexColor;\n\ }"; headID.appendChild(vsScript); headID.appendChild(fsScript); initShaders(); } function setupCanvas(){ canvas1 = document.getElementsByTagName("canvas")[1]; canvas1.style.position = "absolute"; canvas1.style.zIndex = 10; canvas1.style.opacity = 0.5; canvas = document.getElementsByTagName("canvas")[0]; canvas.style.zIndex = 0; initGL(canvas); } function setupGL(){ setupCanvas(); setupShaders(); gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0); loadIdentity(); var uTop = 2.478; var uLeft = -uTop; mvTranslate([uLeft,uTop, -10.0]) mvPushMatrix(); } // Drawing functions function drawPolygon(pixelVertices,color) { var factor; var glWidth = 4.92; var vertices = new Float32Array(1000); var polygonColors = new Float32Array(1000); var vl = 0; if(canvas.width>=canvas.height) factor = glWidth/canvas.height; else factor = glWidth/canvas.width; for(var i=0;i<pixelVertices.length;i++){ pixelVertices[i] = (pixelVertices[i])*factor; if (i%2){ vertices[vl] = -pixelVertices[i]; vl++; vertices[vl] = (4.0); } else { vertices[vl] = (pixelVertices[i]); } vl++; } vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = vl / 3.0; vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); for(var i=0;i<(vl / 3.0)*4;i+=4){ polygonColors[i] = color[0]; polygonColors[i+1] = color[1]; polygonColors[i+2] = color[2]; polygonColors[i+3] = color[3]; } gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = vl / 3.0; gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0); } function drawLine(left1,top1,left2,top2,width,color) { if(top1 <= top2){ var temp1 = left1; var temp2 = top1; left1 = left2; top1 = top2; left2 = temp1; top2 = temp2; } var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1))); var vHeight = top1-top2; var hWidth = left1-left2; var deg = 180/Math.PI; var angle = Math.atan(vHeight/hWidth); var angle2 = ((Math.PI/2)-angle); var height2 = Math.sin(angle2)*(width/2); var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2)); if(angle*deg<0) { var topRightX = left1-(width2); var topRightY = top1-height2; var topLeftX = left1+(width2); var topLeftY = top1+height2; var bottomRightX = left2-(width2); var bottomRightY = top2-height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2+height2; } else { var topRightX = left1-(width2); var topRightY = top1+height2; var topLeftX = left1+(width2); var topLeftY = top1-height2; var bottomRightX = left2-(width2); var bottomRightY = top2+height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2-height2; } var pvertices = new Float32Array([ topRightX, topRightY, topLeftX, topLeftY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY ]); drawPolygon(pvertices,color); } function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);} function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){ var diam = width/2; var topOffset = Math.round(Math.sin(rotation)*diam); var leftOffset = Math.round(Math.cos(rotation)*diam); drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color); } function drawDiamond(left,top,width,height,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(8); pvertices[0] = left; pvertices[1] = top-halfHeight; pvertices[2] = left-halfWidth; pvertices[3] = top; pvertices[4] = left+halfWidth; pvertices[5] = top; pvertices[6] = left; pvertices[7] = top+halfHeight; drawPolygon(pvertices,color); } function drawTriang(left,top,width,height,rotation,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(6); pvertices[0] = 0; pvertices[1] = 0-halfHeight; pvertices[2] = 0-halfWidth; pvertices[3] = 0+halfHeight; pvertices[4] = 0+halfWidth; pvertices[5] = 0+halfHeight; var j = 0; for (i=0;i<3;i++) { var tempX = pvertices[j]; var tempY = pvertices[j+1]; pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+left); j++; pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+top); j++; } drawPolygon(pvertices,color); } function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)}; function drawCircleDim(left,top,width,height,color){ left = Math.round(left); top = Math.round(top); width = Math.round(width); height = Math.round(height); var w = Math.round(width/2); var h = Math.round(height/2); var numSections; if(width>height)numSections = width*2; else numSections = height*2; if(numSections>33)numSections = 33; if(numSections<10)numSections = 10; var delta_theta = 2.0 * Math.PI / numSections var theta = 0 if(circleCoords[w][h]==undefined) { //alert("make circle "+r); circleCoords[w][h] = new Array(numSections); circleCoords[w][h] = new Array(numSections); for (i = 0; i < numSections ; i++) { circleCoords[w][h][i] = new Array(2); x = (w * Math.cos(theta)); y = (h * Math.sin(theta)); x = Math.round(x*1000)/1000 y = Math.round(y*1000)/1000 circleCoords[w][h][i][1] = x; circleCoords[w][h][i][0] = y; theta += delta_theta } circleCoords[w][h].sort(compareXValue); for(var i = 0;i<numSections-1;i++) { if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1]) { temp = circleCoords[w][h][i]; circleCoords[w][h][i] = circleCoords[w][h][i+1]; circleCoords[w][h][i+1] = temp; } } } var j = 0; var pvertices = new Float32Array(numSections*2); for (i=0;i<numSections;i++) { pvertices[j] = circleCoords[w][h][i][1]+left; j++; pvertices[j] = circleCoords[w][h][i][0]+top; j++; } drawPolygon(pvertices,color); } function drawLineArrow(left1,top1,left2,top2,width,color) { var opp = top1-top2; var adj = left1-left2; var angle = Math.atan(opp/adj)+Math.PI/2; if(left1>left2 )angle+=Math.PI; drawLine(left1,top1,left2,top2,width,color); var triLeft = left1-Math.round(adj/2); var triTop = top1-Math.round(opp/2); drawTriang(triLeft,triTop,20,20,angle,color); } function stringPixelLength(string) { var code; var width = 0; for(i=0;i<string.length;i++) { code = string.charCodeAt(i)-32; width += hersheyFont[code][1]; } return width; } function printChar(left,top,character,color,thickness,size) { var code = character.charCodeAt(0)-32; var verticesNeeded = hersheyFont[code][0]; var width = hersheyFont[code][1]; var lef1; var top1; var left2; var top2; var j = 0; var i = 2; var fHeight = 10*size; while(i<(verticesNeeded*2)+2) { j++; left1 = hersheyFont[code][i]*size+left; top1 = (fHeight-hersheyFont[code][i+1]*size)+top; if(hersheyFont[code][i] != -1 && hersheyFont[code][i+1] != -1) { if(i>2 && hersheyFont[code][i-1] != -1 && hersheyFont[code][i-2] != -1) { drawLine(left2,top2,left1,top1,thickness,color); } if(hersheyFont[code][i+2] != -1 && hersheyFont[code][i+3] != -1) { left2 = hersheyFont[code][i+2]*size+left; top2 = (fHeight-hersheyFont[code][i+3]*size)+top; drawLine(left1,top1,left2,top2,thickness,color); } i+=4; } else { i+=2; } } return width*size; } function printString(left,top,string,color,thickness,size) { var wordArray = string.split(" "); var numWords = wordArray.length; var length = (stringPixelLength(string)/2)*size; var offset = -length; for(i=0;i<string.length;i++) { offset += printChar(left+offset,top,string[i],color,thickness,size); } } //Styling functions function getColor(index) { var temp = new Array(4); temp = [colors[index][0],colors[index][1],colors[index][2],1.0] return temp; } function flowTerminator(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; flowTerminatorNoStroke(left,top,width,height,strokeColor); flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color); } function flowTerminatorNoStroke(left,top,width,height,color) { var cWidth = height; var cOff = (width/2)-(cWidth/2); drawCircle(left-cOff,top,cWidth,color); drawCircle(left+cOff,top,cWidth,color); drawSquare(left,top,cOff*2,height,0,color); } function flowProcess(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawSquare(left,top,width,height,0,strokeColor); drawSquare(left,top,width-sOff,height-sOff,0,color); } function diamondStrokeAlgorithm(width, height, strokeSize) { var angle1 = Math.atan(height/width); var angle2 = Math.PI/2 - angle1; var opp = strokeSize*Math.sin(angle2); var width1Sq = (strokeSize*strokeSize)-(opp*opp); var width1 = Math.sqrt(width1Sq); var width2 = opp/(Math.tan(angle1)); var fWidth = (width1+width2)*2; return fWidth; } function flowDecision(left,top,width,height,color,strokeSize,strokeColor) { var wOff = diamondStrokeAlgorithm(width/2, height/2, strokeSize); var hOff = diamondStrokeAlgorithm(height/2, width/2, strokeSize); drawDiamond(left,top,width,height,strokeColor); drawDiamond(left,top,width-wOff,height-hOff,color); } // BLACK 0 // WHITE 1 // RED 2 // GREEN 3 // BLUE 4 // YELLOW 5 // PINK 6 // GREY 7 function drawEdge(left1,top1, left2,top2,style){ switch(style){ case 100: // FLOW CHART // Draw line with Arrow at end drawLineArrow(left1,top1,left2,top2,2,getColor(0)); break; case -100: // Draw line with Arrow at end - HIGHLIGHTED drawLineArrow(left1,top1,left2,top2,2,getColor(6)); break; case -10: drawLine(left1,top1,left2,top2,2,getColor(6)); break; default: //Default edge style: black line drawLine(left1,top1,left2,top2,2,getColor(0)); } } function drawVertex(left,top,width,height,style,text,c1,c2,c3) { var flowStrokeHighColor = getColor(5); var flowStrokeColor = getColor(0); var flowColor = getColor(7); var flowStrokeSize = 2; var flowTextColor = getColor(0); var customColor = [c1,c2,c3,1.0]; switch(style){ case 100: // (100 - 199) FLOW CHART SYMBOLS // Terminator, start stop flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -100: // Terminator, start stop - HIGHLIGHTED flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 101: // Process, process or action step flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -101: // Process, process or action step - HIGHLIGHTED flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 102: // Decision, question or branch flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); printString(left,top,text,flowTextColor,2,0.75); break; case -102: // Decision, question or branch - HIGHLIGHTED flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); printString(left,top,text,flowTextColor,2,0.75); break; case 5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case -5: // Circle var sOff = flowStrokeSize*2; drawCircleDim(left,top,width,height,flowStrokeHighColor); drawCircleDim(left,top,width-sOff,height-sOff,customColor); printString(left,top,text,flowTextColor,2,0.75); break; case 1: // Smiley Face drawCircle(left,top,width,5); drawCircle(left,top,width*0.7,0); drawCircle(left,top,width*0.5,5); drawSquare(left,top,width*0.7,width*0.2,0,5); drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5); drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5); drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5); drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0); drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0); break; case 2: // Bart Simpson drawSquare(left,top,width*0.9,width*1.1,0,0); drawSquare(left,top,width*0.85,width*1.05,0,5); drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0); drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5); drawCircle(left+width*0.15,top+width*0.45,width*0.6,0); drawCircle(left+width*0.15,top+width*0.45,width*0.545,5); drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5); drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5); drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5); drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0) drawCircle(left+width*0.3,top-width*0.1,width*0.4,0); drawCircle(left+width*0.3,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top+width*0.1,width*0.2,0); drawCircle(left+width*0.3,top+width*0.1,width*0.15,5); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5); drawCircle(left+width*0.05,top-width*0.1,width*0.4,0); drawCircle(left+width*0.05,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top-width*0.1,width*0.05,0); drawCircle(left+width*0.05,top-width*0.1,width*0.05,0); break; case -10: drawCircleDim(left,top,width,height,6); break; default: // Default vertex style: black circle drawCircleDim(left,top,width,height,0); } } function drawGraph() { setupGL(); for(var i=0;i<edgeNumber;i++) { var left1 = parseInt(edgeArray[i][0]); var top1 = parseInt(edgeArray[i][1]); var left2 = parseInt(edgeArray[i][2]); var top2 = parseInt(edgeArray[i][3]); var style = parseInt(edgeArray[i][4]); drawEdge( left1,top1,left2,top2,style); } for(var i=0;i<verticeNumber;i++) { var left = parseInt(verticeArray[i][0]); var top = parseInt(verticeArray[i][1]); var width = parseInt(verticeArray[i][2]); var height = parseInt(verticeArray[i][3]); var style = parseInt(verticeArray[i][4]); var text = verticeArray[i][5]; var c1 = verticeArray[i][6]; var c2 = verticeArray[i][7]; var c3 = verticeArray[i][8]; drawVertex(left,top,width,height,style,text,c1,c2,c3); } } drawGraph(); }-*/; private static native int setupJSNI()/*-{ $wnd.edgeNumber = 0; $wnd.verticeNumber = 0; $wnd.edgeArray = new Array(1000); for(i=0;i<edgeArray.length;i++)edgeArray[i] = new Array(5); $wnd.verticeArray = new Array(1000); for(i=0;i<verticeArray.length;i++)verticeArray[i] = new Array(9); }-*/; private static native int addEdge(double startX,double startY,double endX,double endY,int style)/*-{ edgeArray[edgeNumber][0] = parseInt(startX); edgeArray[edgeNumber][1] = parseInt(startY); edgeArray[edgeNumber][2] = parseInt(endX); edgeArray[edgeNumber][3] = parseInt(endY); edgeArray[edgeNumber][4] = parseInt(style); edgeNumber++; }-*/; private static native int addVertice(double centreX,double centreY,double width,double height,int style,String label,double c1,double c2,double c3)/*-{ verticeArray[verticeNumber][0] = parseInt(centreX); verticeArray[verticeNumber][1] = parseInt(centreY); verticeArray[verticeNumber][2] = parseInt(width); verticeArray[verticeNumber][3] = parseInt(height); verticeArray[verticeNumber][4] = parseInt(style); verticeArray[verticeNumber][5] = label; verticeArray[verticeNumber][6] = c1; verticeArray[verticeNumber][7] = c1; verticeArray[verticeNumber][8] = c1; verticeNumber++; }-*/; private static native int webglCheck()/*-{ if (typeof Float32Array != "undefined")return 1; return 0; }-*/; public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { // Do a (kind of reliable) check for webgl if (webglCheck() == 1) { // Can do WebGL // At the moment coordinates are passed to JavaScript as comma // separated strings // This will most probably change in the // future. setupJSNI(); String edgesString = ""; String veticesString = ""; String separator = ","; String label = ""; int vertexStyle; int edgeStyle; for (EdgeDrawable thisEdge : edges) { double startX = (thisEdge.getStartX() + offsetX)*zoom; double startY = (thisEdge.getStartY() + offsetY)*zoom; double endX = (thisEdge.getEndX() + offsetX)*zoom; double endY = (thisEdge.getEndY() + offsetY)*zoom; //edgeStyle = thisEdge.getStyle(); edgeStyle = 100; if(thisEdge.isHilighted())edgeStyle = -100; addEdge(startX,startY,endX,endY,edgeStyle); } for (VertexDrawable thisVertex : vertices) { double centreX = (thisVertex.getCenterX() + offsetX)*zoom; double centreY = (thisVertex.getCenterY() + offsetY)*zoom; double width = (0.5 * thisVertex.getWidth())*zoom; double height = (0.5 * thisVertex.getHeight())*zoom; vertexStyle = thisVertex.getStyle(); switch (vertexStyle) { case VertexDrawable.STROKED_TERM_STYLE: vertexStyle = 100; break; case VertexDrawable.STROKED_SQUARE_STYLE: vertexStyle = 101; break; case VertexDrawable.STROKED_DIAMOND_STYLE: vertexStyle = 102; break; default: vertexStyle = 100; break; } label = thisVertex.getLabel(); int[] customColor = {0,0,0}; if(thisVertex.getStyle() == VertexDrawable.COLORED_FILLED_CIRCLE) { vertexStyle = 5; customColor = thisVertex.getColor(); } if(thisVertex.isHilighted())vertexStyle = -vertexStyle; addVertice(centreX,centreY,width,height,vertexStyle,label,customColor[0],customColor[1],customColor[2]); } // JSNI method used to draw webGL graph version drawGraph3D(); } else { // Cant do webGL so draw on 2d Canvas renderGraph2d(canvas, edges, vertices); } } public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { canvas.setLineWidth(1); canvas.setStrokeStyle(Color.BLACK); canvas.setFillStyle(Color.BLACK); canvas.setFillStyle(Color.WHITE); canvas.fillRect(0, 0, 2000, 2000); canvas.setFillStyle(Color.BLACK); drawGraph(edges, vertices, canvas); } // Draws a single vertex, currently only draws circular nodes private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) { double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom; double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom; double radius = (0.25 * vertex.getWidth()) * zoom; canvas.moveTo(centreX, centreY); canvas.beginPath(); canvas.arc(centreX, centreY, radius, 0, 360, false); canvas.closePath(); canvas.stroke(); canvas.fill(); } // Draws a line from coordinates to other coordinates private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) { double startX = (edge.getStartX() + offsetX)*zoom; double startY = (edge.getStartY() + offsetY)*zoom; double endX = (edge.getEndX() + offsetX)*zoom; double endY = (edge.getEndY() + offsetY)*zoom; canvas.beginPath(); canvas.moveTo(startX, startY); canvas.lineTo(endX, endY); canvas.closePath(); canvas.stroke(); } // Takes collections of edges and vertices and draws a graph on a specified // canvas. private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices, GWTCanvas canvas) { for (EdgeDrawable thisEdge : edges) { drawEdge(thisEdge, canvas); } for (VertexDrawable thisVertex : vertices) { drawVertex(thisVertex, canvas); } } // set offset in the event of a pan public void setOffset(int x, int y) { offsetX = x; offsetY = y; } // getters for offsets public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } //set zoom public void setZoom(double z) { zoom = z; } public double getZoom(){ return zoom; } }
diff --git a/lib/src/com/garlicg/cutinlib/CutinService.java b/lib/src/com/garlicg/cutinlib/CutinService.java index 87de58b..63e0923 100644 --- a/lib/src/com/garlicg/cutinlib/CutinService.java +++ b/lib/src/com/garlicg/cutinlib/CutinService.java @@ -1,82 +1,82 @@ package com.garlicg.cutinlib; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.os.Handler; import android.os.IBinder; import android.view.View; import android.view.WindowManager; public abstract class CutinService extends Service { private View mLayout; private WindowManager mWindowManager; private boolean mStarted = false; protected abstract View create(); protected abstract void start(); protected abstract void destroy(); @Override final public IBinder onBind(Intent arg0) { return null; } @Override final public void onCreate() { super.onCreate(); mLayout = create(); if (mLayout == null) { - throw new NullPointerException("Create view return null."); + throw new NullPointerException("CutinService#create need to return view."); } WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_FULLSCREEN, PixelFormat.TRANSLUCENT); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); mWindowManager.addView(mLayout, params); } @Override final public int onStartCommand(Intent intent, int flags, final int startId) { if (!mStarted) { mStarted = true; new Handler().post(new Runnable() { @Override public void run() { start(); } }); } else { reStart(); } return START_NOT_STICKY; } protected void reStart() { } protected void finishCutin() { stopSelf(); } @Override public void onDestroy() { super.onDestroy(); destroy(); if (mLayout != null) { mWindowManager.removeView(mLayout); } } }
true
true
final public void onCreate() { super.onCreate(); mLayout = create(); if (mLayout == null) { throw new NullPointerException("Create view return null."); } WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_FULLSCREEN, PixelFormat.TRANSLUCENT); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); mWindowManager.addView(mLayout, params); }
final public void onCreate() { super.onCreate(); mLayout = create(); if (mLayout == null) { throw new NullPointerException("CutinService#create need to return view."); } WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_FULLSCREEN, PixelFormat.TRANSLUCENT); mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); mWindowManager.addView(mLayout, params); }
diff --git a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/FileAuxiliary.java b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/FileAuxiliary.java index 90d225a87..22d027bfb 100644 --- a/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/FileAuxiliary.java +++ b/common/plugins/org.jboss.tools.common.model/src/org/jboss/tools/common/model/filesystems/FileAuxiliary.java @@ -1,72 +1,73 @@ /******************************************************************************* * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Exadel, Inc. and Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.common.model.filesystems; import org.jboss.tools.common.model.*; import org.jboss.tools.common.model.filesystems.impl.*; public class FileAuxiliary { public static String AUX_FILE_ENTITY = "FileAnyAuxiliary"; String extension = ""; boolean replaceExtension = true; boolean addLeadingDot = true; public FileAuxiliary(String extension, boolean replaceExtension) { this.extension = extension; this.replaceExtension = replaceExtension; } public String read(XModelObject folder, XModelObject main) { FileAnyAuxiliaryImpl f = getAuxiliaryFile(folder, main, false); if(f == null) return null; BodySource bs = f.getBodySource(); return (bs == null) ? null : bs.get(); } public boolean write(XModelObject folder, XModelObject main, XModelObject object) { FileAnyAuxiliaryImpl f = getAuxiliaryFile(folder, main, true); if(f == null) return false; BodySource bs = f.getBodySource(); return (bs != null && bs.write(object)); } public FileAnyAuxiliaryImpl getAuxiliaryFile(XModelObject folder, XModelObject main, boolean create) { - String name = getAuxiliaryName(main); + if(folder==null) return null; + String name = getAuxiliaryName(main); String p = name + "." + extension; XModelObject f = folder.getChildByPath(p); if(!(f instanceof FileAnyAuxiliaryImpl)) { if(!create) return null; f = folder.getModel().createModelObject(AUX_FILE_ENTITY, null); f.setAttributeValue("name", name); f.setAttributeValue("extension", extension); folder.addChild(f); } FileAnyAuxiliaryImpl aux = (FileAnyAuxiliaryImpl)f; aux.setMainObject(main); aux.setAuxiliaryHelper(this); return aux; } public String getMainName(XModelObject aux) { String auxname = aux.getAttributeValue("name"); if(replaceExtension) return auxname; int i = auxname.lastIndexOf('.'); return (i < 0) ? auxname : auxname.substring(0, i); } public String getAuxiliaryName(XModelObject main) { String name = main.getAttributeValue("name"); if(!replaceExtension) name += "." + main.getAttributeValue("extension"); if(addLeadingDot) name = "." + name; return name; } }
true
true
public FileAnyAuxiliaryImpl getAuxiliaryFile(XModelObject folder, XModelObject main, boolean create) { String name = getAuxiliaryName(main); String p = name + "." + extension; XModelObject f = folder.getChildByPath(p); if(!(f instanceof FileAnyAuxiliaryImpl)) { if(!create) return null; f = folder.getModel().createModelObject(AUX_FILE_ENTITY, null); f.setAttributeValue("name", name); f.setAttributeValue("extension", extension); folder.addChild(f); } FileAnyAuxiliaryImpl aux = (FileAnyAuxiliaryImpl)f; aux.setMainObject(main); aux.setAuxiliaryHelper(this); return aux; }
public FileAnyAuxiliaryImpl getAuxiliaryFile(XModelObject folder, XModelObject main, boolean create) { if(folder==null) return null; String name = getAuxiliaryName(main); String p = name + "." + extension; XModelObject f = folder.getChildByPath(p); if(!(f instanceof FileAnyAuxiliaryImpl)) { if(!create) return null; f = folder.getModel().createModelObject(AUX_FILE_ENTITY, null); f.setAttributeValue("name", name); f.setAttributeValue("extension", extension); folder.addChild(f); } FileAnyAuxiliaryImpl aux = (FileAnyAuxiliaryImpl)f; aux.setMainObject(main); aux.setAuxiliaryHelper(this); return aux; }
diff --git a/src/java/org/apache/hadoop/dfs/FSNamesystem.java b/src/java/org/apache/hadoop/dfs/FSNamesystem.java index f81c3462a..d7b6f4631 100644 --- a/src/java/org/apache/hadoop/dfs/FSNamesystem.java +++ b/src/java/org/apache/hadoop/dfs/FSNamesystem.java @@ -1,1339 +1,1339 @@ /** * Copyright 2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.dfs; import org.apache.hadoop.io.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.util.*; import java.io.*; import java.util.*; import java.util.logging.*; /*************************************************** * FSNamesystem does the actual bookkeeping work for the * DataNode. * * It tracks several important tables. * * 1) valid fsname --> blocklist (kept on disk, logged) * 2) Set of all valid blocks (inverted #1) * 3) block --> machinelist (kept in memory, rebuilt dynamically from reports) * 4) machine --> blocklist (inverted #2) * 5) LRU cache of updated-heartbeat machines ***************************************************/ class FSNamesystem implements FSConstants { public static final Logger LOG = LogFormatter.getLogger("org.apache.hadoop.fs.FSNamesystem"); // // Stores the correct file name hierarchy // FSDirectory dir; // // Stores the block-->datanode(s) map. Updated only in response // to client-sent information. // TreeMap blocksMap = new TreeMap(); // // Stores the datanode-->block map. Done by storing a // set of datanode info objects, sorted by name. Updated only in // response to client-sent information. // TreeMap datanodeMap = new TreeMap(); // // Keeps a Vector for every named machine. The Vector contains // blocks that have recently been invalidated and are thought to live // on the machine in question. // TreeMap recentInvalidateSets = new TreeMap(); // // Keeps a TreeSet for every named node. Each treeset contains // a list of the blocks that are "extra" at that location. We'll // eventually remove these extras. // TreeMap excessReplicateMap = new TreeMap(); // // Keeps track of files that are being created, plus the // blocks that make them up. // TreeMap pendingCreates = new TreeMap(); // // Keeps track of the blocks that are part of those pending creates // TreeSet pendingCreateBlocks = new TreeSet(); // // Stats on overall usage // long totalCapacity = 0, totalRemaining = 0; // Random r = new Random(); // // Stores a set of datanode info objects, sorted by heartbeat // TreeSet heartbeats = new TreeSet(new Comparator() { public int compare(Object o1, Object o2) { DatanodeInfo d1 = (DatanodeInfo) o1; DatanodeInfo d2 = (DatanodeInfo) o2; long lu1 = d1.lastUpdate(); long lu2 = d2.lastUpdate(); if (lu1 < lu2) { return -1; } else if (lu1 > lu2) { return 1; } else { return d1.getName().compareTo(d2.getName()); } } }); // // Store set of Blocks that need to be replicated 1 or more times. // We also store pending replication-orders. // private TreeSet neededReplications = new TreeSet(); private TreeSet pendingReplications = new TreeSet(); // // Used for handling lock-leases // private TreeMap leases = new TreeMap(); private TreeSet sortedLeases = new TreeSet(); // // Threaded object that checks to see if we have been // getting heartbeats from all clients. // HeartbeatMonitor hbmon = null; LeaseMonitor lmon = null; Daemon hbthread = null, lmthread = null; boolean fsRunning = true; long systemStart = 0; private Configuration conf; // DESIRED_REPLICATION is how many copies we try to have at all times private int desiredReplication; // The maximum number of replicates we should allow for a single block private int maxReplication; // How many outgoing replication streams a given node should have at one time private int maxReplicationStreams; // MIN_REPLICATION is how many copies we need in place or else we disallow the write private int minReplication; // HEARTBEAT_RECHECK is how often a datanode sends its hearbeat private int heartBeatRecheck; /** * dir is where the filesystem directory state * is stored */ public FSNamesystem(File dir, Configuration conf) throws IOException { this.dir = new FSDirectory(dir); this.hbthread = new Daemon(new HeartbeatMonitor()); this.lmthread = new Daemon(new LeaseMonitor()); hbthread.start(); lmthread.start(); this.systemStart = System.currentTimeMillis(); this.conf = conf; this.desiredReplication = conf.getInt("dfs.replication", 3); this.maxReplication = desiredReplication; this.maxReplicationStreams = conf.getInt("dfs.max-repl-streams", 2); this.minReplication = 1; this.heartBeatRecheck= 1000; } /** Close down this filesystem manager. * Causes heartbeat and lease daemons to stop; waits briefly for * them to finish, but a short timeout returns control back to caller. */ public void close() { synchronized (this) { fsRunning = false; } try { hbthread.join(3000); } catch (InterruptedException ie) { } finally { // using finally to ensure we also wait for lease daemon try { lmthread.join(3000); } catch (InterruptedException ie) { } } } ///////////////////////////////////////////////////////// // // These methods are called by HadoopFS clients // ///////////////////////////////////////////////////////// /** * The client wants to open the given filename. Return a * list of (block,machineArray) pairs. The sequence of unique blocks * in the list indicates all the blocks that make up the filename. * * The client should choose one of the machines from the machineArray * at random. */ public Object[] open(UTF8 src) { Object results[] = null; Block blocks[] = dir.getFile(src); if (blocks != null) { results = new Object[2]; DatanodeInfo machineSets[][] = new DatanodeInfo[blocks.length][]; for (int i = 0; i < blocks.length; i++) { TreeSet containingNodes = (TreeSet) blocksMap.get(blocks[i]); if (containingNodes == null) { machineSets[i] = new DatanodeInfo[0]; } else { machineSets[i] = new DatanodeInfo[containingNodes.size()]; int j = 0; for (Iterator it = containingNodes.iterator(); it.hasNext(); j++) { machineSets[i][j] = (DatanodeInfo) it.next(); } } } results[0] = blocks; results[1] = machineSets; } return results; } /** * The client would like to create a new block for the indicated * filename. Return an array that consists of the block, plus a set * of machines. The first on this list should be where the client * writes data. Subsequent items in the list must be provided in * the connection to the first datanode. * @return Return an array that consists of the block, plus a set * of machines, or null if src is invalid for creation (based on * {@link FSDirectory#isValidToCreate(UTF8)}. */ public synchronized Object[] startFile(UTF8 src, UTF8 holder, UTF8 clientMachine, boolean overwrite) { Object results[] = null; if (pendingCreates.get(src) == null) { boolean fileValid = dir.isValidToCreate(src); if (overwrite && ! fileValid) { delete(src); fileValid = true; } if (fileValid) { results = new Object[2]; // Get the array of replication targets DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null, clientMachine); if (targets.length < this.minReplication) { LOG.warning("Target-length is " + targets.length + ", below MIN_REPLICATION (" + this.minReplication+ ")"); return null; } // Reserve space for this pending file pendingCreates.put(src, new Vector()); synchronized (leases) { Lease lease = (Lease) leases.get(holder); if (lease == null) { lease = new Lease(holder); leases.put(holder, lease); sortedLeases.add(lease); } else { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } lease.startedCreate(src); } // Create next block results[0] = allocateBlock(src); results[1] = targets; } else { // ! fileValid LOG.warning("Cannot start file because it is invalid. src=" + src); } } else { LOG.warning("Cannot start file because pendingCreates is non-null. src=" + src); } return results; } /** * The client would like to obtain an additional block for the indicated * filename (which is being written-to). Return an array that consists * of the block, plus a set of machines. The first on this list should * be where the client writes data. Subsequent items in the list must * be provided in the connection to the first datanode. * * Make sure the previous blocks have been reported by datanodes and * are replicated. Will return an empty 2-elt array if we want the * client to "try again later". */ public synchronized Object[] getAdditionalBlock(UTF8 src, UTF8 clientMachine) { Object results[] = null; if (dir.getFile(src) == null && pendingCreates.get(src) != null) { results = new Object[2]; // // If we fail this, bad things happen! // if (checkFileProgress(src)) { // Get the array of replication targets DatanodeInfo targets[] = chooseTargets(this.desiredReplication, null, clientMachine); if (targets.length < this.minReplication) { return null; } // Create next block results[0] = allocateBlock(src); results[1] = targets; } } return results; } /** * The client would like to let go of the given block */ public synchronized boolean abandonBlock(Block b, UTF8 src) { // // Remove the block from the pending creates list // Vector pendingVector = (Vector) pendingCreates.get(src); if (pendingVector != null) { for (Iterator it = pendingVector.iterator(); it.hasNext(); ) { Block cur = (Block) it.next(); if (cur.compareTo(b) == 0) { pendingCreateBlocks.remove(cur); it.remove(); return true; } } } return false; } /** * Abandon the entire file in progress */ public synchronized void abandonFileInProgress(UTF8 src) throws IOException { internalReleaseCreate(src); } /** * Finalize the created file and make it world-accessible. The * FSNamesystem will already know the blocks that make up the file. * Before we return, we make sure that all the file's blocks have * been reported by datanodes and are replicated correctly. */ public synchronized int completeFile(UTF8 src, UTF8 holder) { if (dir.getFile(src) != null || pendingCreates.get(src) == null) { LOG.info("Failed to complete " + src + " because dir.getFile()==" + dir.getFile(src) + " and " + pendingCreates.get(src)); return OPERATION_FAILED; } else if (! checkFileProgress(src)) { return STILL_WAITING; } else { Vector pendingVector = (Vector) pendingCreates.get(src); Block pendingBlocks[] = (Block[]) pendingVector.toArray(new Block[pendingVector.size()]); // // We have the pending blocks, but they won't have // length info in them (as they were allocated before // data-write took place). So we need to add the correct // length info to each // // REMIND - mjc - this is very inefficient! We should // improve this! // for (int i = 0; i < pendingBlocks.length; i++) { Block b = pendingBlocks[i]; TreeSet containingNodes = (TreeSet) blocksMap.get(b); DatanodeInfo node = (DatanodeInfo) containingNodes.first(); for (Iterator it = node.getBlockIterator(); it.hasNext(); ) { Block cur = (Block) it.next(); if (b.getBlockId() == cur.getBlockId()) { b.setNumBytes(cur.getNumBytes()); break; } } } // // Now we can add the (name,blocks) tuple to the filesystem // if (dir.addFile(src, pendingBlocks)) { // The file is no longer pending pendingCreates.remove(src); for (int i = 0; i < pendingBlocks.length; i++) { pendingCreateBlocks.remove(pendingBlocks[i]); } synchronized (leases) { Lease lease = (Lease) leases.get(holder); if (lease != null) { lease.completedCreate(src); if (! lease.hasLocks()) { leases.remove(holder); sortedLeases.remove(lease); } } } // // REMIND - mjc - this should be done only after we wait a few secs. // The namenode isn't giving datanodes enough time to report the // replicated blocks that are automatically done as part of a client // write. // // Now that the file is real, we need to be sure to replicate // the blocks. for (int i = 0; i < pendingBlocks.length; i++) { TreeSet containingNodes = (TreeSet) blocksMap.get(pendingBlocks[i]); if (containingNodes.size() < this.desiredReplication) { synchronized (neededReplications) { LOG.info("Completed file " + src + ", at holder " + holder + ". There is/are only " + containingNodes.size() + " copies of block " + pendingBlocks[i] + ", so replicating up to " + this.desiredReplication); neededReplications.add(pendingBlocks[i]); } } } return COMPLETE_SUCCESS; } else { System.out.println("AddFile() for " + src + " failed"); } LOG.info("Dropped through on file add...."); } return OPERATION_FAILED; } /** * Allocate a block at the given pending filename */ synchronized Block allocateBlock(UTF8 src) { Block b = new Block(); Vector v = (Vector) pendingCreates.get(src); v.add(b); pendingCreateBlocks.add(b); return b; } /** * Check that the indicated file's blocks are present and * replicated. If not, return false. */ synchronized boolean checkFileProgress(UTF8 src) { Vector v = (Vector) pendingCreates.get(src); for (Iterator it = v.iterator(); it.hasNext(); ) { Block b = (Block) it.next(); TreeSet containingNodes = (TreeSet) blocksMap.get(b); if (containingNodes == null || containingNodes.size() < this.minReplication) { return false; } } return true; } //////////////////////////////////////////////////////////////// // Here's how to handle block-copy failure during client write: // -- As usual, the client's write should result in a streaming // backup write to a k-machine sequence. // -- If one of the backup machines fails, no worries. Fail silently. // -- Before client is allowed to close and finalize file, make sure // that the blocks are backed up. Namenode may have to issue specific backup // commands to make up for earlier datanode failures. Once all copies // are made, edit namespace and return to client. //////////////////////////////////////////////////////////////// /** * Change the indicated filename. */ public boolean renameTo(UTF8 src, UTF8 dst) { return dir.renameTo(src, dst); } /** * Remove the indicated filename from the namespace. This may * invalidate some blocks that make up the file. */ public synchronized boolean delete(UTF8 src) { Block deletedBlocks[] = (Block[]) dir.delete(src); if (deletedBlocks != null) { for (int i = 0; i < deletedBlocks.length; i++) { Block b = deletedBlocks[i]; TreeSet containingNodes = (TreeSet) blocksMap.get(b); if (containingNodes != null) { for (Iterator it = containingNodes.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); Vector invalidateSet = (Vector) recentInvalidateSets.get(node.getName()); if (invalidateSet == null) { invalidateSet = new Vector(); recentInvalidateSets.put(node.getName(), invalidateSet); } invalidateSet.add(b); } } } } return (deletedBlocks != null); } /** * Return whether the given filename exists */ public boolean exists(UTF8 src) { if (dir.getFile(src) != null || dir.isDir(src)) { return true; } else { return false; } } /** * Whether the given name is a directory */ public boolean isDir(UTF8 src) { return dir.isDir(src); } /** * Create all the necessary directories */ public boolean mkdirs(UTF8 src) { return dir.mkdirs(src); } /** * Figure out a few hosts that are likely to contain the * block(s) referred to by the given (filename, start, len) tuple. */ public UTF8[][] getDatanodeHints(UTF8 src, long start, long len) { if (start < 0 || len < 0) { return new UTF8[0][]; } int startBlock = -1; int endBlock = -1; Block blocks[] = dir.getFile(src); if (blocks == null) { // no blocks return new UTF8[0][]; } // // First, figure out where the range falls in // the blocklist. // long startpos = start; long endpos = start + len; for (int i = 0; i < blocks.length; i++) { if (startpos >= 0) { startpos -= blocks[i].getNumBytes(); if (startpos <= 0) { startBlock = i; } } if (endpos >= 0) { endpos -= blocks[i].getNumBytes(); if (endpos <= 0) { endBlock = i; break; } } } // // Next, create an array of hosts where each block can // be found // if (startBlock < 0 || endBlock < 0) { return new UTF8[0][]; } else { UTF8 hosts[][] = new UTF8[(endBlock - startBlock) + 1][]; for (int i = startBlock; i <= endBlock; i++) { TreeSet containingNodes = (TreeSet) blocksMap.get(blocks[i]); Vector v = new Vector(); for (Iterator it = containingNodes.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); v.add(cur.getHost()); } hosts[i-startBlock] = (UTF8[]) v.toArray(new UTF8[v.size()]); } return hosts; } } /************************************************************ * A Lease governs all the locks held by a single client. * For each client there's a corresponding lease, whose * timestamp is updated when the client periodically * checks in. If the client dies and allows its lease to * expire, all the corresponding locks can be released. *************************************************************/ class Lease implements Comparable { public UTF8 holder; public long lastUpdate; TreeSet locks = new TreeSet(); TreeSet creates = new TreeSet(); public Lease(UTF8 holder) { this.holder = holder; renew(); } public void renew() { this.lastUpdate = System.currentTimeMillis(); } public boolean expired() { if (System.currentTimeMillis() - lastUpdate > LEASE_PERIOD) { return true; } else { return false; } } public void obtained(UTF8 src) { locks.add(src); } public void released(UTF8 src) { locks.remove(src); } public void startedCreate(UTF8 src) { creates.add(src); } public void completedCreate(UTF8 src) { creates.remove(src); } public boolean hasLocks() { return (locks.size() + creates.size()) > 0; } public void releaseLocks() { for (Iterator it = locks.iterator(); it.hasNext(); ) { UTF8 src = (UTF8) it.next(); internalReleaseLock(src, holder); } locks.clear(); for (Iterator it = creates.iterator(); it.hasNext(); ) { UTF8 src = (UTF8) it.next(); internalReleaseCreate(src); } creates.clear(); } /** */ public String toString() { return "[Lease. Holder: " + holder.toString() + ", heldlocks: " + locks.size() + ", pendingcreates: " + creates.size() + "]"; } /** */ public int compareTo(Object o) { Lease l1 = (Lease) this; Lease l2 = (Lease) o; long lu1 = l1.lastUpdate; long lu2 = l2.lastUpdate; if (lu1 < lu2) { return -1; } else if (lu1 > lu2) { return 1; } else { return l1.holder.compareTo(l2.holder); } } } /****************************************************** * LeaseMonitor checks for leases that have expired, * and disposes of them. ******************************************************/ class LeaseMonitor implements Runnable { public void run() { while (fsRunning) { synchronized (FSNamesystem.this) { synchronized (leases) { Lease top; while ((sortedLeases.size() > 0) && ((top = (Lease) sortedLeases.first()) != null)) { if (top.expired()) { top.releaseLocks(); leases.remove(top.holder); LOG.info("Removing lease " + top + ", leases remaining: " + sortedLeases.size()); if (!sortedLeases.remove(top)) { LOG.info("Unknown failure trying to remove " + top + " from lease set."); } } else { break; } } } } try { Thread.sleep(2000); } catch (InterruptedException ie) { } } } } /** * Get a lock (perhaps exclusive) on the given file */ public synchronized int obtainLock(UTF8 src, UTF8 holder, boolean exclusive) { int result = dir.obtainLock(src, holder, exclusive); if (result == COMPLETE_SUCCESS) { synchronized (leases) { Lease lease = (Lease) leases.get(holder); if (lease == null) { lease = new Lease(holder); leases.put(holder, lease); sortedLeases.add(lease); } else { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } lease.obtained(src); } } return result; } /** * Release the lock on the given file */ public synchronized int releaseLock(UTF8 src, UTF8 holder) { int result = internalReleaseLock(src, holder); if (result == COMPLETE_SUCCESS) { synchronized (leases) { Lease lease = (Lease) leases.get(holder); if (lease != null) { lease.released(src); if (! lease.hasLocks()) { leases.remove(holder); sortedLeases.remove(lease); } } } } return result; } private int internalReleaseLock(UTF8 src, UTF8 holder) { return dir.releaseLock(src, holder); } private void internalReleaseCreate(UTF8 src) { Vector v = (Vector) pendingCreates.remove(src); for (Iterator it2 = v.iterator(); it2.hasNext(); ) { Block b = (Block) it2.next(); pendingCreateBlocks.remove(b); } } /** * Renew the lease(s) held by the given client */ public void renewLease(UTF8 holder) { synchronized (leases) { Lease lease = (Lease) leases.get(holder); if (lease != null) { sortedLeases.remove(lease); lease.renew(); sortedLeases.add(lease); } } } /** * Get a listing of all files at 'src'. The Object[] array * exists so we can return file attributes (soon to be implemented) */ public DFSFileInfo[] getListing(UTF8 src) { return dir.getListing(src); } ///////////////////////////////////////////////////////// // // These methods are called by datanodes // ///////////////////////////////////////////////////////// /** * The given node has reported in. This method should: * 1) Record the heartbeat, so the datanode isn't timed out * 2) Adjust usage stats for future block allocation */ public synchronized void gotHeartbeat(UTF8 name, long capacity, long remaining) { synchronized (heartbeats) { synchronized (datanodeMap) { long capacityDiff = 0; long remainingDiff = 0; DatanodeInfo nodeinfo = (DatanodeInfo) datanodeMap.get(name); if (nodeinfo == null) { LOG.info("Got brand-new heartbeat from " + name); nodeinfo = new DatanodeInfo(name, capacity, remaining); datanodeMap.put(name, nodeinfo); capacityDiff = capacity; remainingDiff = remaining; } else { capacityDiff = capacity - nodeinfo.getCapacity(); remainingDiff = remaining - nodeinfo.getRemaining(); heartbeats.remove(nodeinfo); nodeinfo.updateHeartbeat(capacity, remaining); } heartbeats.add(nodeinfo); totalCapacity += capacityDiff; totalRemaining += remainingDiff; } } } /** * Periodically calls heartbeatCheck(). */ class HeartbeatMonitor implements Runnable { /** */ public void run() { while (fsRunning) { heartbeatCheck(); try { Thread.sleep(heartBeatRecheck); } catch (InterruptedException ie) { } } } } /** * Check if there are any expired heartbeats, and if so, * whether any blocks have to be re-replicated. */ synchronized void heartbeatCheck() { synchronized (heartbeats) { DatanodeInfo nodeInfo = null; while ((heartbeats.size() > 0) && ((nodeInfo = (DatanodeInfo) heartbeats.first()) != null) && (nodeInfo.lastUpdate() < System.currentTimeMillis() - EXPIRE_INTERVAL)) { LOG.info("Lost heartbeat for " + nodeInfo.getName()); heartbeats.remove(nodeInfo); synchronized (datanodeMap) { datanodeMap.remove(nodeInfo.getName()); } totalCapacity -= nodeInfo.getCapacity(); totalRemaining -= nodeInfo.getRemaining(); Block deadblocks[] = nodeInfo.getBlocks(); if (deadblocks != null) { for (int i = 0; i < deadblocks.length; i++) { removeStoredBlock(deadblocks[i], nodeInfo); } } if (heartbeats.size() > 0) { nodeInfo = (DatanodeInfo) heartbeats.first(); } } } } /** * The given node is reporting all its blocks. Use this info to * update the (machine-->blocklist) and (block-->machinelist) tables. */ public synchronized Block[] processReport(Block newReport[], UTF8 name) { DatanodeInfo node = (DatanodeInfo) datanodeMap.get(name); if (node == null) { throw new IllegalArgumentException("Unexpected exception. Received block report from node " + name + ", but there is no info for " + name); } // // Modify the (block-->datanode) map, according to the difference // between the old and new block report. // int oldPos = 0, newPos = 0; Block oldReport[] = node.getBlocks(); while (oldReport != null && newReport != null && oldPos < oldReport.length && newPos < newReport.length) { int cmp = oldReport[oldPos].compareTo(newReport[newPos]); if (cmp == 0) { // Do nothing, blocks are the same oldPos++; newPos++; } else if (cmp < 0) { // The old report has a block the new one does not removeStoredBlock(oldReport[oldPos], node); oldPos++; } else { // The new report has a block the old one does not addStoredBlock(newReport[newPos], node); newPos++; } } while (oldReport != null && oldPos < oldReport.length) { // The old report has a block the new one does not removeStoredBlock(oldReport[oldPos], node); oldPos++; } while (newReport != null && newPos < newReport.length) { // The new report has a block the old one does not addStoredBlock(newReport[newPos], node); newPos++; } // // Modify node so it has the new blockreport // node.updateBlocks(newReport); // // We've now completely updated the node's block report profile. // We now go through all its blocks and find which ones are invalid, // no longer pending, or over-replicated. // // (Note it's not enough to just invalidate blocks at lease expiry // time; datanodes can go down before the client's lease on // the failed file expires and miss the "expire" event.) // // This function considers every block on a datanode, and thus // should only be invoked infrequently. // Vector obsolete = new Vector(); for (Iterator it = node.getBlockIterator(); it.hasNext(); ) { Block b = (Block) it.next(); if (! dir.isValidBlock(b) && ! pendingCreateBlocks.contains(b)) { LOG.info("Obsoleting block " + b); obsolete.add(b); } } return (Block[]) obsolete.toArray(new Block[obsolete.size()]); } /** * Modify (block-->datanode) map. Remove block from set of * needed replications if this takes care of the problem. */ synchronized void addStoredBlock(Block block, DatanodeInfo node) { TreeSet containingNodes = (TreeSet) blocksMap.get(block); if (containingNodes == null) { containingNodes = new TreeSet(); blocksMap.put(block, containingNodes); } if (! containingNodes.contains(node)) { containingNodes.add(node); } else { LOG.info("Redundant addStoredBlock request received for block " + block + " on node " + node); } synchronized (neededReplications) { if (dir.isValidBlock(block)) { if (containingNodes.size() >= this.desiredReplication) { neededReplications.remove(block); pendingReplications.remove(block); } else if (containingNodes.size() < this.desiredReplication) { if (! neededReplications.contains(block)) { neededReplications.add(block); } } // // Find how many of the containing nodes are "extra", if any. // If there are any extras, call chooseExcessReplicates() to // mark them in the excessReplicateMap. // Vector nonExcess = new Vector(); for (Iterator it = containingNodes.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName()); if (excessBlocks == null || ! excessBlocks.contains(block)) { nonExcess.add(cur); } } if (nonExcess.size() > this.maxReplication) { chooseExcessReplicates(nonExcess, block, this.maxReplication); } } } } /** * We want a max of "maxReps" replicates for any block, but we now have too many. * In this method, copy enough nodes from 'srcNodes' into 'dstNodes' such that: * * srcNodes.size() - dstNodes.size() == maxReps * * For now, we choose nodes randomly. In the future, we might enforce some * kind of policy (like making sure replicates are spread across racks). */ void chooseExcessReplicates(Vector nonExcess, Block b, int maxReps) { while (nonExcess.size() - maxReps > 0) { int chosenNode = r.nextInt(nonExcess.size()); DatanodeInfo cur = (DatanodeInfo) nonExcess.elementAt(chosenNode); nonExcess.removeElementAt(chosenNode); TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(cur.getName()); if (excessBlocks == null) { excessBlocks = new TreeSet(); excessReplicateMap.put(cur.getName(), excessBlocks); } excessBlocks.add(b); // // The 'excessblocks' tracks blocks until we get confirmation // that the datanode has deleted them; the only way we remove them // is when we get a "removeBlock" message. // // The 'invalidate' list is used to inform the datanode the block // should be deleted. Items are removed from the invalidate list // upon giving instructions to the namenode. // Vector invalidateSet = (Vector) recentInvalidateSets.get(cur.getName()); if (invalidateSet == null) { invalidateSet = new Vector(); recentInvalidateSets.put(cur.getName(), invalidateSet); } invalidateSet.add(b); } } /** * Modify (block-->datanode) map. Possibly generate * replication tasks, if the removed block is still valid. */ synchronized void removeStoredBlock(Block block, DatanodeInfo node) { TreeSet containingNodes = (TreeSet) blocksMap.get(block); if (containingNodes == null || ! containingNodes.contains(node)) { throw new IllegalArgumentException("No machine mapping found for block " + block + ", which should be at node " + node); } containingNodes.remove(node); // // It's possible that the block was removed because of a datanode // failure. If the block is still valid, check if replication is // necessary. In that case, put block on a possibly-will- // be-replicated list. // if (dir.isValidBlock(block) && (containingNodes.size() < this.desiredReplication)) { synchronized (neededReplications) { neededReplications.add(block); } } // // We've removed a block from a node, so it's definitely no longer // in "excess" there. // TreeSet excessBlocks = (TreeSet) excessReplicateMap.get(node.getName()); if (excessBlocks != null) { excessBlocks.remove(block); if (excessBlocks.size() == 0) { excessReplicateMap.remove(node.getName()); } } } /** * The given node is reporting that it received a certain block. */ public synchronized void blockReceived(Block block, UTF8 name) { DatanodeInfo node = (DatanodeInfo) datanodeMap.get(name); if (node == null) { throw new IllegalArgumentException("Unexpected exception. Got blockReceived message from node " + name + ", but there is no info for " + name); } // // Modify the blocks->datanode map // addStoredBlock(block, node); // // Supplement node's blockreport // node.addBlock(block); } /** * Total raw bytes */ public long totalCapacity() { return totalCapacity; } /** * Total non-used raw bytes */ public long totalRemaining() { return totalRemaining; } /** */ public DatanodeInfo[] datanodeReport() { DatanodeInfo results[] = null; synchronized (heartbeats) { synchronized (datanodeMap) { results = new DatanodeInfo[datanodeMap.size()]; int i = 0; for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); results[i++] = cur; } } } return results; } ///////////////////////////////////////////////////////// // // These methods are called by the Namenode system, to see // if there is any work for a given datanode. // ///////////////////////////////////////////////////////// /** * Check if there are any recently-deleted blocks a datanode should remove. */ public synchronized Block[] blocksToInvalidate(UTF8 sender) { Vector invalidateSet = (Vector) recentInvalidateSets.remove(sender); if (invalidateSet != null) { return (Block[]) invalidateSet.toArray(new Block[invalidateSet.size()]); } else { return null; } } /** * Return with a list of Block/DataNodeInfo sets, indicating * where various Blocks should be copied, ASAP. * * The Array that we return consists of two objects: * The 1st elt is an array of Blocks. * The 2nd elt is a 2D array of DatanodeInfo objs, identifying the * target sequence for the Block at the appropriate index. * */ public synchronized Object[] pendingTransfers(DatanodeInfo srcNode, int xmitsInProgress) { synchronized (neededReplications) { Object results[] = null; int scheduledXfers = 0; if (neededReplications.size() > 0) { // // Go through all blocks that need replications. See if any // are present at the current node. If so, ask the node to // replicate them. // Vector replicateBlocks = new Vector(); Vector replicateTargetSets = new Vector(); for (Iterator it = neededReplications.iterator(); it.hasNext(); ) { // // We can only reply with 'maxXfers' or fewer blocks // if (scheduledXfers >= this.maxReplicationStreams - xmitsInProgress) { break; } Block block = (Block) it.next(); if (! dir.isValidBlock(block)) { it.remove(); } else { TreeSet containingNodes = (TreeSet) blocksMap.get(block); if (containingNodes.contains(srcNode)) { DatanodeInfo targets[] = chooseTargets(Math.min(this.desiredReplication - containingNodes.size(), this.maxReplicationStreams - xmitsInProgress), containingNodes, null); if (targets.length > 0) { // Build items to return replicateBlocks.add(block); replicateTargetSets.add(targets); scheduledXfers += targets.length; } } } } // // Move the block-replication into a "pending" state. // The reason we use 'pending' is so we can retry // replications that fail after an appropriate amount of time. // (REMIND - mjc - this timer is not yet implemented.) // if (replicateBlocks.size() > 0) { int i = 0; for (Iterator it = replicateBlocks.iterator(); it.hasNext(); i++) { Block block = (Block) it.next(); DatanodeInfo targets[] = (DatanodeInfo[]) replicateTargetSets.elementAt(i); TreeSet containingNodes = (TreeSet) blocksMap.get(block); if (containingNodes.size() + targets.length >= this.desiredReplication) { neededReplications.remove(block); pendingReplications.add(block); } LOG.info("Pending transfer (block " + block.getBlockName() + ") from " + srcNode.getName() + " to " + targets.length + " destinations"); } // // Build returned objects from above lists // DatanodeInfo targetMatrix[][] = new DatanodeInfo[replicateTargetSets.size()][]; for (i = 0; i < targetMatrix.length; i++) { targetMatrix[i] = (DatanodeInfo[]) replicateTargetSets.elementAt(i); } results = new Object[2]; results[0] = replicateBlocks.toArray(new Block[replicateBlocks.size()]); results[1] = targetMatrix; } } return results; } } /** * Get a certain number of targets, if possible. * If not, return as many as we can. * @param desiredReplicates number of duplicates wanted. * @param forbiddenNodes of DatanodeInfo instances that should not be * considered targets. * @return array of DatanodeInfo instances uses as targets. */ DatanodeInfo[] chooseTargets(int desiredReplicates, TreeSet forbiddenNodes, UTF8 clientMachine) { TreeSet alreadyChosen = new TreeSet(); Vector targets = new Vector(); for (int i = 0; i < desiredReplicates; i++) { DatanodeInfo target = chooseTarget(forbiddenNodes, alreadyChosen, clientMachine); if (target != null) { targets.add(target); alreadyChosen.add(target); } else { break; // calling chooseTarget again won't help } } return (DatanodeInfo[]) targets.toArray(new DatanodeInfo[targets.size()]); } /** * Choose a target from available machines, excepting the * given ones. * * Right now it chooses randomly from available boxes. In future could * choose according to capacity and load-balancing needs (or even * network-topology, to avoid inter-switch traffic). * @param forbidden1 DatanodeInfo targets not allowed, null allowed. * @param forbidden2 DatanodeInfo targets not allowed, null allowed. * @return DatanodeInfo instance to use or null if something went wrong * (a log message is emitted if null is returned). */ DatanodeInfo chooseTarget(TreeSet forbidden1, TreeSet forbidden2, UTF8 clientMachine) { // // Check if there are any available targets at all // int totalMachines = datanodeMap.size(); if (totalMachines == 0) { LOG.warning("While choosing target, totalMachines is " + totalMachines); return null; } // // Build a map of forbidden hostnames from the two forbidden sets. // TreeSet forbiddenMachines = new TreeSet(); if (forbidden1 != null) { for (Iterator it = forbidden1.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } if (forbidden2 != null) { for (Iterator it = forbidden2.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } // // Build list of machines we can actually choose from // Vector targetList = new Vector(); for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (! forbiddenMachines.contains(node.getHost())) { targetList.add(node); } } Collections.shuffle(targetList); // // Now pick one // if (targetList.size() > 0) { // // If the requester's machine is in the targetList, // and it's got the capacity, pick it. // if (clientMachine != null && clientMachine.getLength() > 0) { for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (clientMachine.equals(node.getHost())) { if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } } } // // Otherwise, choose node according to target capacity // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); - if ((node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE)) { + if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } // // That should do the trick. But we might not be able // to pick any node if the target was out of bytes. As // a last resort, pick the first valid one we can find. // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); - if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { + if (node.getRemaining() > BLOCK_SIZE) { return node; } } LOG.warning("Could not find any nodes with sufficient capacity"); return null; } else { LOG.warning("Zero targets found, forbidden1.size=" + ( forbidden1 != null ? forbidden1.size() : 0 ) + " forbidden2.size()=" + ( forbidden2 != null ? forbidden2.size() : 0 )); return null; } } }
false
true
DatanodeInfo chooseTarget(TreeSet forbidden1, TreeSet forbidden2, UTF8 clientMachine) { // // Check if there are any available targets at all // int totalMachines = datanodeMap.size(); if (totalMachines == 0) { LOG.warning("While choosing target, totalMachines is " + totalMachines); return null; } // // Build a map of forbidden hostnames from the two forbidden sets. // TreeSet forbiddenMachines = new TreeSet(); if (forbidden1 != null) { for (Iterator it = forbidden1.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } if (forbidden2 != null) { for (Iterator it = forbidden2.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } // // Build list of machines we can actually choose from // Vector targetList = new Vector(); for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (! forbiddenMachines.contains(node.getHost())) { targetList.add(node); } } Collections.shuffle(targetList); // // Now pick one // if (targetList.size() > 0) { // // If the requester's machine is in the targetList, // and it's got the capacity, pick it. // if (clientMachine != null && clientMachine.getLength() > 0) { for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (clientMachine.equals(node.getHost())) { if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } } } // // Otherwise, choose node according to target capacity // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if ((node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE)) { return node; } } // // That should do the trick. But we might not be able // to pick any node if the target was out of bytes. As // a last resort, pick the first valid one we can find. // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } LOG.warning("Could not find any nodes with sufficient capacity"); return null; } else { LOG.warning("Zero targets found, forbidden1.size=" + ( forbidden1 != null ? forbidden1.size() : 0 ) + " forbidden2.size()=" + ( forbidden2 != null ? forbidden2.size() : 0 )); return null; } }
DatanodeInfo chooseTarget(TreeSet forbidden1, TreeSet forbidden2, UTF8 clientMachine) { // // Check if there are any available targets at all // int totalMachines = datanodeMap.size(); if (totalMachines == 0) { LOG.warning("While choosing target, totalMachines is " + totalMachines); return null; } // // Build a map of forbidden hostnames from the two forbidden sets. // TreeSet forbiddenMachines = new TreeSet(); if (forbidden1 != null) { for (Iterator it = forbidden1.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } if (forbidden2 != null) { for (Iterator it = forbidden2.iterator(); it.hasNext(); ) { DatanodeInfo cur = (DatanodeInfo) it.next(); forbiddenMachines.add(cur.getHost()); } } // // Build list of machines we can actually choose from // Vector targetList = new Vector(); for (Iterator it = datanodeMap.values().iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (! forbiddenMachines.contains(node.getHost())) { targetList.add(node); } } Collections.shuffle(targetList); // // Now pick one // if (targetList.size() > 0) { // // If the requester's machine is in the targetList, // and it's got the capacity, pick it. // if (clientMachine != null && clientMachine.getLength() > 0) { for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (clientMachine.equals(node.getHost())) { if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } } } // // Otherwise, choose node according to target capacity // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (node.getRemaining() > BLOCK_SIZE * MIN_BLOCKS_FOR_WRITE) { return node; } } // // That should do the trick. But we might not be able // to pick any node if the target was out of bytes. As // a last resort, pick the first valid one we can find. // for (Iterator it = targetList.iterator(); it.hasNext(); ) { DatanodeInfo node = (DatanodeInfo) it.next(); if (node.getRemaining() > BLOCK_SIZE) { return node; } } LOG.warning("Could not find any nodes with sufficient capacity"); return null; } else { LOG.warning("Zero targets found, forbidden1.size=" + ( forbidden1 != null ? forbidden1.size() : 0 ) + " forbidden2.size()=" + ( forbidden2 != null ? forbidden2.size() : 0 )); return null; } }
diff --git a/app/src/processing/app/debug/AvrdudeUploader.java b/app/src/processing/app/debug/AvrdudeUploader.java index a7afb5d4..641e4412 100755 --- a/app/src/processing/app/debug/AvrdudeUploader.java +++ b/app/src/processing/app/debug/AvrdudeUploader.java @@ -1,333 +1,334 @@ /* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* AvrdudeUploader - uploader implementation using avrdude Part of the Arduino project - http://www.arduino.cc/ Copyright (c) 2004-05 Hernando Barragan This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ */ package processing.app.debug; import processing.app.Base; import processing.app.Preferences; import processing.app.Serial; import processing.app.SerialException; import static processing.app.I18n._; import java.io.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import gnu.io.*; public class AvrdudeUploader extends Uploader { public AvrdudeUploader() { } public boolean uploadUsingPreferences(String buildPath, String className, boolean usingProgrammer) throws RunnerException, SerialException { this.verbose = verbose; Map<String, String> boardPreferences = Base.getBoardPreferences(); // if no protocol is specified for this board, assume it lacks a // bootloader and upload using the selected programmer. if (usingProgrammer || boardPreferences.get("upload.protocol") == null) { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } Collection params = getProgrammerCommands(target, programmer); params.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); return avrdude(params); } return uploadViaBootloader(buildPath, className); } private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || + boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; } public boolean burnBootloader() throws RunnerException { String programmer = Preferences.get("programmer"); Target target = Base.getTarget(); if (programmer.indexOf(":") != -1) { target = Base.targetsTable.get(programmer.substring(0, programmer.indexOf(":"))); programmer = programmer.substring(programmer.indexOf(":") + 1); } return burnBootloader(getProgrammerCommands(target, programmer)); } private Collection getProgrammerCommands(Target target, String programmer) { Map<String, String> programmerPreferences = target.getProgrammers().get(programmer); List params = new ArrayList(); params.add("-c" + programmerPreferences.get("protocol")); if ("usb".equals(programmerPreferences.get("communication"))) { params.add("-Pusb"); } else if ("serial".equals(programmerPreferences.get("communication"))) { params.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + Preferences.get("serial.port")); if (programmerPreferences.get("speed") != null) { params.add("-b" + Integer.parseInt(programmerPreferences.get("speed"))); } } // XXX: add support for specifying the port address for parallel // programmers, although avrdude has a default that works in most cases. if (programmerPreferences.get("force") != null && programmerPreferences.get("force").toLowerCase().equals("true")) params.add("-F"); if (programmerPreferences.get("delay") != null) params.add("-i" + programmerPreferences.get("delay")); return params; } protected boolean burnBootloader(Collection params) throws RunnerException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List fuses = new ArrayList(); fuses.add("-e"); // erase the chip if (boardPreferences.get("bootloader.unlock_bits") != null) fuses.add("-Ulock:w:" + boardPreferences.get("bootloader.unlock_bits") + ":m"); if (boardPreferences.get("bootloader.extended_fuses") != null) fuses.add("-Uefuse:w:" + boardPreferences.get("bootloader.extended_fuses") + ":m"); fuses.add("-Uhfuse:w:" + boardPreferences.get("bootloader.high_fuses") + ":m"); fuses.add("-Ulfuse:w:" + boardPreferences.get("bootloader.low_fuses") + ":m"); if (!avrdude(params, fuses)) return false; try { Thread.sleep(1000); } catch (InterruptedException e) {} Target t; List bootloader = new ArrayList(); String bootloaderPath = boardPreferences.get("bootloader.path"); if (bootloaderPath != null) { if (bootloaderPath.indexOf(':') == -1) { t = Base.getTarget(); // the current target (associated with the board) } else { String targetName = bootloaderPath.substring(0, bootloaderPath.indexOf(':')); t = Base.targetsTable.get(targetName); bootloaderPath = bootloaderPath.substring(bootloaderPath.indexOf(':') + 1); } File bootloadersFile = new File(t.getFolder(), "bootloaders"); File bootloaderFile = new File(bootloadersFile, bootloaderPath); bootloaderPath = bootloaderFile.getAbsolutePath(); bootloader.add("-Uflash:w:" + bootloaderPath + File.separator + boardPreferences.get("bootloader.file") + ":i"); } if (boardPreferences.get("bootloader.lock_bits") != null) bootloader.add("-Ulock:w:" + boardPreferences.get("bootloader.lock_bits") + ":m"); if (bootloader.size() > 0) return avrdude(params, bootloader); return true; } public boolean avrdude(Collection p1, Collection p2) throws RunnerException { ArrayList p = new ArrayList(p1); p.addAll(p2); return avrdude(p); } public boolean avrdude(Collection params) throws RunnerException { List commandDownloader = new ArrayList(); if(Base.isLinux()) { if ((new File(Base.getHardwarePath() + "/tools/" + "avrdude")).exists()) { commandDownloader.add(Base.getHardwarePath() + "/tools/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avrdude.conf"); } else { commandDownloader.add("avrdude"); } } else { commandDownloader.add(Base.getHardwarePath() + "/tools/avr/bin/" + "avrdude"); commandDownloader.add("-C" + Base.getHardwarePath() + "/tools/avr/etc/avrdude.conf"); } if (verbose || Preferences.getBoolean("upload.verbose")) { commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); commandDownloader.add("-v"); } else { commandDownloader.add("-q"); commandDownloader.add("-q"); } commandDownloader.add("-p" + Base.getBoardPreferences().get("build.mcu")); commandDownloader.addAll(params); return executeUploadCommand(commandDownloader); } }
true
true
private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; }
private boolean uploadViaBootloader(String buildPath, String className) throws RunnerException, SerialException { Map<String, String> boardPreferences = Base.getBoardPreferences(); List commandDownloader = new ArrayList(); String protocol = boardPreferences.get("upload.protocol"); // avrdude wants "stk500v1" to distinguish it from stk500v2 if (protocol.equals("stk500")) protocol = "stk500v1"; String uploadPort = Preferences.get("serial.port"); // need to do a little dance for Leonardo and derivatives: // open then close the port at the magic baudrate (usually 1200 bps) first // to signal to the sketch that it should reset into bootloader. after doing // this wait a moment for the bootloader to enumerate. On Windows, also must // deal with the fact that the COM port number changes from bootloader to // sketch. if (boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-Arduino_Robot") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { String caterinaUploadPort = null; try { // Toggle 1200 bps on selected serial port to force board reset. List<String> before = Serial.list(); if (before.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out .println(_("Forcing reset using 1200bps open/close on port ") + uploadPort); Serial.touchPort(uploadPort, 1200); // Scanning for available ports seems to open the port or // otherwise assert DTR, which would cancel the WDT reset if // it happened within 250 ms. So we wait until the reset should // have already occured before we start scanning. if (!Base.isMacOS()) Thread.sleep(300); } // Wait for a port to appear on the list int elapsed = 0; while (elapsed < 10000) { List<String> now = Serial.list(); List<String> diff = new ArrayList<String>(now); diff.removeAll(before); if (verbose || Preferences.getBoolean("upload.verbose")) { System.out.print("PORTS {"); for (String p : before) System.out.print(p+", "); System.out.print("} / {"); for (String p : now) System.out.print(p+", "); System.out.print("} => {"); for (String p : diff) System.out.print(p+", "); System.out.println("}"); } if (diff.size() > 0) { caterinaUploadPort = diff.get(0); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Found Leonardo upload port: " + caterinaUploadPort); break; } // Keep track of port that disappears before = now; Thread.sleep(250); elapsed += 250; // On Windows, it can take a long time for the port to disappear and // come back, so use a longer time out before assuming that the selected // port is the bootloader (not the sketch). if (((!Base.isWindows() && elapsed >= 500) || elapsed >= 5000) && now.contains(uploadPort)) { if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Uploading using selected port: " + uploadPort); caterinaUploadPort = uploadPort; break; } } if (caterinaUploadPort == null) // Something happened while detecting port throw new RunnerException( _("Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.")); uploadPort = caterinaUploadPort; } catch (SerialException e) { throw new RunnerException(e.getMessage()); } catch (InterruptedException e) { throw new RunnerException(e.getMessage()); } } commandDownloader.add("-c" + protocol); commandDownloader.add("-P" + (Base.isWindows() ? "\\\\.\\" : "") + uploadPort); commandDownloader.add( "-b" + Integer.parseInt(boardPreferences.get("upload.speed"))); commandDownloader.add("-D"); // don't erase if (!Preferences.getBoolean("upload.verify")) commandDownloader.add("-V"); // disable verify commandDownloader.add("-Uflash:w:" + buildPath + File.separator + className + ".hex:i"); if (boardPreferences.get("upload.disable_flushing") == null || boardPreferences.get("upload.disable_flushing").toLowerCase().equals("false")) { flushSerialBuffer(); } boolean avrdudeResult = avrdude(commandDownloader); // For Leonardo wait until the bootloader serial port disconnects and the sketch serial // port reconnects (or timeout after a few seconds if the sketch port never comes back). // Doing this saves users from accidentally opening Serial Monitor on the soon-to-be-orphaned // bootloader port. if (true == avrdudeResult && boardPreferences.get("bootloader.path") != null && (boardPreferences.get("bootloader.path").equals("caterina") || boardPreferences.get("bootloader.path").equals("caterina-LilyPadUSB"))) { try { Thread.sleep(500); } catch (InterruptedException ex) { } long timeout = System.currentTimeMillis() + 2000; while (timeout > System.currentTimeMillis()) { List<String> portList = Serial.list(); uploadPort = Preferences.get("serial.port"); if (portList.contains(uploadPort)) { try { Thread.sleep(100); // delay to avoid port in use and invalid parameters errors } catch (InterruptedException ex) { } // Remove the magic baud rate (1200bps) to avoid future unwanted board resets int serialRate = Preferences.getInteger("serial.debug_rate"); if (verbose || Preferences.getBoolean("upload.verbose")) System.out.println("Setting baud rate to " + serialRate + " on " + uploadPort); Serial.touchPort(uploadPort, serialRate); break; } try { Thread.sleep(100); } catch (InterruptedException ex) { } } } return avrdudeResult; }
diff --git a/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamLineRecordReader.java b/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamLineRecordReader.java index bc8c0cb28..ae9cab8c6 100644 --- a/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamLineRecordReader.java +++ b/src/contrib/streaming/src/java/org/apache/hadoop/streaming/StreamLineRecordReader.java @@ -1,127 +1,127 @@ /** * 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.streaming; import java.io.*; import java.nio.charset.MalformedInputException; import java.util.Arrays; import java.util.zip.GZIPInputStream; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.Text; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.util.StringUtils; /** * Similar to org.apache.hadoop.mapred.TextRecordReader, * but delimits key and value with a TAB. * @author Michel Tourn */ public class StreamLineRecordReader extends StreamBaseRecordReader { public StreamLineRecordReader(FSDataInputStream in, FileSplit split, Reporter reporter, JobConf job, FileSystem fs) throws IOException { super(in, split, reporter, job, fs); gzipped_ = StreamInputFormat.isGzippedInput(job); if (gzipped_) { din_ = new DataInputStream(new GZIPInputStream(in_)); } else { din_ = in_; } } public void seekNextRecordBoundary() throws IOException { if (gzipped_) { // no skipping: use din_ as-is // assumes splitter created only one split per file return; } else { int bytesSkipped = 0; if (start_ != 0) { in_.seek(start_ - 1); // scan to the next newline in the file while (in_.getPos() < end_) { char c = (char) in_.read(); bytesSkipped++; if (c == '\r' || c == '\n') { break; } } } //System.out.println("getRecordReader start="+start_ + " end=" + end_ + " bytesSkipped"+bytesSkipped); } } public synchronized boolean next(Writable key, Writable value) throws IOException { if (!(key instanceof Text)) { throw new IllegalArgumentException("Key should be of type Text but: " + key.getClass().getName()); } if (!(value instanceof Text)) { throw new IllegalArgumentException("Value should be of type Text but: " + value.getClass().getName()); } Text tKey = (Text) key; Text tValue = (Text) value; byte[] line; while (true) { if (gzipped_) { // figure EOS from readLine } else { long pos = in_.getPos(); if (pos >= end_) return false; } line = UTF8ByteArrayUtils.readLine((InputStream) in_); + if (line == null) return false; try { Text.validateUTF8(line); } catch (MalformedInputException m) { System.err.println("line=" + line + "|" + new Text(line)); System.out.flush(); } - if (line == null) return false; try { int tab = UTF8ByteArrayUtils.findTab(line); if (tab == -1) { tKey.set(line); tValue.set(""); } else { UTF8ByteArrayUtils.splitKeyVal(line, tKey, tValue, tab); } break; } catch (MalformedInputException e) { LOG.warn(StringUtils.stringifyException(e)); } } numRecStats(line, 0, line.length); return true; } boolean gzipped_; GZIPInputStream zin_; DataInputStream din_; // GZIP or plain }
false
true
public synchronized boolean next(Writable key, Writable value) throws IOException { if (!(key instanceof Text)) { throw new IllegalArgumentException("Key should be of type Text but: " + key.getClass().getName()); } if (!(value instanceof Text)) { throw new IllegalArgumentException("Value should be of type Text but: " + value.getClass().getName()); } Text tKey = (Text) key; Text tValue = (Text) value; byte[] line; while (true) { if (gzipped_) { // figure EOS from readLine } else { long pos = in_.getPos(); if (pos >= end_) return false; } line = UTF8ByteArrayUtils.readLine((InputStream) in_); try { Text.validateUTF8(line); } catch (MalformedInputException m) { System.err.println("line=" + line + "|" + new Text(line)); System.out.flush(); } if (line == null) return false; try { int tab = UTF8ByteArrayUtils.findTab(line); if (tab == -1) { tKey.set(line); tValue.set(""); } else { UTF8ByteArrayUtils.splitKeyVal(line, tKey, tValue, tab); } break; } catch (MalformedInputException e) { LOG.warn(StringUtils.stringifyException(e)); } } numRecStats(line, 0, line.length); return true; }
public synchronized boolean next(Writable key, Writable value) throws IOException { if (!(key instanceof Text)) { throw new IllegalArgumentException("Key should be of type Text but: " + key.getClass().getName()); } if (!(value instanceof Text)) { throw new IllegalArgumentException("Value should be of type Text but: " + value.getClass().getName()); } Text tKey = (Text) key; Text tValue = (Text) value; byte[] line; while (true) { if (gzipped_) { // figure EOS from readLine } else { long pos = in_.getPos(); if (pos >= end_) return false; } line = UTF8ByteArrayUtils.readLine((InputStream) in_); if (line == null) return false; try { Text.validateUTF8(line); } catch (MalformedInputException m) { System.err.println("line=" + line + "|" + new Text(line)); System.out.flush(); } try { int tab = UTF8ByteArrayUtils.findTab(line); if (tab == -1) { tKey.set(line); tValue.set(""); } else { UTF8ByteArrayUtils.splitKeyVal(line, tKey, tValue, tab); } break; } catch (MalformedInputException e) { LOG.warn(StringUtils.stringifyException(e)); } } numRecStats(line, 0, line.length); return true; }
diff --git a/src/main/java/hudson/plugins/xvnc/Xvnc.java b/src/main/java/hudson/plugins/xvnc/Xvnc.java index b027896..7191ee0 100644 --- a/src/main/java/hudson/plugins/xvnc/Xvnc.java +++ b/src/main/java/hudson/plugins/xvnc/Xvnc.java @@ -1,258 +1,258 @@ package hudson.plugins.xvnc; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.Proc; import hudson.Util; import hudson.model.BuildListener; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Computer; import hudson.model.Hudson; import hudson.model.Node; import hudson.tasks.BuildWrapper; import hudson.tasks.BuildWrapperDescriptor; import hudson.util.FormValidation; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; /** * {@link BuildWrapper} that runs <tt>xvnc</tt>. * * @author Kohsuke Kawaguchi */ public class Xvnc extends BuildWrapper { /** * Whether or not to take a screenshot upon completion of the build. */ public boolean takeScreenshot; public Boolean useXauthority; private static final String FILENAME_SCREENSHOT = "screenshot.jpg"; @DataBoundConstructor public Xvnc(boolean takeScreenshot, boolean useXauthority) { this.takeScreenshot = takeScreenshot; this.useXauthority = useXauthority; } @Override public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) throws IOException, InterruptedException { final PrintStream logger = listener.getLogger(); DescriptorImpl DESCRIPTOR = Hudson.getInstance().getDescriptorByType(DescriptorImpl.class); // skip xvnc execution if (build.getBuiltOn().getAssignedLabels().contains(Jenkins.getInstance().getLabelAtom("noxvnc")) || build.getBuiltOn().getNodeProperties().get(NodePropertyImpl.class) != null) { return new Environment(){}; } if (DESCRIPTOR.skipOnWindows && !launcher.isUnix()) { return new Environment(){}; } if (DESCRIPTOR.cleanUp) { maybeCleanUp(launcher, listener); } String cmd = Util.nullify(DESCRIPTOR.xvnc); if (cmd == null) { cmd = "vncserver :$DISPLAY_NUMBER -localhost -nolisten tcp"; } return doSetUp(build, launcher, logger, cmd, 10, DESCRIPTOR.minDisplayNumber, DESCRIPTOR.maxDisplayNumber); } private Environment doSetUp(AbstractBuild build, final Launcher launcher, final PrintStream logger, String cmd, int retries, int minDisplayNumber, int maxDisplayNumber) throws IOException, InterruptedException { final int displayNumber = allocator.allocate(minDisplayNumber, maxDisplayNumber); final String actualCmd = Util.replaceMacro(cmd, Collections.singletonMap("DISPLAY_NUMBER",String.valueOf(displayNumber))); logger.println(Messages.Xvnc_STARTING()); String[] cmds = Util.tokenize(actualCmd); final FilePath xauthority = build.getWorkspace().createTempFile(".Xauthority-", ""); final Map<String,String> xauthorityEnv = new HashMap<String, String>(); if (useXauthority) { - xauthorityEnv.put("XAUTHORITY", "\"" + xauthority.getRemote() + "\""); + xauthorityEnv.put("XAUTHORITY", xauthority.getRemote()); } final Proc proc = launcher.launch().cmds(cmds).envs(xauthorityEnv).stdout(logger).pwd(build.getWorkspace()).start(); final String vncserverCommand; if (cmds[0].endsWith("vncserver") && cmd.contains(":$DISPLAY_NUMBER")) { // Command just started the server; -kill will stop it. vncserverCommand = cmds[0]; int exit = proc.join(); if (exit != 0) { // XXX I18N String message = "Failed to run \'" + actualCmd + "\' (exit code " + exit + "), blacklisting display #" + displayNumber + "; consider checking the \"Clean up before start\" option"; // Do not release it; it may be "stuck" until cleaned up by an administrator. //allocator.free(displayNumber); allocator.blacklist(displayNumber); if (retries > 0) { return doSetUp(build, launcher, logger, cmd, retries - 1, minDisplayNumber, maxDisplayNumber); } else { throw new IOException(message); } } } else { vncserverCommand = null; } return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { env.put("DISPLAY",":"+displayNumber); env.putAll(xauthorityEnv); } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { if (takeScreenshot) { FilePath ws = build.getWorkspace(); File artifactsDir = build.getArtifactsDir(); artifactsDir.mkdirs(); logger.println(Messages.Xvnc_TAKING_SCREENSHOT()); launcher.launch().cmds("echo", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("ls", "-l", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("import", "-window", "root", "-display", ":" + displayNumber, FILENAME_SCREENSHOT). envs(xauthorityEnv).stdout(logger).pwd(ws).join(); ws.child(FILENAME_SCREENSHOT).copyTo(new FilePath(artifactsDir).child(FILENAME_SCREENSHOT)); } logger.println(Messages.Xvnc_TERMINATING()); if (vncserverCommand != null) { // #173: stopping the wrapper script will accomplish nothing. It has already exited, in fact. launcher.launch().cmds(vncserverCommand, "-kill", ":" + displayNumber).envs(xauthorityEnv).stdout(logger).join(); } else { // Assume it can be shut down by being killed. proc.kill(); } allocator.free(displayNumber); xauthority.delete(); return true; } }; } /** * Manages display numbers in use. */ private static final DisplayAllocator allocator = new DisplayAllocator(); /** * Whether {@link #maybeCleanUp} has already been run on a given node. */ private static final Map<Node,Boolean> cleanedUpOn = new WeakHashMap<Node,Boolean>(); // XXX I18N private static synchronized void maybeCleanUp(Launcher launcher, BuildListener listener) throws IOException, InterruptedException { Node node = Computer.currentComputer().getNode(); if (cleanedUpOn.put(node, true) != null) { return; } if (!launcher.isUnix()) { listener.error("Clean up not currently implemented for non-Unix nodes; skipping"); return; } PrintStream logger = listener.getLogger(); // ignore any error return codes launcher.launch().stdout(logger).cmds("pkill", "Xvnc").join(); launcher.launch().stdout(logger).cmds("pkill", "Xrealvnc").join(); launcher.launch().stdout(logger).cmds("sh", "-c", "rm -f /tmp/.X*-lock /tmp/.X11-unix/X*").join(); } @Extension public static final class DescriptorImpl extends BuildWrapperDescriptor { /** * xvnc command line. This can include macro. * * If null, the default will kick in. */ public String xvnc; /* * Base X display number. */ public int minDisplayNumber = 10; /* * Maximum X display number. */ public int maxDisplayNumber = 99; /** * If true, skip xvnc launch on all Windows slaves. */ public boolean skipOnWindows = true; /** * If true, try to clean up old processes and locks when first run. */ public boolean cleanUp = false; public DescriptorImpl() { super(Xvnc.class); load(); } public String getDisplayName() { return Messages.description(); } @Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { // XXX is this now the right style? req.bindJSON(this,json); save(); return true; } public boolean isApplicable(AbstractProject<?, ?> item) { return true; } public String getCommandline() { return xvnc; } public void setCommandline(String value) { this.xvnc = value; } public FormValidation doCheckCommandline(@QueryParameter String value) { if (Util.nullify(value) == null || value.contains("$DISPLAY_NUMBER")) { return FormValidation.ok(); } else { return FormValidation.warningWithMarkup(Messages.Xvnc_SHOULD_INCLUDE_DISPLAY_NUMBER()); } } } public Object readResolve() { if (useXauthority == null) useXauthority = true; return this; } }
true
true
private Environment doSetUp(AbstractBuild build, final Launcher launcher, final PrintStream logger, String cmd, int retries, int minDisplayNumber, int maxDisplayNumber) throws IOException, InterruptedException { final int displayNumber = allocator.allocate(minDisplayNumber, maxDisplayNumber); final String actualCmd = Util.replaceMacro(cmd, Collections.singletonMap("DISPLAY_NUMBER",String.valueOf(displayNumber))); logger.println(Messages.Xvnc_STARTING()); String[] cmds = Util.tokenize(actualCmd); final FilePath xauthority = build.getWorkspace().createTempFile(".Xauthority-", ""); final Map<String,String> xauthorityEnv = new HashMap<String, String>(); if (useXauthority) { xauthorityEnv.put("XAUTHORITY", "\"" + xauthority.getRemote() + "\""); } final Proc proc = launcher.launch().cmds(cmds).envs(xauthorityEnv).stdout(logger).pwd(build.getWorkspace()).start(); final String vncserverCommand; if (cmds[0].endsWith("vncserver") && cmd.contains(":$DISPLAY_NUMBER")) { // Command just started the server; -kill will stop it. vncserverCommand = cmds[0]; int exit = proc.join(); if (exit != 0) { // XXX I18N String message = "Failed to run \'" + actualCmd + "\' (exit code " + exit + "), blacklisting display #" + displayNumber + "; consider checking the \"Clean up before start\" option"; // Do not release it; it may be "stuck" until cleaned up by an administrator. //allocator.free(displayNumber); allocator.blacklist(displayNumber); if (retries > 0) { return doSetUp(build, launcher, logger, cmd, retries - 1, minDisplayNumber, maxDisplayNumber); } else { throw new IOException(message); } } } else { vncserverCommand = null; } return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { env.put("DISPLAY",":"+displayNumber); env.putAll(xauthorityEnv); } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { if (takeScreenshot) { FilePath ws = build.getWorkspace(); File artifactsDir = build.getArtifactsDir(); artifactsDir.mkdirs(); logger.println(Messages.Xvnc_TAKING_SCREENSHOT()); launcher.launch().cmds("echo", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("ls", "-l", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("import", "-window", "root", "-display", ":" + displayNumber, FILENAME_SCREENSHOT). envs(xauthorityEnv).stdout(logger).pwd(ws).join(); ws.child(FILENAME_SCREENSHOT).copyTo(new FilePath(artifactsDir).child(FILENAME_SCREENSHOT)); } logger.println(Messages.Xvnc_TERMINATING()); if (vncserverCommand != null) { // #173: stopping the wrapper script will accomplish nothing. It has already exited, in fact. launcher.launch().cmds(vncserverCommand, "-kill", ":" + displayNumber).envs(xauthorityEnv).stdout(logger).join(); } else { // Assume it can be shut down by being killed. proc.kill(); } allocator.free(displayNumber); xauthority.delete(); return true; } }; }
private Environment doSetUp(AbstractBuild build, final Launcher launcher, final PrintStream logger, String cmd, int retries, int minDisplayNumber, int maxDisplayNumber) throws IOException, InterruptedException { final int displayNumber = allocator.allocate(minDisplayNumber, maxDisplayNumber); final String actualCmd = Util.replaceMacro(cmd, Collections.singletonMap("DISPLAY_NUMBER",String.valueOf(displayNumber))); logger.println(Messages.Xvnc_STARTING()); String[] cmds = Util.tokenize(actualCmd); final FilePath xauthority = build.getWorkspace().createTempFile(".Xauthority-", ""); final Map<String,String> xauthorityEnv = new HashMap<String, String>(); if (useXauthority) { xauthorityEnv.put("XAUTHORITY", xauthority.getRemote()); } final Proc proc = launcher.launch().cmds(cmds).envs(xauthorityEnv).stdout(logger).pwd(build.getWorkspace()).start(); final String vncserverCommand; if (cmds[0].endsWith("vncserver") && cmd.contains(":$DISPLAY_NUMBER")) { // Command just started the server; -kill will stop it. vncserverCommand = cmds[0]; int exit = proc.join(); if (exit != 0) { // XXX I18N String message = "Failed to run \'" + actualCmd + "\' (exit code " + exit + "), blacklisting display #" + displayNumber + "; consider checking the \"Clean up before start\" option"; // Do not release it; it may be "stuck" until cleaned up by an administrator. //allocator.free(displayNumber); allocator.blacklist(displayNumber); if (retries > 0) { return doSetUp(build, launcher, logger, cmd, retries - 1, minDisplayNumber, maxDisplayNumber); } else { throw new IOException(message); } } } else { vncserverCommand = null; } return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { env.put("DISPLAY",":"+displayNumber); env.putAll(xauthorityEnv); } @Override public boolean tearDown(AbstractBuild build, BuildListener listener) throws IOException, InterruptedException { if (takeScreenshot) { FilePath ws = build.getWorkspace(); File artifactsDir = build.getArtifactsDir(); artifactsDir.mkdirs(); logger.println(Messages.Xvnc_TAKING_SCREENSHOT()); launcher.launch().cmds("echo", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("ls", "-l", "$XAUTHORITY").envs(xauthorityEnv).stdout(logger).pwd(ws).join(); launcher.launch().cmds("import", "-window", "root", "-display", ":" + displayNumber, FILENAME_SCREENSHOT). envs(xauthorityEnv).stdout(logger).pwd(ws).join(); ws.child(FILENAME_SCREENSHOT).copyTo(new FilePath(artifactsDir).child(FILENAME_SCREENSHOT)); } logger.println(Messages.Xvnc_TERMINATING()); if (vncserverCommand != null) { // #173: stopping the wrapper script will accomplish nothing. It has already exited, in fact. launcher.launch().cmds(vncserverCommand, "-kill", ":" + displayNumber).envs(xauthorityEnv).stdout(logger).join(); } else { // Assume it can be shut down by being killed. proc.kill(); } allocator.free(displayNumber); xauthority.delete(); return true; } }; }
diff --git a/source/com/anars/jbrackets/TemplateProcessor.java b/source/com/anars/jbrackets/TemplateProcessor.java index 828b7c4..951fd74 100644 --- a/source/com/anars/jbrackets/TemplateProcessor.java +++ b/source/com/anars/jbrackets/TemplateProcessor.java @@ -1,1044 +1,1044 @@ /** * Copyright (c) 2012 Anar Software LLC <http://anars.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.anars.jbrackets; import com.anars.jbrackets.exceptions.ArrayNotFoundException; import com.anars.jbrackets.exceptions.AttributeNotFoundException; import com.anars.jbrackets.exceptions.NotArrayException; import com.anars.jbrackets.exceptions.ObjectNotFoundException; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** */ public class TemplateProcessor { /** */ public static final double VERSION = 0.1; /** */ public static final long BUILD = 20120204; private static final String[] LATIN_WORDS = { // "abduco", "accipio", "acer", "acquiro", "addo", "adduco", "adeo", "adepto", "adfero", "adficio", // "adflicto", "adhuc", "aequitas", "aequus", "affero", "affligo", "agnosco", "alo", "altum", "alui", // "amo", "amplexus", "amplitudo", "animus", "antepono", "aperio", "arcis", "arguo", "arx", "attero", // "attollo", "autem", "autus", "auxilium", "bellus", "Berlinmonte", "bibo", "carcer", "casso", "celer", // "celeritas", "celeriter", "censura", "cito", "clarus", "coerceo", "cogito", "cohibeo", "comminuo", // "commisceo", "commodum", "concedo", "condico", "conor", "conservo", "consilium", "conspicio", // "constituo", "consulo", "consumo", "contineo", "corrumpo", "crebro", "cresco", "cretum", "cum", // "cupido", "cursim", "dare", "datum", "decorus", "decretum", "dedi", "defendo", "defero", "defluo", // "deinde", "denuncio", "detrimentum", "dexter", "dico", "dignitas", "dimitto", "directus", "diripio", // "discedo", "discessum", "discrepo", "do", "donum", "duco", "effero", "egredior", "egressus", "elatum", // "eo", "equitas", "equus", "excellentia", "exhibeo", "exibeo", "exigo", "exitus", "expleo", "expletum", // "explevi", "expugno", "extuli", "facina", "facio", "facultas", "facundia", "facunditas", "fateor", // "fatigo", "fatum", "faveo", "felicis", "felix", "ferus", "festinatio", "fidelis", "flatus", "fors", // "fortis", "fortuna", "fortunatus", "frequento", "gaudium", "gens", "grassor", "gregatim", "haesito", // "haud", "hesito", "honor", "iacio", "iam", "impedio", "impetus", "inanis", "inritus", "invado", "ire", // "irritus", "itum", "iudicium", "iustus", "jaculum", "judicium", "laedo", "laetificus", "laevus", "lamia", // "laqueus", "laudo", "ledo", "letificus", "leviculus", "levis", "levo", "levus", "liber", "libera", // "libero", "liberum", "macero", "macto", "malum", "maneo", "mansuetus", "maxime", "mereo", "modo", // "moris", "mos", "mundus", "narro", "nequaquam", "nimirum", "non", "nota", "novitas", "novus", "numerus", // "nunc", "nusquam", "nutrio", "nutus", "obduro", "ocius", "officium", "ordinatio", "pendo", "penus", // "percepi", "perceptum", "percipio", "perdo", "perfectus", "perscitus", "pertinax", "pessum", "placide", // "placidus", "placitum", "plenus", "plerusque", "plurimus", "poema", "poematis", "praeclarus", "praeda", // "praesto", "preclarus", "preda", "prehendo", "presto", "pretium", "priscus", "pristinus", "probo", // "proficio", "progredior", "progressus", "prohibeo", "promptus", "prope", "proventus", "pulcher", // "pulchra", "pulchrum", "puto", "qualitas", "qualiter", "quasi", "quies", "quietis", "ratio", "recolo", // "recordatio", "rectum", "rectus", "reddo", "regina", "rei", "relaxo", "renuntio", "repens", "reperio", // "repeto", "repleo", "reprehendo", "requiro", "res", "retineo", "rideo", "risi", "risum", "rubor", "rumor", // "salus", "saluto", "salutor", "sanctimonia", "sane", "sanitas", "sapiens", "sapienter", "sceleris", // "scelus", "scisco", "securus", "secus", "seditio", "sentio", "sepelio", "servo", "sicut", "silentium", // "similis", "singularis", "sino", "siquidem", "solus", "solvo", "somnium", "speciosus", "strenuus", // "subiungo", "subvenio", "succurro", "suffragium", "summopere", "super", "suscipio", "tamen", "tamquam", // "tanquam", "tectum", "tego", "tendo", "teneo", "tergum", "terra", "tersus", "texi", "totus", "tribuo", // "turpis", "universitas", "universum", "us", "usus", "utilis", "utilitas", "valde", "valens", "velociter", // "velox", "velut", "venia", "vergo", "videlicet", "video", "vidi", "vindico", "vires", "vis", "visum", // "vocis", "voco", "volo", "voluntas", "vomica", "vox" // } ; private static final String VO_NAME_CLASS_VERSION = "jb_class_version"; private static final String VO_NAME_CLASS_BUILD = "jb_class_build"; private static final String VO_NAME_LOCALE_CODE = "jb_locale_code"; private static final String VO_NAME_LOCALE_NAME = "jb_locale_name"; private static final String VO_NAME_COUNTRY_CODE = "jb_country_code"; private static final String VO_NAME_COUNTRY_NAME = "jb_country_name"; private static final String VO_NAME_LANGUAGE_CODE = "jb_language_code"; private static final String VO_NAME_LANGUAGE_NAME = "jb_language_name"; // private static final String LOOP = "loop"; private static final String SHOW_RANDOMLY = "show-randomly"; private static final String REPEAT = "repeat"; private static final String RANDOM_NUMBER = "random-number"; private static final String DRAW = "draw"; private static final String DATE = "date"; private static final String TIME = "time"; private static final String GET = "get"; private static final String SET = "set"; private static final String PROPERTY = "property"; private static final String LOREM_IPSUM = "lorem-ipsum"; private static final String FORMAT = "format"; private static final String IF = "if"; // private Logger _logger = Logger.getLogger(getClass().getCanonicalName()); // private Pattern _pattern = Pattern.compile( // "\\{" + LOOP + ":(\\w+)(:\\-?\\d+)?\\}.*?\\{/" + LOOP + ":\\1\\}|" + // "\\{" + SHOW_RANDOMLY + ":(\\w+)\\}.*?\\{/" + SHOW_RANDOMLY + ":\\3\\}|" + // "\\{" + REPEAT + ":(\\w+):\\d+(:\\d+)?\\}.*?\\{/" + REPEAT + ":\\4\\}|" + // "\\{" + RANDOM_NUMBER + ":\\-?\\d+:\\-?\\d+\\}|" + // "\\{" + DRAW + ":\\w+:\\w+(:\\w+)*\\}|" + // "\\{" + DATE + ":[GyMwWDdFE]+(:\\w{2}){0,2}\\}|" + // "\\{" + TIME + ":[aHkKhmsSzZ]+(:\\w{2}){0,2}\\}|" + // "\\{" + GET + ":\\w+((\\[\\d+\\])?(\\.\\w+)?|(\\.\\-value|\\.\\-offset|\\.\\-length|\\.\\-first|\\.\\-last))?\\}|" + // "\\{" + PROPERTY + ":[^}]*\\}|" + // "\\{" + LOREM_IPSUM + ":\\d+:\\d+\\}|" + // "\\{" + SET + ":(\\w+)\\}.*?\\{/" + SET + ":\\13\\}|" + // "\\{" + FORMAT + ":(\\w+)(:\\w{2}){0,2}\\}.*?\\{/" + FORMAT + ":\\14\\}|" + // "\\{" + IF + ":(\\w+):((\\w+((\\[\\d+\\])?(\\.\\w+)|(\\.\\-value|\\.\\-offset|\\.\\-length|\\.\\-first|\\.\\-last))?)|" + // "([\'][^\']*[\'])):(equals|equals-ignore-case|not-equals|not-equals-ignore-case|greater-than|greater-than-or-equals|" + // "less-than|less-than-or-equals|empty|not-empty|exists|not-exists|even-number|odd-number)(:((\\w+((\\[\\d+\\])?(\\.\\w+)|" + // "(\\.\\-value|\\.\\-offset|\\.\\-length|\\.\\-first|\\.\\-last))?)|([\'][^\']*[\'])))?\\}.*?\\{/" + IF + ":\\16\\}", // Pattern.CASE_INSENSITIVE | Pattern.DOTALL); private Locale _locale = null; private Hashtable<String, Object> _valueObjects = new Hashtable<String, Object>(); private Hashtable<String, SpanFormatter> _spanFormatters = new Hashtable<String, SpanFormatter>(); /** */ public TemplateProcessor() { super(); putValueObject(VO_NAME_CLASS_VERSION, VERSION); putValueObject(VO_NAME_CLASS_BUILD, BUILD); setLocale(Locale.getDefault()); } /** * @param locale * @param valueObjects */ public TemplateProcessor(Locale locale, Hashtable<String, Object> valueObjects) { this(); setLocale(locale); setValueObjects(valueObjects); } /** * @param locale */ public TemplateProcessor(Locale locale) { this(); setLocale(locale); } /** * @param valueObjects */ public TemplateProcessor(Hashtable<String, Object> valueObjects) { this(); setValueObjects(valueObjects); } /** * @param valueObjects */ public synchronized void setValueObjects(Hashtable<String, Object> valueObjects) { _valueObjects = valueObjects; } /** * @return */ public synchronized Hashtable<String, Object> getValueObjects() { return (_valueObjects); } /** */ public synchronized void clearValueObjects() { _valueObjects.clear(); } /** * @param name * @param valueObject * @return */ public synchronized Object putValueObject(String name, Object valueObject) { return (valueObject != null ? _valueObjects.put(name.toLowerCase(), valueObject) : null); } /** * @param name * @return */ public synchronized Object getValueObject(String name) { return (_valueObjects.get(name.toLowerCase())); } /** * @param name * @return */ public synchronized Object removeValueObject(String name) { return (_valueObjects.remove(name.toLowerCase())); } /** * @return */ public synchronized boolean hasAnyValueObjects() { return (!_valueObjects.isEmpty()); } /** * @return */ public synchronized int valueObjectCount() { return (_valueObjects.size()); } /** * @param name * @return */ public synchronized boolean containsValueObjectName(String name) { return (_valueObjects.containsKey(name.toLowerCase())); } /** * @param valueObject * @return */ public synchronized boolean containsValueObject(Object valueObject) { return (_valueObjects.containsValue(valueObject)); } /** * @return */ public synchronized Enumeration<String> valueObjectNames() { return (_valueObjects.keys()); } /** * @return */ public synchronized Collection<Object> valueObjects() { return (_valueObjects.values()); } /** */ public synchronized void clearSpanFormatters() { _spanFormatters.clear(); } /** * @param name * @param spanFormatter * @return */ public synchronized SpanFormatter putSpanFormatter(String name, SpanFormatter spanFormatter) { return (_spanFormatters.put(name, spanFormatter)); } /** * @param name * @return */ public synchronized SpanFormatter getSpanFormatter(String name) { return (_spanFormatters.get(name)); } /** * @param name * @return */ public synchronized SpanFormatter removeSpanFormatter(String name) { return (_spanFormatters.remove(name)); } /** * @return */ public synchronized boolean hasAnySpanFormatters() { return (!_spanFormatters.isEmpty()); } /** * @return */ public synchronized int spanFormatterCount() { return (_spanFormatters.size()); } /** * @param name * @return */ public synchronized boolean containsSpanFormatterName(String name) { return (_spanFormatters.containsKey(name)); } /** * @param spanFormatter * @return */ public synchronized boolean containsSpanFormatter(SpanFormatter spanFormatter) { return (_spanFormatters.containsValue(spanFormatter)); } /** * @return */ public synchronized Enumeration<String> spanFormatterNames() { return (_spanFormatters.keys()); } /** * @return */ public synchronized Collection<SpanFormatter> spanFormatters() { return (_spanFormatters.values()); } /** * @param locale */ public void setLocale(Locale locale) { _locale = locale; putValueObject(VO_NAME_LOCALE_CODE, locale.toString()); putValueObject(VO_NAME_LOCALE_NAME, locale.getDisplayName(locale)); putValueObject(VO_NAME_COUNTRY_CODE, locale.getCountry()); putValueObject(VO_NAME_COUNTRY_NAME, locale.getDisplayCountry(locale)); putValueObject(VO_NAME_LANGUAGE_CODE, locale.getLanguage()); putValueObject(VO_NAME_LANGUAGE_NAME, locale.getDisplayLanguage(locale)); } /** * @return */ public Locale getLocale() { return (_locale); } /** * @param templateFile * @return * @throws IOException * @throws FileNotFoundException */ public String apply(File templateFile) throws IOException, FileNotFoundException { BufferedReader bufferedReader = new BufferedReader(new FileReader(templateFile)); StringBuffer stringBuffer = new StringBuffer(); String lineSeparator = System.getProperty("line.separator"); try { String lineString = bufferedReader.readLine(); while (lineString != null) { stringBuffer.append(lineString); stringBuffer.append(lineSeparator); lineString = bufferedReader.readLine(); } } finally { bufferedReader.close(); } return (apply(stringBuffer.toString())); } /** * @param templateString * @return */ public String apply(String templateString) { Matcher matcher = _pattern.matcher(templateString); StringBuffer stringBuffer = new StringBuffer(); while (matcher.find()) { String matchedString = substring(matcher.group(), "{", "}", false); String replacement = null; String[] pieces = matchedString.split(":"); if (pieces[0].equals(RANDOM_NUMBER)) { try { int startNumber = Integer.parseInt(pieces[1]); replacement = "" + ((int) (Math.random() * (Integer.parseInt(pieces[2]) - startNumber + 1)) + startNumber); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(LOREM_IPSUM)) { int minSentences = 1; int maxSentences = 1; try { minSentences = Integer.parseInt(pieces[1]); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } try { maxSentences = Integer.parseInt(pieces[2]); } catch (Exception exception) { maxSentences = minSentences; _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } int sentences = (int) (Math.random() * (maxSentences - minSentences + 1)) + minSentences; StringBuffer stringBufferParagraph = new StringBuffer("Lorem ipsum"); for (int sentenceIndex = 0; sentenceIndex < sentences; sentenceIndex++) { int wordCount = (int) (Math.random() * 6) + 3; for (int wordIndex = 0; wordIndex < wordCount; wordIndex++) { String word = LATIN_WORDS[(int) (Math.random() * LATIN_WORDS.length)]; if (wordIndex == 0 && sentenceIndex != 0) stringBufferParagraph.append(" " + word.substring(0, 1).toUpperCase() + word.substring(1)); else stringBufferParagraph.append(" " + word); } switch ((int) Math.random() * 10) { case 8: stringBufferParagraph.append("!"); break; case 9: stringBufferParagraph.append("?"); break; default: stringBufferParagraph.append("."); break; } } replacement = stringBufferParagraph.toString(); } else if (pieces[0].equals(DATE) || pieces[0].equals(TIME)) { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); try { replacement = (new SimpleDateFormat(pieces[1], locale)).format(new Date()); } catch (IllegalArgumentException illegalArgumentException) { _logger.log(Level.SEVERE, "Invalid date and time format; \"" + pieces[1] + "\".", illegalArgumentException); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(GET)) { try { Object object = getObjectValue(pieces[1]); replacement = object.toString(); } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(LOOP)) { try { int increment = 1; if (pieces.length == 3) increment = Integer.parseInt(pieces[2]); Object[] object = (Object[]) _valueObjects.get(pieces[1].toLowerCase()); if (object != null) { String loopTemplate = substring(matcher.group(), "}", "{/"); replacement = ""; if (increment > 0) for (int index = 0; index < object.length; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index + 1 >= object.length)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } else if (increment < 0) for (int index = object.length - 1; index >= 0; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == object.length - 1)); putValueObject(pieces[1] + "-last", (index == 0)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(IF)) { boolean condition = false; String ifBlock = substring(matcher.group(), "}", "{/"); if (pieces[3].equals("exists") || pieces[3].equals("not-exists")) { try { getObjectValue(pieces[2]); condition = pieces[3].equals("exists"); } catch (Exception exception) { condition = pieces[3].equals("not-exists"); } } else { try { String leftSideStr = ""; if (pieces[2].startsWith("'") && pieces[2].endsWith("'")) { leftSideStr = pieces[2].substring(1).substring(0, pieces[2].length() - 2); } else { Object leftSideObj = getObjectValue(pieces[2]); leftSideStr = leftSideObj == null ? "" : leftSideObj.toString(); } String rightSideStr = ""; if (pieces.length == 5) if (pieces[4].startsWith("'") && pieces[4].endsWith("'")) { rightSideStr = pieces[4].substring(1).substring(0, pieces[4].length() - 2); } else { Object rightSideObj = getObjectValue(pieces[4]); rightSideStr = rightSideObj == null ? "" : rightSideObj.toString(); } if (pieces[3].equals("equals")) { condition = leftSideStr.equals(rightSideStr); } else if (pieces[3].equals("not-equals")) { condition = !leftSideStr.equals(rightSideStr); } - if (pieces[3].equals("equals-ignore-case")) + else if (pieces[3].equals("equals-ignore-case")) { condition = leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("not-equals-ignore-case")) { condition = !leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("empty")) { condition = leftSideStr.equals(""); } else if (pieces[3].equals("not-empty")) { condition = !leftSideStr.equals(""); } else { int leftSideInt = 0; int rightSideInt = 0; try { if (!leftSideStr.equals("")) leftSideInt = Integer.parseInt(leftSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } try { if (!rightSideStr.equals("")) rightSideInt = Integer.parseInt(rightSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } if (pieces[3].equals("greater-than")) { condition = leftSideInt > rightSideInt; } else if (pieces[3].equals("greater-than-or-equals")) { condition = leftSideInt >= rightSideInt; } else if (pieces[3].equals("less-than")) { condition = leftSideInt < rightSideInt; } else if (pieces[3].equals("less-than-or-equals")) { condition = leftSideInt <= rightSideInt; } else if (pieces[3].equals("even-number")) { condition = leftSideInt % 2 == 0 && leftSideInt != 0; } else if (pieces[3].equals("odd-number")) { condition = leftSideInt % 2 == 1 && leftSideInt != 0; } } } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } replacement = condition ? apply(ifBlock) : ""; } else if (pieces[0].equals(SHOW_RANDOMLY)) { String randomlyBlock = substring(matcher.group(), "}", "{/"); replacement = (int) (Math.random() * 2.0) == 1 ? apply(randomlyBlock) : ""; } else if (pieces[0].equals(DRAW)) { replacement = pieces[1 + (int) (Math.random() * pieces.length - 1)]; } else if (pieces[0].equals(REPEAT)) { int repeatTimes = 1; try { if (pieces.length == 4) { int startNumber = repeatTimes = Integer.parseInt(pieces[2]); repeatTimes = ((int) (Math.random() * (Integer.parseInt(pieces[3]) - startNumber + 1)) + startNumber); } else { repeatTimes = Integer.parseInt(pieces[2]); } } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } String repeatBlock = substring(matcher.group(), "}", "{/"); replacement = ""; putValueObject(pieces[1], ""); putValueObject(pieces[1] + "-length", repeatTimes); for (int index = 0; index < repeatTimes; index++) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index == repeatTimes - 1)); putValueObject(pieces[1] + "-value", index + 1); replacement += apply(repeatBlock); } removeValueObject(pieces[1] + "-length"); removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); removeValueObject(pieces[1]); } else if (pieces[0].equals(PROPERTY)) { replacement = System.getProperty(pieces[1], ""); } else if (pieces[0].equals(FORMAT)) { try { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); SpanFormatter spanFormatter = _spanFormatters.get(pieces[1]); if (spanFormatter != null) { String spanTemplate = substring(matcher.group(), "}", "{/"); replacement = spanFormatter.format(apply(spanTemplate), locale); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(SET)) { if (!pieces[1].equalsIgnoreCase(VO_NAME_CLASS_VERSION) && !pieces[1].equalsIgnoreCase(VO_NAME_CLASS_BUILD) && // !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_NAME)) { putValueObject(pieces[1], apply(substring(matcher.group(), "}", "{/"))); } else if (pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE)) { String localeString = substring(matcher.group(), "}", "{/").trim(); if (localeString.length() == 0) setLocale(Locale.getDefault()); else if (localeString.length() == 2) setLocale(new Locale(localeString)); else if (localeString.length() == 5 && localeString.charAt(2) == '_') setLocale(new Locale(localeString.substring(0, 2), localeString.substring(3))); } } matcher.appendReplacement(stringBuffer, replacement == null ? "" : replacement); replacement = null; } matcher.appendTail(stringBuffer); matcher = null; String output = stringBuffer.toString(); if (_pattern.matcher(output).find()) output = apply(output); return (output); } private Object[] getArrayObject(String name) throws ArrayNotFoundException, NotArrayException { try { Object[] objArray = (Object[]) _valueObjects.get(name.toLowerCase()); if (objArray == null) throw new ArrayNotFoundException(name); return (objArray); } catch (ClassCastException classCastException) { throw new NotArrayException(name); } } private Object getObjectValue(String name) throws ArrayNotFoundException, NotArrayException, ArrayIndexOutOfBoundsException, ObjectNotFoundException, AttributeNotFoundException { String[] pieces = name.split("[.]"); Object object = null; if (pieces[0].endsWith("]")) { String arrayName = null; int index = 0; try { arrayName = pieces[0].substring(0, pieces[0].indexOf("[")); index = Integer.parseInt(pieces[0].substring(pieces[0].indexOf("[") + 1, pieces[0].length() - 1)) - 1; if (index < 0) throw new ArrayIndexOutOfBoundsException("0"); object = getArrayObject(arrayName)[index]; } catch (IndexOutOfBoundsException indexOutOfBoundsException) { throw new ArrayIndexOutOfBoundsException("" + index); } } else { object = _valueObjects.get(pieces[0].toLowerCase()); } if (object == null) { throw new ObjectNotFoundException(pieces[0]); } else if (pieces.length == 2) { if (pieces[1].toLowerCase().equals("-length")) { Object offsetValue = _valueObjects.get(pieces[0].toLowerCase() + "-length"); return (offsetValue == null ? getArrayObject(pieces[0]).length : offsetValue); } else if (pieces[1].toLowerCase().equals("-offset") | pieces[1].toLowerCase().equals("-value")) { Object offsetValue = _valueObjects.get(pieces[0].toLowerCase() + pieces[1].toLowerCase()); return (offsetValue == null ? 0 : offsetValue); } else if (pieces[1].toLowerCase().equals("-first") || pieces[1].toLowerCase().equals("-last")) { return (((Boolean) _valueObjects.get(pieces[0].toLowerCase() + pieces[1].toLowerCase())).booleanValue()); } else { boolean found = false; try { if (object instanceof Properties) { Properties properties = (Properties) object; object = properties.getProperty(pieces[1]); found = object != null; } else { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (int index = 0; index < descriptors.length && !found; index++) if (descriptors[index].getName().equals(pieces[1])) { object = descriptors[index].getReadMethod().invoke(object); found = true; } } } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } if (!found) throw new AttributeNotFoundException("Attribute :" + pieces[1] + " in " + name); } } return (object); } /** */ public void loadAllSpanFormatters() { loadAllSpanFormatters(null); } /** * @param rootPackageName */ public void loadAllSpanFormatters(String rootPackageName) { try { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (rootPackageName == null) rootPackageName = "com.anars.jbrackets.formatters"; else rootPackageName = rootPackageName.trim(); String path = rootPackageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> directories = new ArrayList<File>(); while (resources.hasMoreElements()) directories.add(new File(resources.nextElement().getFile())); ArrayList<Class> classes = new ArrayList<Class>(); for (File directory : directories) classes.addAll(findClasses(directory, rootPackageName)); for (Class formatterClass : classes) { String formatterName = formatterClass.getSimpleName(); if (formatterName.endsWith("SpanFormatter")) formatterName = formatterName.substring(0, formatterName.length() - 13); putSpanFormatter(formatterName, (SpanFormatter) formatterClass.newInstance()); } } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } private List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class> classList = new ArrayList<Class>(); if (!directory.exists()) return classList; File[] files = directory.listFiles(); for (File file : files) if (file.isDirectory()) { if (packageName.startsWith(".")) packageName = packageName.substring(1); classList.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { Class cls = Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)); if (cls.getSuperclass().getName().equals("com.anars.jbrackets.SpanFormatter")) classList.add(cls); } return (classList); } private String substring(String string, String start, String end) { return (substring(string, start, end, true)); } private String substring(String string, String start, String end, boolean lastIndex) { String substring = string; substring = substring.substring(substring.indexOf(start) + 1); substring = substring.substring(0, lastIndex ? substring.lastIndexOf(end) : substring.indexOf(end)); return (substring); } }
true
true
public String apply(String templateString) { Matcher matcher = _pattern.matcher(templateString); StringBuffer stringBuffer = new StringBuffer(); while (matcher.find()) { String matchedString = substring(matcher.group(), "{", "}", false); String replacement = null; String[] pieces = matchedString.split(":"); if (pieces[0].equals(RANDOM_NUMBER)) { try { int startNumber = Integer.parseInt(pieces[1]); replacement = "" + ((int) (Math.random() * (Integer.parseInt(pieces[2]) - startNumber + 1)) + startNumber); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(LOREM_IPSUM)) { int minSentences = 1; int maxSentences = 1; try { minSentences = Integer.parseInt(pieces[1]); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } try { maxSentences = Integer.parseInt(pieces[2]); } catch (Exception exception) { maxSentences = minSentences; _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } int sentences = (int) (Math.random() * (maxSentences - minSentences + 1)) + minSentences; StringBuffer stringBufferParagraph = new StringBuffer("Lorem ipsum"); for (int sentenceIndex = 0; sentenceIndex < sentences; sentenceIndex++) { int wordCount = (int) (Math.random() * 6) + 3; for (int wordIndex = 0; wordIndex < wordCount; wordIndex++) { String word = LATIN_WORDS[(int) (Math.random() * LATIN_WORDS.length)]; if (wordIndex == 0 && sentenceIndex != 0) stringBufferParagraph.append(" " + word.substring(0, 1).toUpperCase() + word.substring(1)); else stringBufferParagraph.append(" " + word); } switch ((int) Math.random() * 10) { case 8: stringBufferParagraph.append("!"); break; case 9: stringBufferParagraph.append("?"); break; default: stringBufferParagraph.append("."); break; } } replacement = stringBufferParagraph.toString(); } else if (pieces[0].equals(DATE) || pieces[0].equals(TIME)) { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); try { replacement = (new SimpleDateFormat(pieces[1], locale)).format(new Date()); } catch (IllegalArgumentException illegalArgumentException) { _logger.log(Level.SEVERE, "Invalid date and time format; \"" + pieces[1] + "\".", illegalArgumentException); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(GET)) { try { Object object = getObjectValue(pieces[1]); replacement = object.toString(); } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(LOOP)) { try { int increment = 1; if (pieces.length == 3) increment = Integer.parseInt(pieces[2]); Object[] object = (Object[]) _valueObjects.get(pieces[1].toLowerCase()); if (object != null) { String loopTemplate = substring(matcher.group(), "}", "{/"); replacement = ""; if (increment > 0) for (int index = 0; index < object.length; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index + 1 >= object.length)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } else if (increment < 0) for (int index = object.length - 1; index >= 0; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == object.length - 1)); putValueObject(pieces[1] + "-last", (index == 0)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(IF)) { boolean condition = false; String ifBlock = substring(matcher.group(), "}", "{/"); if (pieces[3].equals("exists") || pieces[3].equals("not-exists")) { try { getObjectValue(pieces[2]); condition = pieces[3].equals("exists"); } catch (Exception exception) { condition = pieces[3].equals("not-exists"); } } else { try { String leftSideStr = ""; if (pieces[2].startsWith("'") && pieces[2].endsWith("'")) { leftSideStr = pieces[2].substring(1).substring(0, pieces[2].length() - 2); } else { Object leftSideObj = getObjectValue(pieces[2]); leftSideStr = leftSideObj == null ? "" : leftSideObj.toString(); } String rightSideStr = ""; if (pieces.length == 5) if (pieces[4].startsWith("'") && pieces[4].endsWith("'")) { rightSideStr = pieces[4].substring(1).substring(0, pieces[4].length() - 2); } else { Object rightSideObj = getObjectValue(pieces[4]); rightSideStr = rightSideObj == null ? "" : rightSideObj.toString(); } if (pieces[3].equals("equals")) { condition = leftSideStr.equals(rightSideStr); } else if (pieces[3].equals("not-equals")) { condition = !leftSideStr.equals(rightSideStr); } if (pieces[3].equals("equals-ignore-case")) { condition = leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("not-equals-ignore-case")) { condition = !leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("empty")) { condition = leftSideStr.equals(""); } else if (pieces[3].equals("not-empty")) { condition = !leftSideStr.equals(""); } else { int leftSideInt = 0; int rightSideInt = 0; try { if (!leftSideStr.equals("")) leftSideInt = Integer.parseInt(leftSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } try { if (!rightSideStr.equals("")) rightSideInt = Integer.parseInt(rightSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } if (pieces[3].equals("greater-than")) { condition = leftSideInt > rightSideInt; } else if (pieces[3].equals("greater-than-or-equals")) { condition = leftSideInt >= rightSideInt; } else if (pieces[3].equals("less-than")) { condition = leftSideInt < rightSideInt; } else if (pieces[3].equals("less-than-or-equals")) { condition = leftSideInt <= rightSideInt; } else if (pieces[3].equals("even-number")) { condition = leftSideInt % 2 == 0 && leftSideInt != 0; } else if (pieces[3].equals("odd-number")) { condition = leftSideInt % 2 == 1 && leftSideInt != 0; } } } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } replacement = condition ? apply(ifBlock) : ""; } else if (pieces[0].equals(SHOW_RANDOMLY)) { String randomlyBlock = substring(matcher.group(), "}", "{/"); replacement = (int) (Math.random() * 2.0) == 1 ? apply(randomlyBlock) : ""; } else if (pieces[0].equals(DRAW)) { replacement = pieces[1 + (int) (Math.random() * pieces.length - 1)]; } else if (pieces[0].equals(REPEAT)) { int repeatTimes = 1; try { if (pieces.length == 4) { int startNumber = repeatTimes = Integer.parseInt(pieces[2]); repeatTimes = ((int) (Math.random() * (Integer.parseInt(pieces[3]) - startNumber + 1)) + startNumber); } else { repeatTimes = Integer.parseInt(pieces[2]); } } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } String repeatBlock = substring(matcher.group(), "}", "{/"); replacement = ""; putValueObject(pieces[1], ""); putValueObject(pieces[1] + "-length", repeatTimes); for (int index = 0; index < repeatTimes; index++) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index == repeatTimes - 1)); putValueObject(pieces[1] + "-value", index + 1); replacement += apply(repeatBlock); } removeValueObject(pieces[1] + "-length"); removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); removeValueObject(pieces[1]); } else if (pieces[0].equals(PROPERTY)) { replacement = System.getProperty(pieces[1], ""); } else if (pieces[0].equals(FORMAT)) { try { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); SpanFormatter spanFormatter = _spanFormatters.get(pieces[1]); if (spanFormatter != null) { String spanTemplate = substring(matcher.group(), "}", "{/"); replacement = spanFormatter.format(apply(spanTemplate), locale); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(SET)) { if (!pieces[1].equalsIgnoreCase(VO_NAME_CLASS_VERSION) && !pieces[1].equalsIgnoreCase(VO_NAME_CLASS_BUILD) && // !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_NAME)) { putValueObject(pieces[1], apply(substring(matcher.group(), "}", "{/"))); } else if (pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE)) { String localeString = substring(matcher.group(), "}", "{/").trim(); if (localeString.length() == 0) setLocale(Locale.getDefault()); else if (localeString.length() == 2) setLocale(new Locale(localeString)); else if (localeString.length() == 5 && localeString.charAt(2) == '_') setLocale(new Locale(localeString.substring(0, 2), localeString.substring(3))); } } matcher.appendReplacement(stringBuffer, replacement == null ? "" : replacement); replacement = null; } matcher.appendTail(stringBuffer); matcher = null; String output = stringBuffer.toString(); if (_pattern.matcher(output).find()) output = apply(output); return (output); }
public String apply(String templateString) { Matcher matcher = _pattern.matcher(templateString); StringBuffer stringBuffer = new StringBuffer(); while (matcher.find()) { String matchedString = substring(matcher.group(), "{", "}", false); String replacement = null; String[] pieces = matchedString.split(":"); if (pieces[0].equals(RANDOM_NUMBER)) { try { int startNumber = Integer.parseInt(pieces[1]); replacement = "" + ((int) (Math.random() * (Integer.parseInt(pieces[2]) - startNumber + 1)) + startNumber); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(LOREM_IPSUM)) { int minSentences = 1; int maxSentences = 1; try { minSentences = Integer.parseInt(pieces[1]); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } try { maxSentences = Integer.parseInt(pieces[2]); } catch (Exception exception) { maxSentences = minSentences; _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } int sentences = (int) (Math.random() * (maxSentences - minSentences + 1)) + minSentences; StringBuffer stringBufferParagraph = new StringBuffer("Lorem ipsum"); for (int sentenceIndex = 0; sentenceIndex < sentences; sentenceIndex++) { int wordCount = (int) (Math.random() * 6) + 3; for (int wordIndex = 0; wordIndex < wordCount; wordIndex++) { String word = LATIN_WORDS[(int) (Math.random() * LATIN_WORDS.length)]; if (wordIndex == 0 && sentenceIndex != 0) stringBufferParagraph.append(" " + word.substring(0, 1).toUpperCase() + word.substring(1)); else stringBufferParagraph.append(" " + word); } switch ((int) Math.random() * 10) { case 8: stringBufferParagraph.append("!"); break; case 9: stringBufferParagraph.append("?"); break; default: stringBufferParagraph.append("."); break; } } replacement = stringBufferParagraph.toString(); } else if (pieces[0].equals(DATE) || pieces[0].equals(TIME)) { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); try { replacement = (new SimpleDateFormat(pieces[1], locale)).format(new Date()); } catch (IllegalArgumentException illegalArgumentException) { _logger.log(Level.SEVERE, "Invalid date and time format; \"" + pieces[1] + "\".", illegalArgumentException); } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } } else if (pieces[0].equals(GET)) { try { Object object = getObjectValue(pieces[1]); replacement = object.toString(); } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(LOOP)) { try { int increment = 1; if (pieces.length == 3) increment = Integer.parseInt(pieces[2]); Object[] object = (Object[]) _valueObjects.get(pieces[1].toLowerCase()); if (object != null) { String loopTemplate = substring(matcher.group(), "}", "{/"); replacement = ""; if (increment > 0) for (int index = 0; index < object.length; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index + 1 >= object.length)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } else if (increment < 0) for (int index = object.length - 1; index >= 0; index += increment) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == object.length - 1)); putValueObject(pieces[1] + "-last", (index == 0)); putValueObject(pieces[1] + "-value", object[index]); replacement += apply(loopTemplate); } removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(IF)) { boolean condition = false; String ifBlock = substring(matcher.group(), "}", "{/"); if (pieces[3].equals("exists") || pieces[3].equals("not-exists")) { try { getObjectValue(pieces[2]); condition = pieces[3].equals("exists"); } catch (Exception exception) { condition = pieces[3].equals("not-exists"); } } else { try { String leftSideStr = ""; if (pieces[2].startsWith("'") && pieces[2].endsWith("'")) { leftSideStr = pieces[2].substring(1).substring(0, pieces[2].length() - 2); } else { Object leftSideObj = getObjectValue(pieces[2]); leftSideStr = leftSideObj == null ? "" : leftSideObj.toString(); } String rightSideStr = ""; if (pieces.length == 5) if (pieces[4].startsWith("'") && pieces[4].endsWith("'")) { rightSideStr = pieces[4].substring(1).substring(0, pieces[4].length() - 2); } else { Object rightSideObj = getObjectValue(pieces[4]); rightSideStr = rightSideObj == null ? "" : rightSideObj.toString(); } if (pieces[3].equals("equals")) { condition = leftSideStr.equals(rightSideStr); } else if (pieces[3].equals("not-equals")) { condition = !leftSideStr.equals(rightSideStr); } else if (pieces[3].equals("equals-ignore-case")) { condition = leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("not-equals-ignore-case")) { condition = !leftSideStr.equalsIgnoreCase(rightSideStr); } else if (pieces[3].equals("empty")) { condition = leftSideStr.equals(""); } else if (pieces[3].equals("not-empty")) { condition = !leftSideStr.equals(""); } else { int leftSideInt = 0; int rightSideInt = 0; try { if (!leftSideStr.equals("")) leftSideInt = Integer.parseInt(leftSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } try { if (!rightSideStr.equals("")) rightSideInt = Integer.parseInt(rightSideStr); } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } if (pieces[3].equals("greater-than")) { condition = leftSideInt > rightSideInt; } else if (pieces[3].equals("greater-than-or-equals")) { condition = leftSideInt >= rightSideInt; } else if (pieces[3].equals("less-than")) { condition = leftSideInt < rightSideInt; } else if (pieces[3].equals("less-than-or-equals")) { condition = leftSideInt <= rightSideInt; } else if (pieces[3].equals("even-number")) { condition = leftSideInt % 2 == 0 && leftSideInt != 0; } else if (pieces[3].equals("odd-number")) { condition = leftSideInt % 2 == 1 && leftSideInt != 0; } } } catch (ObjectNotFoundException objectNotFoundException) { _logger.log(Level.SEVERE, "Object Not Found", objectNotFoundException); } catch (AttributeNotFoundException attributeNotFoundException) { _logger.log(Level.SEVERE, "Attribute Not Found", attributeNotFoundException); } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) { _logger.log(Level.SEVERE, "Array Index Out Of Bound", arrayIndexOutOfBoundsException); } catch (NotArrayException notArrayException) { _logger.log(Level.SEVERE, "Not An Array", notArrayException); } catch (ArrayNotFoundException arrayNotFoundException) { _logger.log(Level.SEVERE, "Array Not Found", arrayNotFoundException); } catch (NullPointerException nullPointerException) { _logger.log(Level.SEVERE, "Null Pointer", nullPointerException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } replacement = condition ? apply(ifBlock) : ""; } else if (pieces[0].equals(SHOW_RANDOMLY)) { String randomlyBlock = substring(matcher.group(), "}", "{/"); replacement = (int) (Math.random() * 2.0) == 1 ? apply(randomlyBlock) : ""; } else if (pieces[0].equals(DRAW)) { replacement = pieces[1 + (int) (Math.random() * pieces.length - 1)]; } else if (pieces[0].equals(REPEAT)) { int repeatTimes = 1; try { if (pieces.length == 4) { int startNumber = repeatTimes = Integer.parseInt(pieces[2]); repeatTimes = ((int) (Math.random() * (Integer.parseInt(pieces[3]) - startNumber + 1)) + startNumber); } else { repeatTimes = Integer.parseInt(pieces[2]); } } catch (Exception exception) { _logger.log(Level.SEVERE, "An error occurred while getting \"{" + matchedString + "}\".", exception); } String repeatBlock = substring(matcher.group(), "}", "{/"); replacement = ""; putValueObject(pieces[1], ""); putValueObject(pieces[1] + "-length", repeatTimes); for (int index = 0; index < repeatTimes; index++) { putValueObject(pieces[1] + "-offset", index + 1); putValueObject(pieces[1] + "-first", (index == 0)); putValueObject(pieces[1] + "-last", (index == repeatTimes - 1)); putValueObject(pieces[1] + "-value", index + 1); replacement += apply(repeatBlock); } removeValueObject(pieces[1] + "-length"); removeValueObject(pieces[1] + "-offset"); removeValueObject(pieces[1] + "-first"); removeValueObject(pieces[1] + "-last"); removeValueObject(pieces[1] + "-value"); removeValueObject(pieces[1]); } else if (pieces[0].equals(PROPERTY)) { replacement = System.getProperty(pieces[1], ""); } else if (pieces[0].equals(FORMAT)) { try { Locale locale = _locale; if (pieces.length == 3) locale = new Locale(pieces[2]); else if (pieces.length == 4) locale = new Locale(pieces[2], pieces[3]); SpanFormatter spanFormatter = _spanFormatters.get(pieces[1]); if (spanFormatter != null) { String spanTemplate = substring(matcher.group(), "}", "{/"); replacement = spanFormatter.format(apply(spanTemplate), locale); } else { _logger.log(Level.SEVERE, "Unable to find array \"" + pieces[1] + "\"."); } } catch (NumberFormatException numberFormatException) { _logger.log(Level.SEVERE, "Invalid Number", numberFormatException); } catch (Exception exception) { _logger.log(Level.SEVERE, "Exception", exception); } } else if (pieces[0].equals(SET)) { if (!pieces[1].equalsIgnoreCase(VO_NAME_CLASS_VERSION) && !pieces[1].equalsIgnoreCase(VO_NAME_CLASS_BUILD) && // !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_COUNTRY_NAME) && // !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_CODE) && !pieces[1].equalsIgnoreCase(VO_NAME_LANGUAGE_NAME)) { putValueObject(pieces[1], apply(substring(matcher.group(), "}", "{/"))); } else if (pieces[1].equalsIgnoreCase(VO_NAME_LOCALE_CODE)) { String localeString = substring(matcher.group(), "}", "{/").trim(); if (localeString.length() == 0) setLocale(Locale.getDefault()); else if (localeString.length() == 2) setLocale(new Locale(localeString)); else if (localeString.length() == 5 && localeString.charAt(2) == '_') setLocale(new Locale(localeString.substring(0, 2), localeString.substring(3))); } } matcher.appendReplacement(stringBuffer, replacement == null ? "" : replacement); replacement = null; } matcher.appendTail(stringBuffer); matcher = null; String output = stringBuffer.toString(); if (_pattern.matcher(output).find()) output = apply(output); return (output); }
diff --git a/src/frontend/edu/brown/hstore/util/PrefetchQueryPlanner.java b/src/frontend/edu/brown/hstore/util/PrefetchQueryPlanner.java index c1416b1df..83428c519 100644 --- a/src/frontend/edu/brown/hstore/util/PrefetchQueryPlanner.java +++ b/src/frontend/edu/brown/hstore/util/PrefetchQueryPlanner.java @@ -1,274 +1,274 @@ package edu.brown.hstore.util; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.voltdb.CatalogContext; import org.voltdb.ParameterSet; import org.voltdb.SQLStmt; import org.voltdb.VoltProcedure; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.messaging.FastSerializer; import com.google.protobuf.ByteString; import edu.brown.catalog.CatalogUtil; import edu.brown.hstore.BatchPlanner; import edu.brown.hstore.BatchPlanner.BatchPlan; import edu.brown.hstore.Hstoreservice.TransactionInitRequest; import edu.brown.hstore.Hstoreservice.WorkFragment; import edu.brown.hstore.estimators.EstimatorState.CountedStatement; import edu.brown.hstore.txns.LocalTransaction; import edu.brown.interfaces.Loggable; import edu.brown.logging.LoggerUtil; import edu.brown.logging.LoggerUtil.LoggerBoolean; import edu.brown.mappings.ParameterMapping; import edu.brown.utils.CollectionUtil; import edu.brown.utils.PartitionEstimator; import edu.brown.utils.StringUtil; /** * @author pavlo * @author cjl6 */ public class PrefetchQueryPlanner implements Loggable { private static final Logger LOG = Logger.getLogger(PrefetchQueryPlanner.class); private static final LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled()); private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled()); static { LoggerUtil.attachObserver(LOG, debug, trace); } // private final Database catalog_db; private final Map<Integer, BatchPlanner> planners = new HashMap<Integer, BatchPlanner>(); private final int[] partitionSiteXref; private final CatalogContext catalogContext; private final BitSet touched_sites; private final FastSerializer fs = new FastSerializer(); // TODO: Use pooled memory /** * Constructor * @param catalogContext * @param p_estimator */ public PrefetchQueryPlanner(CatalogContext catalogContext, PartitionEstimator p_estimator) { this.catalogContext = catalogContext; this.touched_sites = new BitSet(this.catalogContext.numberOfSites); // Initialize a BatchPlanner for each Procedure if it has the // prefetch flag set to true. We generate an array of the SQLStmt // handles that we will want to prefetch for each Procedure List<SQLStmt> prefetchStmts = new ArrayList<SQLStmt>(); for (Procedure catalog_proc : this.catalogContext.procedures.values()) { if (catalog_proc.getPrefetchable() == false) continue; prefetchStmts.clear(); for (Statement catalog_stmt : catalog_proc.getStatements().values()) { if (catalog_stmt.getPrefetchable() == false) continue; // Make sure that all of this Statement's input parameters // are mapped to one of the Procedure's ProcParameter boolean valid = true; for (StmtParameter catalog_param : catalog_stmt.getParameters().values()) { if (catalog_param.getProcparameter() == null) { LOG.warn(String.format("Unable to mark %s as prefetchable because %s is not mapped to a ProcParameter", catalog_stmt.fullName(), catalog_param.fullName())); valid = false; } } // FOR if (valid) prefetchStmts.add(new SQLStmt(catalog_stmt)); } // FOR if (prefetchStmts.isEmpty() == false) { // Are the prefetchStmts always going to be sorted the same way? (Does it matter for the hash code?) SQLStmt[] batchStmts = prefetchStmts.toArray(new SQLStmt[0]); BatchPlanner planner = new BatchPlanner(batchStmts, prefetchStmts.size(), catalog_proc, p_estimator); planner.setPrefetchFlag(true); this.planners.put(VoltProcedure.getBatchHashCode(batchStmts, batchStmts.length), planner); if (debug.get()) LOG.debug(String.format("%s Prefetch Statements: %s", catalog_proc.getName(), prefetchStmts)); } else { LOG.warn("There are no prefetchable Statements available for " + catalog_proc); catalog_proc.setPrefetchable(false); } } // FOR (procedure) this.partitionSiteXref = CatalogUtil.getPartitionSiteXrefArray(catalogContext.database); if (debug.get()) LOG.debug(String.format("Initialized QueryPrefetchPlanner for %d " + "Procedures with prefetchable Statements", this.planners.size())); if (this.catalogContext.paramMappings == null) { LOG.warn("Unable to generate prefetachable query plans without a ParameterMappingSet"); } } /** * @param ts * @return */ public TransactionInitRequest[] generateWorkFragments(LocalTransaction ts) { // We can't do this without a ParameterMappingSet if (this.catalogContext.paramMappings == null) { return (null); } // FIXME(cjl6) ts.getEstimatorState().getPrefetchableStatements(); if (debug.get()) LOG.debug(ts + " - Generating prefetch WorkFragments"); // ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( // Statement catalog_stmt, int catalog_stmt_index, StmtParameter catalog_stmt_param)); // pm.procedure_parameter.getIsarray(); // pm.procedure_parameter_index; Procedure catalog_proc = ts.getProcedure(); assert (ts.getProcedureParameters() != null) : "Unexpected null ParameterSet for " + ts; Object proc_params[] = ts.getProcedureParameters().toArray(); CountedStatement[] countedStmts = ts.getEstimatorState().getPrefetchableStatements().toArray(new CountedStatement[0]); SQLStmt[] prefetchStmts = new SQLStmt[countedStmts.length]; for (int i = 0; i < prefetchStmts.length; ++i) { prefetchStmts[i] = new SQLStmt(countedStmts[i].statement); } // Use the StmtParameter mappings for the queries we // want to prefetch and extract the ProcParameters // to populate an array of ParameterSets to use as the batchArgs BatchPlanner planner = this.planners.get(VoltProcedure.getBatchHashCode(prefetchStmts, prefetchStmts.length)); assert (planner != null) : "Missing BatchPlanner for " + catalog_proc; ParameterSet prefetchParams[] = new ParameterSet[planner.getBatchSize()]; ByteString prefetchParamsSerialized[] = new ByteString[prefetchParams.length]; // Makes a list of ByteStrings containing the ParameterSets that we need // to send over to the remote sites so that they can execute our // prefetchable queries for (int i = 0; i < prefetchParams.length; i++) { Statement catalog_stmt = planner.getStatement(i); CountedStatement counted_stmt = countedStmts[i]; if (debug.get()) LOG.debug(String.format("%s - Building ParameterSet for prefetchable query %s", ts, catalog_stmt.fullName())); Object stmt_params[] = new Object[catalog_stmt.getParameters().size()]; // Generates a new object array using a mapping from the // ProcParameter to the StmtParameter. This relies on a // ParameterMapping already being installed in the catalog // TODO: Precompute this as arrays (it will be much faster) for (StmtParameter catalog_param : catalog_stmt.getParameters().values()) { ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( counted_stmt.statement, counted_stmt.counter, catalog_param)); if (pm.procedure_parameter.getIsarray()) { stmt_params[catalog_param.getIndex()] = proc_params[pm.procedure_parameter_index]; } else { - ProcParameter catalog_proc_param = catalog_param.getProcparameter(); + ProcParameter catalog_proc_param = pm.procedure_parameter; assert(catalog_proc_param != null) : "Missing mapping from " + catalog_param.fullName() + " to ProcParameter"; stmt_params[catalog_param.getIndex()] = proc_params[catalog_proc_param.getIndex()]; } } // FOR (StmtParameter) prefetchParams[i] = new ParameterSet(stmt_params); if (debug.get()) LOG.debug(String.format("%s - [%02d] Prefetch %s -> %s", ts, i, catalog_stmt.getName(), prefetchParams[i])); // Serialize this ParameterSet for the TransactionInitRequests try { if (i > 0) this.fs.clear(); prefetchParams[i].writeExternal(this.fs); prefetchParamsSerialized[i] = ByteString.copyFrom(this.fs.getBBContainer().b); } catch (Exception ex) { throw new RuntimeException("Failed to serialize ParameterSet " + i + " for " + ts, ex); } } // FOR (Statement) // Generate the WorkFragments that we will need to send in our // TransactionInitRequest BatchPlan plan = planner.plan(ts.getTransactionId(), ts.getClientHandle(), ts.getBasePartition(), ts.getPredictTouchedPartitions(), ts.isPredictSinglePartition(), ts.getTouchedPartitions(), prefetchParams); List<WorkFragment> fragments = new ArrayList<WorkFragment>(); plan.getWorkFragments(ts.getTransactionId(), fragments); // Loop through the fragments and check whether at least one of // them needs to be executed at the base (local) partition. If so, we need a // separate TransactionInitRequest per site. Group the WorkFragments by siteID. // If we have a prefetchable query for the base partition, it means that // we will try to execute it before we actually need it whenever the // PartitionExecutor is idle That means, we don't want to serialize all this // if it's only going to the base partition. TransactionInitRequest.Builder[] builders = new TransactionInitRequest.Builder[this.catalogContext.numberOfSites]; for (WorkFragment frag : fragments) { int site_id = this.partitionSiteXref[frag.getPartitionId()]; if (builders[site_id] == null) { builders[site_id] = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()); for (ByteString bs : prefetchParamsSerialized) { builders[site_id].addPrefetchParams(bs); } // FOR } builders[site_id].addPrefetchFragments(frag); } // FOR (WorkFragment) Collection<Integer> touched_partitions = ts.getPredictTouchedPartitions(); this.touched_sites.clear(); for (int partition : touched_partitions) { this.touched_sites.set(this.partitionSiteXref[partition]); } // FOR TransactionInitRequest[] init_requests = new TransactionInitRequest[this.catalogContext.numberOfSites]; TransactionInitRequest default_request = null; for (int site_id = 0; site_id < this.catalogContext.numberOfSites; ++site_id) { // If this site has no prefetched fragments ... if (builders[site_id] == null) { // but it has other non-prefetched WorkFragments, create a // default TransactionInitRequest. if (this.touched_sites.get(site_id)) { if (default_request == null) { default_request = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()).build(); } init_requests[site_id] = default_request; if (debug.get()) LOG.debug(ts + " - Sending default TransactionInitRequest to site " + site_id); } // and no other WorkFragments, set the TransactionInitRequest to // null. else { init_requests[site_id] = null; } } // Otherwise, just build it. else { init_requests[site_id] = builders[site_id].build(); if (debug.get()) LOG.debug(ts + " - Sending prefetch WorkFragments to site " + site_id); } } // FOR (Site) if (trace.get()) LOG.trace(ts + " - TransactionInitRequests\n" + StringUtil.join("\n", init_requests)); return (init_requests); } @Override public void updateLogging() { // TODO Auto-generated method stub } }
true
true
public TransactionInitRequest[] generateWorkFragments(LocalTransaction ts) { // We can't do this without a ParameterMappingSet if (this.catalogContext.paramMappings == null) { return (null); } // FIXME(cjl6) ts.getEstimatorState().getPrefetchableStatements(); if (debug.get()) LOG.debug(ts + " - Generating prefetch WorkFragments"); // ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( // Statement catalog_stmt, int catalog_stmt_index, StmtParameter catalog_stmt_param)); // pm.procedure_parameter.getIsarray(); // pm.procedure_parameter_index; Procedure catalog_proc = ts.getProcedure(); assert (ts.getProcedureParameters() != null) : "Unexpected null ParameterSet for " + ts; Object proc_params[] = ts.getProcedureParameters().toArray(); CountedStatement[] countedStmts = ts.getEstimatorState().getPrefetchableStatements().toArray(new CountedStatement[0]); SQLStmt[] prefetchStmts = new SQLStmt[countedStmts.length]; for (int i = 0; i < prefetchStmts.length; ++i) { prefetchStmts[i] = new SQLStmt(countedStmts[i].statement); } // Use the StmtParameter mappings for the queries we // want to prefetch and extract the ProcParameters // to populate an array of ParameterSets to use as the batchArgs BatchPlanner planner = this.planners.get(VoltProcedure.getBatchHashCode(prefetchStmts, prefetchStmts.length)); assert (planner != null) : "Missing BatchPlanner for " + catalog_proc; ParameterSet prefetchParams[] = new ParameterSet[planner.getBatchSize()]; ByteString prefetchParamsSerialized[] = new ByteString[prefetchParams.length]; // Makes a list of ByteStrings containing the ParameterSets that we need // to send over to the remote sites so that they can execute our // prefetchable queries for (int i = 0; i < prefetchParams.length; i++) { Statement catalog_stmt = planner.getStatement(i); CountedStatement counted_stmt = countedStmts[i]; if (debug.get()) LOG.debug(String.format("%s - Building ParameterSet for prefetchable query %s", ts, catalog_stmt.fullName())); Object stmt_params[] = new Object[catalog_stmt.getParameters().size()]; // Generates a new object array using a mapping from the // ProcParameter to the StmtParameter. This relies on a // ParameterMapping already being installed in the catalog // TODO: Precompute this as arrays (it will be much faster) for (StmtParameter catalog_param : catalog_stmt.getParameters().values()) { ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( counted_stmt.statement, counted_stmt.counter, catalog_param)); if (pm.procedure_parameter.getIsarray()) { stmt_params[catalog_param.getIndex()] = proc_params[pm.procedure_parameter_index]; } else { ProcParameter catalog_proc_param = catalog_param.getProcparameter(); assert(catalog_proc_param != null) : "Missing mapping from " + catalog_param.fullName() + " to ProcParameter"; stmt_params[catalog_param.getIndex()] = proc_params[catalog_proc_param.getIndex()]; } } // FOR (StmtParameter) prefetchParams[i] = new ParameterSet(stmt_params); if (debug.get()) LOG.debug(String.format("%s - [%02d] Prefetch %s -> %s", ts, i, catalog_stmt.getName(), prefetchParams[i])); // Serialize this ParameterSet for the TransactionInitRequests try { if (i > 0) this.fs.clear(); prefetchParams[i].writeExternal(this.fs); prefetchParamsSerialized[i] = ByteString.copyFrom(this.fs.getBBContainer().b); } catch (Exception ex) { throw new RuntimeException("Failed to serialize ParameterSet " + i + " for " + ts, ex); } } // FOR (Statement) // Generate the WorkFragments that we will need to send in our // TransactionInitRequest BatchPlan plan = planner.plan(ts.getTransactionId(), ts.getClientHandle(), ts.getBasePartition(), ts.getPredictTouchedPartitions(), ts.isPredictSinglePartition(), ts.getTouchedPartitions(), prefetchParams); List<WorkFragment> fragments = new ArrayList<WorkFragment>(); plan.getWorkFragments(ts.getTransactionId(), fragments); // Loop through the fragments and check whether at least one of // them needs to be executed at the base (local) partition. If so, we need a // separate TransactionInitRequest per site. Group the WorkFragments by siteID. // If we have a prefetchable query for the base partition, it means that // we will try to execute it before we actually need it whenever the // PartitionExecutor is idle That means, we don't want to serialize all this // if it's only going to the base partition. TransactionInitRequest.Builder[] builders = new TransactionInitRequest.Builder[this.catalogContext.numberOfSites]; for (WorkFragment frag : fragments) { int site_id = this.partitionSiteXref[frag.getPartitionId()]; if (builders[site_id] == null) { builders[site_id] = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()); for (ByteString bs : prefetchParamsSerialized) { builders[site_id].addPrefetchParams(bs); } // FOR } builders[site_id].addPrefetchFragments(frag); } // FOR (WorkFragment) Collection<Integer> touched_partitions = ts.getPredictTouchedPartitions(); this.touched_sites.clear(); for (int partition : touched_partitions) { this.touched_sites.set(this.partitionSiteXref[partition]); } // FOR TransactionInitRequest[] init_requests = new TransactionInitRequest[this.catalogContext.numberOfSites]; TransactionInitRequest default_request = null; for (int site_id = 0; site_id < this.catalogContext.numberOfSites; ++site_id) { // If this site has no prefetched fragments ... if (builders[site_id] == null) { // but it has other non-prefetched WorkFragments, create a // default TransactionInitRequest. if (this.touched_sites.get(site_id)) { if (default_request == null) { default_request = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()).build(); } init_requests[site_id] = default_request; if (debug.get()) LOG.debug(ts + " - Sending default TransactionInitRequest to site " + site_id); } // and no other WorkFragments, set the TransactionInitRequest to // null. else { init_requests[site_id] = null; } } // Otherwise, just build it. else { init_requests[site_id] = builders[site_id].build(); if (debug.get()) LOG.debug(ts + " - Sending prefetch WorkFragments to site " + site_id); } } // FOR (Site) if (trace.get()) LOG.trace(ts + " - TransactionInitRequests\n" + StringUtil.join("\n", init_requests)); return (init_requests); }
public TransactionInitRequest[] generateWorkFragments(LocalTransaction ts) { // We can't do this without a ParameterMappingSet if (this.catalogContext.paramMappings == null) { return (null); } // FIXME(cjl6) ts.getEstimatorState().getPrefetchableStatements(); if (debug.get()) LOG.debug(ts + " - Generating prefetch WorkFragments"); // ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( // Statement catalog_stmt, int catalog_stmt_index, StmtParameter catalog_stmt_param)); // pm.procedure_parameter.getIsarray(); // pm.procedure_parameter_index; Procedure catalog_proc = ts.getProcedure(); assert (ts.getProcedureParameters() != null) : "Unexpected null ParameterSet for " + ts; Object proc_params[] = ts.getProcedureParameters().toArray(); CountedStatement[] countedStmts = ts.getEstimatorState().getPrefetchableStatements().toArray(new CountedStatement[0]); SQLStmt[] prefetchStmts = new SQLStmt[countedStmts.length]; for (int i = 0; i < prefetchStmts.length; ++i) { prefetchStmts[i] = new SQLStmt(countedStmts[i].statement); } // Use the StmtParameter mappings for the queries we // want to prefetch and extract the ProcParameters // to populate an array of ParameterSets to use as the batchArgs BatchPlanner planner = this.planners.get(VoltProcedure.getBatchHashCode(prefetchStmts, prefetchStmts.length)); assert (planner != null) : "Missing BatchPlanner for " + catalog_proc; ParameterSet prefetchParams[] = new ParameterSet[planner.getBatchSize()]; ByteString prefetchParamsSerialized[] = new ByteString[prefetchParams.length]; // Makes a list of ByteStrings containing the ParameterSets that we need // to send over to the remote sites so that they can execute our // prefetchable queries for (int i = 0; i < prefetchParams.length; i++) { Statement catalog_stmt = planner.getStatement(i); CountedStatement counted_stmt = countedStmts[i]; if (debug.get()) LOG.debug(String.format("%s - Building ParameterSet for prefetchable query %s", ts, catalog_stmt.fullName())); Object stmt_params[] = new Object[catalog_stmt.getParameters().size()]; // Generates a new object array using a mapping from the // ProcParameter to the StmtParameter. This relies on a // ParameterMapping already being installed in the catalog // TODO: Precompute this as arrays (it will be much faster) for (StmtParameter catalog_param : catalog_stmt.getParameters().values()) { ParameterMapping pm = CollectionUtil.first(this.catalogContext.paramMappings.get( counted_stmt.statement, counted_stmt.counter, catalog_param)); if (pm.procedure_parameter.getIsarray()) { stmt_params[catalog_param.getIndex()] = proc_params[pm.procedure_parameter_index]; } else { ProcParameter catalog_proc_param = pm.procedure_parameter; assert(catalog_proc_param != null) : "Missing mapping from " + catalog_param.fullName() + " to ProcParameter"; stmt_params[catalog_param.getIndex()] = proc_params[catalog_proc_param.getIndex()]; } } // FOR (StmtParameter) prefetchParams[i] = new ParameterSet(stmt_params); if (debug.get()) LOG.debug(String.format("%s - [%02d] Prefetch %s -> %s", ts, i, catalog_stmt.getName(), prefetchParams[i])); // Serialize this ParameterSet for the TransactionInitRequests try { if (i > 0) this.fs.clear(); prefetchParams[i].writeExternal(this.fs); prefetchParamsSerialized[i] = ByteString.copyFrom(this.fs.getBBContainer().b); } catch (Exception ex) { throw new RuntimeException("Failed to serialize ParameterSet " + i + " for " + ts, ex); } } // FOR (Statement) // Generate the WorkFragments that we will need to send in our // TransactionInitRequest BatchPlan plan = planner.plan(ts.getTransactionId(), ts.getClientHandle(), ts.getBasePartition(), ts.getPredictTouchedPartitions(), ts.isPredictSinglePartition(), ts.getTouchedPartitions(), prefetchParams); List<WorkFragment> fragments = new ArrayList<WorkFragment>(); plan.getWorkFragments(ts.getTransactionId(), fragments); // Loop through the fragments and check whether at least one of // them needs to be executed at the base (local) partition. If so, we need a // separate TransactionInitRequest per site. Group the WorkFragments by siteID. // If we have a prefetchable query for the base partition, it means that // we will try to execute it before we actually need it whenever the // PartitionExecutor is idle That means, we don't want to serialize all this // if it's only going to the base partition. TransactionInitRequest.Builder[] builders = new TransactionInitRequest.Builder[this.catalogContext.numberOfSites]; for (WorkFragment frag : fragments) { int site_id = this.partitionSiteXref[frag.getPartitionId()]; if (builders[site_id] == null) { builders[site_id] = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId().longValue()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()); for (ByteString bs : prefetchParamsSerialized) { builders[site_id].addPrefetchParams(bs); } // FOR } builders[site_id].addPrefetchFragments(frag); } // FOR (WorkFragment) Collection<Integer> touched_partitions = ts.getPredictTouchedPartitions(); this.touched_sites.clear(); for (int partition : touched_partitions) { this.touched_sites.set(this.partitionSiteXref[partition]); } // FOR TransactionInitRequest[] init_requests = new TransactionInitRequest[this.catalogContext.numberOfSites]; TransactionInitRequest default_request = null; for (int site_id = 0; site_id < this.catalogContext.numberOfSites; ++site_id) { // If this site has no prefetched fragments ... if (builders[site_id] == null) { // but it has other non-prefetched WorkFragments, create a // default TransactionInitRequest. if (this.touched_sites.get(site_id)) { if (default_request == null) { default_request = TransactionInitRequest.newBuilder() .setTransactionId(ts.getTransactionId()) .setProcedureId(ts.getProcedure().getId()) .setBasePartition(ts.getBasePartition()) .addAllPartitions(ts.getPredictTouchedPartitions()).build(); } init_requests[site_id] = default_request; if (debug.get()) LOG.debug(ts + " - Sending default TransactionInitRequest to site " + site_id); } // and no other WorkFragments, set the TransactionInitRequest to // null. else { init_requests[site_id] = null; } } // Otherwise, just build it. else { init_requests[site_id] = builders[site_id].build(); if (debug.get()) LOG.debug(ts + " - Sending prefetch WorkFragments to site " + site_id); } } // FOR (Site) if (trace.get()) LOG.trace(ts + " - TransactionInitRequests\n" + StringUtil.join("\n", init_requests)); return (init_requests); }
diff --git a/com/mraof/minestuck/network/MachinePacket.java b/com/mraof/minestuck/network/MachinePacket.java index c1010e50..0da0afba 100644 --- a/com/mraof/minestuck/network/MachinePacket.java +++ b/com/mraof/minestuck/network/MachinePacket.java @@ -1,63 +1,64 @@ package com.mraof.minestuck.network; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import com.mraof.minestuck.alchemy.CombinationMode; import com.mraof.minestuck.entity.item.EntityGrist; import com.mraof.minestuck.inventory.ContainerMachine; import com.mraof.minestuck.network.MinestuckPacket.Type; import com.mraof.minestuck.tileentity.TileEntityMachine; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.Container; import net.minecraft.inventory.ContainerBeacon; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.INetworkManager; import cpw.mods.fml.common.network.Player; public class MachinePacket extends MinestuckPacket { public boolean newMode; public int xCoord; public int yCoord; public int zCoord; public int gristTotal; public MachinePacket() { super(Type.MACHINE); } @Override public byte[] generatePacket(Object... data) { ByteArrayDataOutput dat = ByteStreams.newDataOutput(); dat.writeBoolean((Boolean) data[0]); return dat.toByteArray(); } @Override public MinestuckPacket consumePacket(byte[] data) { ByteArrayDataInput dat = ByteStreams.newDataInput(data); newMode = dat.readBoolean(); return this; } @Override public void execute(INetworkManager network, MinestuckPacketHandler handler, Player player, String userName) { TileEntityMachine te = ((ContainerMachine) ((EntityPlayerMP)player).openContainer).tileEntity; if (te == null) { System.out.println("[MINESTUCK] Invalid TE!"); } else { + System.out.println("[MINESTUCK] Button pressed. AND mode is " + newMode); te.mode = newMode ? CombinationMode.AND : CombinationMode.OR; } } }
true
true
public void execute(INetworkManager network, MinestuckPacketHandler handler, Player player, String userName) { TileEntityMachine te = ((ContainerMachine) ((EntityPlayerMP)player).openContainer).tileEntity; if (te == null) { System.out.println("[MINESTUCK] Invalid TE!"); } else { te.mode = newMode ? CombinationMode.AND : CombinationMode.OR; } }
public void execute(INetworkManager network, MinestuckPacketHandler handler, Player player, String userName) { TileEntityMachine te = ((ContainerMachine) ((EntityPlayerMP)player).openContainer).tileEntity; if (te == null) { System.out.println("[MINESTUCK] Invalid TE!"); } else { System.out.println("[MINESTUCK] Button pressed. AND mode is " + newMode); te.mode = newMode ? CombinationMode.AND : CombinationMode.OR; } }
diff --git a/src/main/java/dbs/project/main/gui/AppGui.java b/src/main/java/dbs/project/main/gui/AppGui.java index 32c2595..02040d7 100644 --- a/src/main/java/dbs/project/main/gui/AppGui.java +++ b/src/main/java/dbs/project/main/gui/AppGui.java @@ -1,159 +1,159 @@ package dbs.project.main.gui; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.CellRendererPane; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTree; import javax.swing.ListCellRenderer; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.tree.TreeModel; import dbs.project.dev.Generator; import dbs.project.entity.Tournament; import dbs.project.entity.TournamentGroup; import dbs.project.service.KnockoutStageService; import dbs.project.service.TournamentService; import dbs.project.service.group.StandingRow; public class AppGui extends JFrame { private static final long serialVersionUID = 1L; private final String APP_NAME = "Weltmeisterschaft DB"; private JPanel mainPanel; private JList tournamentsList; private JPanel groupStageComponents; private JTree knockoutTree; public AppGui() { this.setName(APP_NAME); this.setTitle(APP_NAME); this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); this.setSize(1024, 768); initComponents(); } public static void main(String[] args) { AppGui gui = new AppGui(); gui.setVisible(true); } private void initComponents() { mainPanel = new javax.swing.JPanel(); mainPanel.setName("mainPanel"); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); initLeftComponents(); initTab(); this.add(mainPanel); } private void initTab() { JTabbedPane tabbComponents = new JTabbedPane(); groupStageComponents = new JPanel(); groupStageComponents.setLayout(new BoxLayout(groupStageComponents, BoxLayout.Y_AXIS)); tabbComponents.add("Vorrunde", groupStageComponents); knockoutTree = new JTree(); tabbComponents.add("Finalrunde", knockoutTree); Tournament firstTournament = (Tournament) tournamentsList.getModel().getElementAt(0); refreshTabs(firstTournament); mainPanel.add(tabbComponents); } private void refreshTabs(Tournament tournament) { List<TournamentGroup> groups = tournament.getGroupPhase().getGroups(); groupStageComponents.removeAll(); for(TournamentGroup group : groups) { JTable tmpJTable = new JTable(); JScrollPane tmpJScrollPane = new JScrollPane(); tmpJTable.setModel(StandingRow.getModel(group)); tmpJScrollPane.setViewportView(tmpJTable); groupStageComponents.add(tmpJScrollPane); } TreeModel treeModel = KnockoutStageService.getAsTreeModel(tournament.getKnockoutPhase()); knockoutTree.setModel(treeModel); mainPanel.validate(); } private void initLeftComponents() { JPanel components = new JPanel(); BoxLayout bl = new BoxLayout(components, BoxLayout.Y_AXIS); components.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); components.setLayout(bl); components.setMaximumSize(new Dimension(15, Short.MAX_VALUE)); JLabel label = new JLabel("Verfügbare Turniere:"); label.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); components.add(label); JScrollPane tournamentsScrollPane = new JScrollPane(); tournamentsList = new JList(); tournamentsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tournamentsScrollPane.setViewportView(tournamentsList); refreshList(); ListSelectionListener listListener = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { - int i = e.getLastIndex(); + int i = ((JList) e.getSource()).getSelectedIndex(); Tournament selectedTournament = (Tournament) tournamentsList.getModel().getElementAt(i); refreshTabs(selectedTournament); } }; tournamentsList.addListSelectionListener(listListener); JButton refreshTournament = new JButton(); refreshTournament.setText("Turnier generieren"); // NOI18N refreshTournament.setName("tournamentCreateButton"); // NOI18N ActionListener buttonPressed = new ActionListener() { public void actionPerformed(ActionEvent ev) { try { Generator.generateTournament(); } catch(Exception e) {} refreshList(); } }; refreshTournament.addActionListener(buttonPressed); //Liste hinzufügen components.add(tournamentsScrollPane); //Button hinzufügen components.add(refreshTournament); mainPanel.add(components); } private void refreshList() { tournamentsList.setModel(TournamentService.getListModel()); } }
true
true
private void initLeftComponents() { JPanel components = new JPanel(); BoxLayout bl = new BoxLayout(components, BoxLayout.Y_AXIS); components.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); components.setLayout(bl); components.setMaximumSize(new Dimension(15, Short.MAX_VALUE)); JLabel label = new JLabel("Verfügbare Turniere:"); label.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); components.add(label); JScrollPane tournamentsScrollPane = new JScrollPane(); tournamentsList = new JList(); tournamentsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tournamentsScrollPane.setViewportView(tournamentsList); refreshList(); ListSelectionListener listListener = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int i = e.getLastIndex(); Tournament selectedTournament = (Tournament) tournamentsList.getModel().getElementAt(i); refreshTabs(selectedTournament); } }; tournamentsList.addListSelectionListener(listListener); JButton refreshTournament = new JButton(); refreshTournament.setText("Turnier generieren"); // NOI18N refreshTournament.setName("tournamentCreateButton"); // NOI18N ActionListener buttonPressed = new ActionListener() { public void actionPerformed(ActionEvent ev) { try { Generator.generateTournament(); } catch(Exception e) {} refreshList(); } }; refreshTournament.addActionListener(buttonPressed); //Liste hinzufügen components.add(tournamentsScrollPane); //Button hinzufügen components.add(refreshTournament); mainPanel.add(components); }
private void initLeftComponents() { JPanel components = new JPanel(); BoxLayout bl = new BoxLayout(components, BoxLayout.Y_AXIS); components.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); components.setLayout(bl); components.setMaximumSize(new Dimension(15, Short.MAX_VALUE)); JLabel label = new JLabel("Verfügbare Turniere:"); label.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0)); components.add(label); JScrollPane tournamentsScrollPane = new JScrollPane(); tournamentsList = new JList(); tournamentsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tournamentsScrollPane.setViewportView(tournamentsList); refreshList(); ListSelectionListener listListener = new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int i = ((JList) e.getSource()).getSelectedIndex(); Tournament selectedTournament = (Tournament) tournamentsList.getModel().getElementAt(i); refreshTabs(selectedTournament); } }; tournamentsList.addListSelectionListener(listListener); JButton refreshTournament = new JButton(); refreshTournament.setText("Turnier generieren"); // NOI18N refreshTournament.setName("tournamentCreateButton"); // NOI18N ActionListener buttonPressed = new ActionListener() { public void actionPerformed(ActionEvent ev) { try { Generator.generateTournament(); } catch(Exception e) {} refreshList(); } }; refreshTournament.addActionListener(buttonPressed); //Liste hinzufügen components.add(tournamentsScrollPane); //Button hinzufügen components.add(refreshTournament); mainPanel.add(components); }
diff --git a/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java b/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java index 7938ce86..fd66235e 100644 --- a/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java +++ b/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java @@ -1,467 +1,466 @@ /******************************************************************************* * Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence. All rights reserved. * This program and the accompanying materials are made available under the terms of the new BSD license which * accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html Contributors: * Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence - initial API and implementation ******************************************************************************/ package org.vivoweb.harvester.update; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.xml.parsers.ParserConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vivoweb.harvester.util.InitLog; import org.vivoweb.harvester.util.IterableAdaptor; import org.vivoweb.harvester.util.args.ArgDef; import org.vivoweb.harvester.util.args.ArgList; import org.vivoweb.harvester.util.args.ArgParser; import org.vivoweb.harvester.util.repo.JenaConnect; import org.xml.sax.SAXException; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.Syntax; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.sparql.util.StringUtils; import com.hp.hpl.jena.util.ResourceUtils; /** * Changes the namespace for all matching uris * @author Christopher Haines ([email protected]) */ public class ChangeNamespace { /** * SLF4J Logger */ private static Logger log = LoggerFactory.getLogger(ChangeNamespace.class); /** * The model to change uris in */ private JenaConnect model; /** * The old namespace */ private String oldNamespace; /** * The new namespace */ private String newNamespace; /** * the propeties to match on */ private List<Property> properties; /** * The search model */ private JenaConnect vivo; /** * Constructor * @param argList parsed argument list * @throws IOException error reading config * @throws SAXException error parsing config * @throws ParserConfigurationException error parsing config */ public ChangeNamespace(ArgList argList) throws ParserConfigurationException, SAXException, IOException { this.model = JenaConnect.parseConfig(argList.get("i"), argList.getProperties("I")); this.vivo = JenaConnect.parseConfig(argList.get("v"), argList.getProperties("V")); this.oldNamespace = argList.get("o"); this.newNamespace = argList.get("n"); List<String> predicates = argList.getAll("p"); this.properties = new ArrayList<Property>(predicates.size()); for (String pred : predicates) { this.properties.add(ResourceFactory.createProperty(pred)); } } /** * Get either a matching uri from the given model or an unused uri * @param current the current resource * @param namespace the namespace to match in * @param properties the propeties to match on * @param uriCheck list of new uris generated during this changenamespace run * @param errorOnNewURI Log ERROR messages when a new URI is generated * @param vivo the model to match in * @param model model to check for duplicates * @return the uri of the first matched resource or an unused uri if none found */ public static String getURI(Resource current, String namespace, List<Property> properties, ArrayList<String> uriCheck, boolean errorOnNewURI, JenaConnect vivo, JenaConnect model) { String uri = null; if (properties != null && !properties.isEmpty()) { uri = getMatchingURI(current, namespace, properties, vivo); } if (uri == null) { uri = getUnusedURI(namespace, uriCheck, vivo, model); if (errorOnNewURI) { log.error("Generated New Unused URI <"+uri+"> for rdf node <"+current.getURI()+">"); } } log.debug("Using URI: <"+uri+">"); return uri; } /** * Gets an unused URI in the the given namespace for the given models * @param namespace the namespace * @param uriCheck list of new uris generated during this changenamespace run * @param models models to check in * @return the uri * @throws IllegalArgumentException empty namespace */ public static String getUnusedURI(String namespace, ArrayList<String> uriCheck, JenaConnect... models) throws IllegalArgumentException { if (namespace == null || namespace.equals("")) { throw new IllegalArgumentException("namespace cannot be empty"); } String uri = null; Random random = new Random(); while (uri == null) { uri = namespace + "n" + random.nextInt(Integer.MAX_VALUE); log.trace("uriCheck: "+uriCheck.contains(uri)); if (uriCheck.contains(uri)) { uri = null; } for (JenaConnect model : models) { if (model.containsURI(uri)) { uri = null; } } } uriCheck.add(uri); log.debug("Using new URI: <"+uri+">"); return uri; } /** * Matches the current resource to a resource in the given namespace in the given model based on the given properties * @param current the current resource * @param namespace the namespace to match in * @param properties the propeties to match on * @param vivo the model to match in * @return the uri of the first matched resource or null if none found */ public static String getMatchingURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo) { List<String> uris = getMatchingURIs(current, namespace, properties, vivo); String uri = uris.isEmpty()?null:uris.get(0); if (uri != null) { log.debug("Matched URI: <"+uri+">"); } else { log.debug("No Matched URI"); } return uri; } /** * Matches the current resource to resources in the given namespace in the given model based on the given properties * @param current the current resource * @param namespace the namespace to match in * @param properties the propeties to match on * @param vivo the model to match in * @return the uris of the matched resources (empty set if none found) */ public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) { StringBuilder sbQuery = new StringBuilder(); ArrayList<String> filters = new ArrayList<String>(); int valueCount = 0; sbQuery.append("SELECT ?uri\nWHERE\n{"); log.debug("properties size: "+properties.size()); if (properties.size() < 1) { throw new IllegalArgumentException("No properties! SELECT cannot be created!"); } for (Property p : properties) { StmtIterator stmntit = current.listProperties(p); if (!stmntit.hasNext()) { throw new IllegalArgumentException("Resource <"+current.getURI()+"> does not have property <"+p.getURI()+">! SELECT cannot be created!"); } for (Statement s : IterableAdaptor.adapt(stmntit)) { sbQuery.append("\t?uri <"); sbQuery.append(p.getURI()); sbQuery.append("> "); if (s.getObject().isResource()) { sbQuery.append("<"); sbQuery.append(s.getResource().getURI()); sbQuery.append(">"); } else { filters.add("( str(?value"+valueCount+") = \""+s.getLiteral().getValue().toString()+"\" )"); sbQuery.append("?value"); sbQuery.append(valueCount); valueCount++; } sbQuery.append(" .\n"); } } // sbQuery.append("regex( ?uri , \""); // sbQuery.append(namespace); // sbQuery.append("\" )"); if (!filters.isEmpty()) { sbQuery.append("\tFILTER ("); // sbQuery.append(" && "); sbQuery.append(StringUtils.join(" && ", filters)); sbQuery.append(")\n"); } sbQuery.append("}"); ArrayList<String> retVal = new ArrayList<String>(); int count = 0; log.debug("Query:\n"+sbQuery.toString()); log.debug("namespace: "+namespace); for (QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) { Resource res = qs.getResource("uri"); if (res == null) { throw new IllegalArgumentException("res is null! SELECT for resource <"+current.getURI()+"> is most likely corrupted!"); } String resns = res.getNameSpace(); if (resns.equals(namespace)) { String uri = res.getURI(); retVal.add(uri); log.debug("Matched URI["+count+"]: <"+uri+">"); count++; } } return retVal; } /** * Changes the namespace for all matching uris * @param model the model to change namespaces for * @param vivo the model to search for uris in * @param oldNamespace the old namespace * @param newNamespace the new namespace * @param properties the properties to match on * @throws IllegalArgumentException empty namespace */ public static void changeNS(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties) throws IllegalArgumentException { if (oldNamespace == null || oldNamespace.equals("")) { throw new IllegalArgumentException("old namespace cannot be empty"); } if (newNamespace == null || newNamespace.equals("")) { throw new IllegalArgumentException("new namespace cannot be empty"); } if (oldNamespace.equals(newNamespace)) { return; } ArrayList<String> uriCheck = new ArrayList<String>(); int count = 0; String uri; Resource res; QuerySolution solution; if (properties.size() < 1) { throw new IllegalArgumentException("No properties! SELECT cannot be created!"); } batchMatch(model, vivo, oldNamespace, newNamespace, properties, count); batchRename(model, vivo, oldNamespace, newNamespace, uriCheck, count); } /** * @param model * @param vivo * @param oldNamespace * @param newNamespace * @param uriCheck * @param count */ private static void batchRename(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, ArrayList<String> uriCheck, int count) { String uri; Resource res; QuerySolution solution; //Grab all namespaces needing changed log.trace("Begin Change Query Build"); String subjectQuery = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " + "PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " + "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " + "PREFIX bibo: <http://purl.org/ontology/bibo/> " + "PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " + "PREFIX dcterms: <http://purl.org/dc/terms/> " + "PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " + "PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " + "PREFIX core: <http://vivoweb.org/ontology/core#> " + "SELECT ?sNew " + "WHERE " + "{ " + "?sNew ?p ?o . " + "FILTER regex(str(?sNew), \"" + oldNamespace + "\" ) " + "}"; log.debug(subjectQuery); log.trace("End Change Query Build"); log.trace("Begin Execute Query"); ResultSet changeList = model.executeQuery(subjectQuery); ArrayList<String> changeArray = new ArrayList<String>(); log.trace("End Execute Query"); log.trace("Begin Rename Changes"); while (changeList.hasNext()) { solution = changeList.next(); changeArray.add(solution.getResource("sNew").toString()); count++; } for(int i = 0; i < count; i++) { res = model.getJenaModel().getResource(changeArray.get(i)); uri = getUnusedURI(newNamespace, uriCheck, vivo, model); ResourceUtils.renameResource(res, uri); } log.info("Changed namespace for "+count+" rdf nodes"); log.trace("End Rename Changes"); } /** * @param model * @param vivo * @param oldNamespace * @param newNamespace * @param properties * @param count * @return */ private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) { Resource res; QuerySolution solution; log.trace("Begin Match Query Build"); //Find all namespace matches StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " + "PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " + "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " + "PREFIX bibo: <http://purl.org/ontology/bibo/> " + "PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " + "PREFIX dcterms: <http://purl.org/dc/terms/> " + "PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " + "PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " + "PREFIX core: <http://vivoweb.org/ontology/core#> " + "SELECT ?sNew ?sOld " + "WHERE " + "{ "); int counter = 0; for (Property p : properties) { sQuery.append("\t?sNew <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("?o" + counter ); sQuery.append(" .\n"); sQuery.append("\t?sOld <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("\t?o" + counter ); sQuery.append(" .\n"); } sQuery.append("FILTER regex(str(?sNew), \""); sQuery.append(oldNamespace + "\" ) ."); sQuery.append("FILTER regex(str(?sOld), \""); sQuery.append(newNamespace + "\" ) }"); log.debug(sQuery.toString()); log.trace("End Match Query Build"); log.trace("Begin Union Model"); Model unionModel = model.getJenaModel().union(vivo.getJenaModel()); log.trace("End Union Model"); log.trace("Begin Run Query to ResultSet"); Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ); QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel); ResultSet matchList = queryExec.execSelect(); log.trace("End Run Query to ResultSet"); log.trace("Begin Rename Matches"); ArrayList<String[]> uriArray = new ArrayList<String[]>(); String matchArray[]; while (matchList.hasNext()) { solution = matchList.next(); matchArray = new String[2]; matchArray[0] = solution.getResource("sNew").toString(); matchArray[1] = solution.getResource("sOld").toString(); uriArray.add(matchArray); count++; } for(int i = 0; i < count; i++) { matchArray = uriArray.get(i); res = model.getJenaModel().getResource(matchArray[0]); ResourceUtils.renameResource(res, matchArray[1]); } log.info("Matched namespace for "+count+" rdf nodes"); log.trace("Begin Rename Matches"); count = 0; - return count; } /** * Change namespace */ private void execute() { changeNS(this.model, this.vivo, this.oldNamespace, this.newNamespace, this.properties); } /** * Get the ArgParser for this task * @return the ArgParser */ private static ArgParser getParser() { ArgParser parser = new ArgParser("ChangeNamespace"); // Inputs parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("inputModel").withParameter(true, "CONFIG_FILE").setDescription("config file for input jena model").setRequired(true)); parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("inputModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of input jena model config using VALUE").setRequired(false)); parser.addArgument(new ArgDef().setShortOption('v').setLongOpt("vivoModel").withParameter(true, "CONFIG_FILE").setDescription("config file for vivo jena model").setRequired(true)); parser.addArgument(new ArgDef().setShortOption('V').setLongOpt("vivoModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of vivo jena model config using VALUE").setRequired(false)); // Params parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("oldNamespace").withParameter(true, "OLD_NAMESPACE").setDescription("The old namespace").setRequired(true)); parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("newNamespace").withParameter(true, "NEW_NAMESPACE").setDescription("The new namespace").setRequired(true)); parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("predicate").withParameters(true, "MATCH_PREDICATE").setDescription("Predicate to match on").setRequired(true)); return parser; } /** * Main method * @param args commandline arguments */ public static void main(String... args) { InitLog.initLogger(ChangeNamespace.class); log.info(getParser().getAppName()+": Start"); try { new ChangeNamespace(new ArgList(getParser(), args)).execute(); } catch (IllegalArgumentException e) { log.error(e.getMessage()); System.out.println(getParser().getUsage()); } catch (IOException e) { log.error(e.getMessage(), e); } catch (Exception e) { log.error(e.getMessage(), e); } log.info(getParser().getAppName()+": End"); } }
true
true
private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) { Resource res; QuerySolution solution; log.trace("Begin Match Query Build"); //Find all namespace matches StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " + "PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " + "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " + "PREFIX bibo: <http://purl.org/ontology/bibo/> " + "PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " + "PREFIX dcterms: <http://purl.org/dc/terms/> " + "PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " + "PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " + "PREFIX core: <http://vivoweb.org/ontology/core#> " + "SELECT ?sNew ?sOld " + "WHERE " + "{ "); int counter = 0; for (Property p : properties) { sQuery.append("\t?sNew <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("?o" + counter ); sQuery.append(" .\n"); sQuery.append("\t?sOld <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("\t?o" + counter ); sQuery.append(" .\n"); } sQuery.append("FILTER regex(str(?sNew), \""); sQuery.append(oldNamespace + "\" ) ."); sQuery.append("FILTER regex(str(?sOld), \""); sQuery.append(newNamespace + "\" ) }"); log.debug(sQuery.toString()); log.trace("End Match Query Build"); log.trace("Begin Union Model"); Model unionModel = model.getJenaModel().union(vivo.getJenaModel()); log.trace("End Union Model"); log.trace("Begin Run Query to ResultSet"); Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ); QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel); ResultSet matchList = queryExec.execSelect(); log.trace("End Run Query to ResultSet"); log.trace("Begin Rename Matches"); ArrayList<String[]> uriArray = new ArrayList<String[]>(); String matchArray[]; while (matchList.hasNext()) { solution = matchList.next(); matchArray = new String[2]; matchArray[0] = solution.getResource("sNew").toString(); matchArray[1] = solution.getResource("sOld").toString(); uriArray.add(matchArray); count++; } for(int i = 0; i < count; i++) { matchArray = uriArray.get(i); res = model.getJenaModel().getResource(matchArray[0]); ResourceUtils.renameResource(res, matchArray[1]); } log.info("Matched namespace for "+count+" rdf nodes"); log.trace("Begin Rename Matches"); count = 0; return count; }
private static void batchMatch(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties, int count) { Resource res; QuerySolution solution; log.trace("Begin Match Query Build"); //Find all namespace matches StringBuilder sQuery = new StringBuilder("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> " + "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> " + "PREFIX owl: <http://www.w3.org/2002/07/owl#> " + "PREFIX swrl: <http://www.w3.org/2003/11/swrl#> " + "PREFIX swrlb: <http://www.w3.org/2003/11/swrlb#> " + "PREFIX vitro: <http://vitro.mannlib.cornell.edu/ns/vitro/0.7#> " + "PREFIX bibo: <http://purl.org/ontology/bibo/> " + "PREFIX dcelem: <http://purl.org/dc/elements/1.1/> " + "PREFIX dcterms: <http://purl.org/dc/terms/> " + "PREFIX event: <http://purl.org/NET/c4dm/event.owl#> " + "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " + "PREFIX geo: <http://aims.fao.org/aos/geopolitical.owl#> " + "PREFIX skos: <http://www.w3.org/2004/02/skos/core#> " + "PREFIX ufVivo: <http://vivo.ufl.edu/ontology/vivo-ufl/> " + "PREFIX core: <http://vivoweb.org/ontology/core#> " + "SELECT ?sNew ?sOld " + "WHERE " + "{ "); int counter = 0; for (Property p : properties) { sQuery.append("\t?sNew <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("?o" + counter ); sQuery.append(" .\n"); sQuery.append("\t?sOld <"); sQuery.append(p.getURI()); sQuery.append("> "); sQuery.append("\t?o" + counter ); sQuery.append(" .\n"); } sQuery.append("FILTER regex(str(?sNew), \""); sQuery.append(oldNamespace + "\" ) ."); sQuery.append("FILTER regex(str(?sOld), \""); sQuery.append(newNamespace + "\" ) }"); log.debug(sQuery.toString()); log.trace("End Match Query Build"); log.trace("Begin Union Model"); Model unionModel = model.getJenaModel().union(vivo.getJenaModel()); log.trace("End Union Model"); log.trace("Begin Run Query to ResultSet"); Query query = QueryFactory.create(sQuery.toString(), Syntax.syntaxARQ); QueryExecution queryExec = QueryExecutionFactory.create(query, unionModel); ResultSet matchList = queryExec.execSelect(); log.trace("End Run Query to ResultSet"); log.trace("Begin Rename Matches"); ArrayList<String[]> uriArray = new ArrayList<String[]>(); String matchArray[]; while (matchList.hasNext()) { solution = matchList.next(); matchArray = new String[2]; matchArray[0] = solution.getResource("sNew").toString(); matchArray[1] = solution.getResource("sOld").toString(); uriArray.add(matchArray); count++; } for(int i = 0; i < count; i++) { matchArray = uriArray.get(i); res = model.getJenaModel().getResource(matchArray[0]); ResourceUtils.renameResource(res, matchArray[1]); } log.info("Matched namespace for "+count+" rdf nodes"); log.trace("Begin Rename Matches"); count = 0; }
diff --git a/trunk/java/com/xerox/amazonws/fps/FlexiblePaymentsService.java b/trunk/java/com/xerox/amazonws/fps/FlexiblePaymentsService.java index 2c6fbbc..fa49eac 100644 --- a/trunk/java/com/xerox/amazonws/fps/FlexiblePaymentsService.java +++ b/trunk/java/com/xerox/amazonws/fps/FlexiblePaymentsService.java @@ -1,2420 +1,2420 @@ package com.xerox.amazonws.fps; import com.xerox.amazonws.common.AWSError; import com.xerox.amazonws.common.AWSException; import com.xerox.amazonws.common.AWSQueryConnection; import com.xerox.amazonws.sdb.DataUtils; import com.xerox.amazonws.typica.fps.jaxb.*; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.servlet.http.HttpServletRequest; import javax.xml.bind.JAXBException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.text.Collator; /** * This class provides an interface with the Amazon FPS service. * * @author J. Bernard * @author Elastic Grid, LLC. * @author [email protected] */ public class FlexiblePaymentsService extends AWSQueryConnection { private final String callerToken; private final String recipientToken; private final DescriptorPolicy descriptorPolicy; private final TemporaryDeclinePolicy tempDeclinePolicy; private final String uiPipeline; private static Log logger = LogFactory.getLog(FlexiblePaymentsService.class); /** * Initializes the FPS service with your AWS login information. * * @param awsAccessId the your user key into AWS * @param awsSecretKey the secret string used to generate signatures for authentication. */ public FlexiblePaymentsService(String awsAccessId, String awsSecretKey) { this(awsAccessId, awsSecretKey, true, null, null, null, null); } /** * Initializes the FPS service with your AWS login information. * * @param awsAccessId the your user key into AWS * @param awsSecretKey the secret string used to generate signatures for authentication. * @param callerToken the default caller token to be used when not explicitely specified * @param recipientToken the default recipient token to be used when not explicitely specified * @param descriptorPolicy the descriptor policy to use as descriptive string on credit card statements * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) */ public FlexiblePaymentsService(String awsAccessId, String awsSecretKey, String callerToken, String recipientToken, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) { this(awsAccessId, awsSecretKey, true, callerToken, recipientToken, descriptorPolicy, tempDeclinePolicy); } /** * Initializes the FPS service with your AWS login information. * * @param awsAccessId the your user key into AWS * @param awsSecretKey the secret string used to generate signatures for authentication. * @param isSecure true if the data should be encrypted on the wire on the way to or from FPS. * @param callerToken the default caller token to be used when not explicitely specified * @param recipientToken the default recipient token to be used when not explicitely specified * @param descriptorPolicy the descriptor policy to use as descriptive string on credit card statements * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) */ public FlexiblePaymentsService(String awsAccessId, String awsSecretKey, boolean isSecure, String callerToken, String recipientToken, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) { this(awsAccessId, awsSecretKey, isSecure, callerToken, recipientToken, descriptorPolicy, tempDeclinePolicy, "fps.amazonaws.com", "https://authorize.payments.amazon.com/cobranded-ui/actions/start"); } /** * Initializes the FPS service with your AWS login information. * * @param awsAccessId The your user key into AWS * @param awsSecretKey The secret string used to generate signatures for authentication. * @param isSecure True if the data should be encrypted on the wire on the way to or from FPS. * @param callerToken the default caller token to be used when not explicitely specified * @param recipientToken the default recipient token to be used when not explicitely specified * @param descriptorPolicy the descriptor policy to use as descriptive string on credit card statements * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @param server Which host to connect to. Usually, this will be fps.amazonaws.com. * You can also use fps.sandbox.amazonaws.com instead if you want to test your code within the Sandbox environment * @param uiPipeline the URL of the UI pipeline */ public FlexiblePaymentsService(String awsAccessId, String awsSecretKey, boolean isSecure, String callerToken, String recipientToken, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy, String server, String uiPipeline) { this(awsAccessId, awsSecretKey, isSecure, callerToken, recipientToken, descriptorPolicy, tempDeclinePolicy, server, isSecure ? 443 : 80, uiPipeline); } /** * Initializes the FPS service with your AWS login information. * * @param awsAccessId the your user key into AWS * @param awsSecretKey the secret string used to generate signatures for authentication. * @param isSecure true if the data should be encrypted on the wire on the way to or from FPS. * @param callerToken the default caller token to be used when not explicitely specified * @param recipientToken the default recipient token to be used when not explicitely specified * @param descriptorPolicy the descriptor policy to use as descriptive string on credit card statements * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @param server which host to connect to. Usually, this will be fps.amazonaws.com. * You can also use fps.sandbox.amazonaws.com instead if you want to test your code within the Sandbox environment * @param port which port to use * @param uiPipeline the URL of the UI pipeline */ public FlexiblePaymentsService(String awsAccessId, String awsSecretKey, boolean isSecure, String callerToken, String recipientToken, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy, String server, int port, String uiPipeline) { super(awsAccessId, awsSecretKey, isSecure, server, port); if (callerToken != null && !"".equals(callerToken) && callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes! Invalid value: " + callerToken); if (recipientToken != null && !"".equals(recipientToken) && recipientToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes! Invalid value: " + recipientToken); this.uiPipeline = uiPipeline; this.callerToken = "".equals(callerToken) ? null : callerToken; this.recipientToken = "".equals(recipientToken) ? null : recipientToken; this.descriptorPolicy = descriptorPolicy; this.tempDeclinePolicy = tempDeclinePolicy; setVersionHeader(this); setSignatureVersion(1); } /** * This method returns the signature version * * @return the version */ public int getSignatureVersion() { return 1; } /** * Cancel any token that you installed on your own account. * * @param tokenID the token to be cancelled * @throws FPSException wraps checked exceptions */ public void cancelToken(String tokenID) throws FPSException { cancelToken(tokenID, ""); } /** * Cancel any token that you installed on your own account. * * @param tokenID the token to be cancelled * @param reason reason for cancelling the token -- max 64 characters * @throws FPSException wraps checked exceptions */ public void cancelToken(String tokenID, String reason) throws FPSException { if (tokenID == null || tokenID.length() != 64) throw new IllegalArgumentException("The token must have a length of 64 bytes"); Map<String, String> params = new HashMap<String, String>(); params.put("TokenId", tokenID); params.put("ReasonText", reason); GetMethod method = new GetMethod(); try { makeRequestInt(method, "CancelToken", params, CancelTokenResponse.class); } finally { method.releaseConnection(); } } /** * Discard the results that are fetched using the {@link #getResults()} operation. * * @param transactionIDs the list of transaction to be discarded * @throws FPSException wraps checked exceptions */ public void discardResults(String... transactionIDs) throws FPSException { Map<String, String> params = new HashMap<String, String>(); for (int i = 0; i < transactionIDs.length; i++) params.put("TransactionID." + i, transactionIDs[i]); GetMethod method = new GetMethod(); try { makeRequestInt(method, "DiscardResults", params, DiscardResultsResponse.class); } finally { method.releaseConnection(); } } /** * Transfer money from the sender's payment instrument specified in the funding token to the recipient's account * balance. This operation creates a prepaid balance on the sender' prepaid instrument. * Note: there is no support for <tt>NewSenderTokenUsage</tt> yet. * * @param senderTokenID the token identifying the funding payment instructions * @param prepaidInstrumentID the prepaid instrument ID returned by the prepaid instrument installation pipeline * @param fundingAmount amount to fund the prepaid instrument * @param callerReference a unique reference that you specify in your system to identify a transaction * @return the completed transaction * @throws FPSException wraps checked exceptions */ public Transaction fundPrepaid(String senderTokenID, String prepaidInstrumentID, double fundingAmount, String callerReference) throws FPSException { return fundPrepaid(senderTokenID, callerToken, prepaidInstrumentID, fundingAmount, new Date(), null, null, callerReference, ChargeFeeTo.RECIPIENT, null, null, null, null, descriptorPolicy, tempDeclinePolicy ); } /** * Transfer money from the sender's payment instrument specified in the funding token to the recipient's account * balance. This operation creates a prepaid balance on the sender' prepaid instrument. * Note: there is no support for <tt>NewSenderTokenUsage</tt> yet. * * @param senderTokenID the token identifying the funding payment instructions * @param callerTokenID the caller's token ID * @param prepaidInstrumentID the prepaid instrument ID returned by the prepaid instrument installation pipeline * @param fundingAmount amount to fund the prepaid instrument * @param transactionDate the date specified by the caller and stored with the transaction * @param senderReference any reference that the caller might use to identify the sender in the transaction * @param recipientReference any reference that the caller might use to identify the recipient in the transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param chargeFeeTo the participant paying the fee for the transaction * @param senderDescription 128-byte field to store transaction description * @param recipientDescription 128-byte field to store transaction description * @param callerDescription 128-byte field to store transaction description * @param metadata a 2KB free-form field used to store transaction data * @param descriptorPolicy the soft descriptor type and the customer service number to pass to the payment processor * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @return the completed transaction * @throws FPSException wraps checked exceptions */ public Transaction fundPrepaid(String senderTokenID, String callerTokenID, String prepaidInstrumentID, double fundingAmount, Date transactionDate, String senderReference, String recipientReference, String callerReference, ChargeFeeTo chargeFeeTo, String senderDescription, String recipientDescription, String callerDescription, String metadata, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (callerTokenID == null || callerTokenID.length() != 64) throw new IllegalArgumentException("The token must have a length of 64 bytes"); Map<String, String> params = new HashMap<String, String>(); params.put("SenderTokenId", senderTokenID); params.put("CallerTokenId", callerTokenID); params.put("PrepaidInstrumentId", prepaidInstrumentID); params.put("FundingAmount", Double.toString(fundingAmount)); params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); params.put("CallerReference", callerReference); params.put("ChargeFeeTo", chargeFeeTo.value()); params.put("ChargeFeeTo", chargeFeeTo.value()); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); params.put("ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { FundPrepaidResponse response = makeRequestInt(method, "FundPrepaid", params, FundPrepaidResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.valueOf(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } public AccountActivity getAccountActivity(Date startDate) throws FPSException { return getAccountActivity(null, null, 0, startDate, null, null, null); } public AccountActivity getAccountActivity(Date startDate, Date endDate) throws FPSException { return getAccountActivity(null, null, 0, startDate, endDate, null, null); } /** * Retrieve transactions from an account for a given time period. * * @param filter operation type filter -- use null if this filter shouldn't be used * @param paymentMethod payment method filter -- use null if this filter shouldn't be used * @param maxBatchSize maximum number of transactions to be returned<br/> * {@link AccountActivity} is {@link Iterable} over each page of the paginated results from * the underneath FPS operation. * @param startDate will filter transactions beginning from that date * @param endDate will filter transactions ending up to that date * @param role role filter -- use null if this filter shouldn't be used * @param transactionStatus transaction status filter -- use null if this filter shouldn't be used * @return the account activity matching the filters * @throws FPSException wraps checked exceptions */ public AccountActivity getAccountActivity(FPSOperation filter, PaymentMethod paymentMethod, int maxBatchSize, Date startDate, Date endDate, TransactionalRoleFilter role, Transaction.Status transactionStatus) throws FPSException { if (startDate == null) throw new IllegalArgumentException("The start date should not be null!"); Map<String, String> params = new HashMap<String, String>(); if (filter != null) params.put("Operation", filter.value()); if (paymentMethod != null) params.put("PaymentMethod", paymentMethod.value()); if (maxBatchSize != 0) params.put("MaxBatchSize", Integer.toString(maxBatchSize)); params.put("StartDate", DataUtils.encodeDate(startDate)); if (endDate != null) params.put("EndDate", DataUtils.encodeDate(endDate)); if (role != null) params.put("Role", role.value()); if (transactionStatus != null) params.put("Status", transactionStatus.value()); GetMethod method = new GetMethod(); try { GetAccountActivityResponse response = makeRequestInt(method, "GetAccountActivity", params, GetAccountActivityResponse.class); Date nextStartDate = null; if (response.getStartTimeForNextTransaction() != null) nextStartDate = response.getStartTimeForNextTransaction().toGregorianCalendar().getTime(); BigInteger nbTransactions = response.getResponseBatchSize(); List<com.xerox.amazonws.typica.fps.jaxb.Transaction> rawTransactions = response.getTransactions(); List<Transaction> transactions = new ArrayList<Transaction>(rawTransactions.size()); for (com.xerox.amazonws.typica.fps.jaxb.Transaction txn : rawTransactions) { com.xerox.amazonws.typica.fps.jaxb.Amount txnAmount = txn.getTransactionAmount(); com.xerox.amazonws.typica.fps.jaxb.Amount fees = txn.getFees(); com.xerox.amazonws.typica.fps.jaxb.Amount balance = txn.getBalance(); transactions.add(new Transaction( txn.getTransactionId(), Transaction.Status.fromValue(txn.getStatus().value()), txn.getDateReceived().toGregorianCalendar().getTime(), txn.getDateCompleted().toGregorianCalendar().getTime(), new Amount(new BigDecimal(txnAmount.getAmount()), txnAmount.getCurrencyCode().toString()), FPSOperation.fromValue(txn.getOperation().value()), PaymentMethod.fromValue(txn.getPaymentMethod().value()), txn.getSenderName(), txn.getCallerName(), txn.getRecipientName(), new Amount(new BigDecimal(fees.getAmount()), fees.getCurrencyCode().toString()), new Amount(new BigDecimal(balance.getAmount()), balance.getCurrencyCode().toString()), txn.getCallerTokenId(), txn.getSenderTokenId(), txn.getRecipientTokenId() )); } return new AccountActivity(nextStartDate, nbTransactions, transactions, filter, paymentMethod, maxBatchSize, endDate, transactionStatus, this); } finally { method.releaseConnection(); } } /** * Retrieve all the prepaid instruments associated with your account * @return the list of prepaid instruments * @throws FPSException wraps checked exceptions */ public List<String> getAllPrepaidInstruments() throws FPSException { return getAllPrepaidInstruments(null); } /** * Retrieve all the prepaid instruments associated with your account * * @param instrumentStatus filter instruments by status * @return the list of prepaid instruments * @throws FPSException wraps checked exceptions */ public List<String> getAllPrepaidInstruments(Instrument.Status instrumentStatus) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (instrumentStatus != null) params.put("InstrumentStatus", instrumentStatus.value()); GetMethod method = new GetMethod(); try { GetAllPrepaidInstrumentsResponse response = makeRequestInt(method, "GetAllPrepaidInstruments", params, GetAllPrepaidInstrumentsResponse.class); return response.getPrepaidInstrumentIds(); } finally { method.releaseConnection(); } } /** * Retrieve all credit instruments associated with an account. * * @return the list of credit instruments IDs associated with the account * @throws FPSException wraps checked exceptions */ public List<String> getAllCreditInstruments() throws FPSException { return getAllCreditInstruments(null); } /** * Retrieve all credit instruments associated with an account. * * @return the list of credit instruments balances associated with the account * @throws FPSException wraps checked exceptions */ public List<DebtBalance> getAllCreditInstrumentBalances() throws FPSException { return getAllCreditInstrumentBalances(null); } /** * Retrieve all credit instruments associated with an account. * * @param instrumentStatus filter instruments by status * @return the list of credit instruments IDs associated with the account * @throws FPSException wraps checked exceptions */ public List<String> getAllCreditInstruments(Instrument.Status instrumentStatus) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (instrumentStatus != null) params.put("InstrumentStatus", instrumentStatus.value()); GetMethod method = new GetMethod(); try { GetAllCreditInstrumentsResponse response = makeRequestInt(method, "GetAllCreditInstruments", params, GetAllCreditInstrumentsResponse.class); return response.getCreditInstrumentIds(); } finally { method.releaseConnection(); } } /** * Retrieve all credit instruments associated with an account. * * @param instrumentStatus filter instruments by status * @return the list of credit instruments balances associated with the account * @throws FPSException wraps checked exceptions */ public List<DebtBalance> getAllCreditInstrumentBalances(Instrument.Status instrumentStatus) throws FPSException { List<String> creditInstruments = getAllCreditInstruments(instrumentStatus); List<DebtBalance> balances = new ArrayList<DebtBalance>(creditInstruments.size()); for (String instrument : creditInstruments) balances.add(getDebtBalance(instrument)); return balances; } /** * Retrieve the balance of a credit instrument. * Note: only on the instruments for which you are the sender or the recipient can be queried * * @param creditInstrumentId the credit instrument Id for which debt balance is queried * @return the balance * @throws FPSException wraps checked exceptions */ public DebtBalance getDebtBalance(String creditInstrumentId) throws FPSException { Map<String, String> params = new HashMap<String, String>(); params.put("CreditInstrumentId", creditInstrumentId); GetMethod method = new GetMethod(); try { GetDebtBalanceResponse response = makeRequestInt(method, "GetDebtBalance", params, GetDebtBalanceResponse.class); com.xerox.amazonws.typica.fps.jaxb.DebtBalance balance = response.getDebtBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount availableBalance = balance.getAvailableBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount pendingOutBalance = balance.getPendingOutBalance(); return new DebtBalance( new Amount(new BigDecimal(availableBalance.getAmount()), availableBalance.getCurrencyCode().toString()), new Amount(new BigDecimal(pendingOutBalance.getAmount()), pendingOutBalance.getCurrencyCode().toString()) ); } finally { method.releaseConnection(); } } /** * Retrieve balances of all credit instruments owned by the sender. * Note: only on the instruments for which you are the sender or the recipient can be queried * * @return the aggregated balance * @throws FPSException wraps checked exceptions */ public DebtBalance getOutstandingDebtBalance() throws FPSException { Map<String, String> params = new HashMap<String, String>(); GetMethod method = new GetMethod(); try { GetOutstandingDebtBalanceResponse response = makeRequestInt(method, "GetOutstandingDebtBalance", params, GetOutstandingDebtBalanceResponse.class); OutstandingDebtBalance balance = response.getOutstandingDebt(); com.xerox.amazonws.typica.fps.jaxb.Amount outstanding = balance.getOutstandingBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount pendingOut = balance.getPendingOutBalance(); return new DebtBalance( new Amount(new BigDecimal(outstanding.getAmount()), outstanding.getCurrencyCode().toString()), new Amount(new BigDecimal(pendingOut.getAmount()), pendingOut.getCurrencyCode().toString()) ); } finally { method.releaseConnection(); } } /** * Retrieve the details of a payment instruction. * * @param tokenID token for which the payment instruction is to be retrieved * @return a 64-character alphanumeric string that represents the installed payment instruction * @throws FPSException wraps checked exceptions */ public PaymentInstructionDetail getPaymentInstruction(String tokenID) throws FPSException { Map<String, String> params = new HashMap<String, String>(); params.put("TokenId", tokenID); GetMethod method = new GetMethod(); try { GetPaymentInstructionResponse response = makeRequestInt(method, "GetPaymentInstruction", params, GetPaymentInstructionResponse.class); Token token = new Token( response.getToken().getTokenId(), response.getToken().getFriendlyName(), Token.Status.fromValue(response.getToken().getStatus().value()), response.getToken().getDateInstalled().toGregorianCalendar().getTime(), response.getToken().getCallerInstalled(), TokenType.fromValue(response.getToken().getTokenType().value()), response.getToken().getOldTokenId(), response.getToken().getPaymentReason() ); return new PaymentInstructionDetail(token, response.getPaymentInstruction(), response.getAccountId(), response.getTokenFriendlyName()); } finally { method.releaseConnection(); } } /** * Retrieve the balance of a prepaid instrument. * Note: only on the instruments for which you are the sender or the recipient can be queried * * @param prepaidInstrumentId prepaid instrument for which the balance is queried * @return the balance * @throws FPSException wraps checked exceptions */ public PrepaidBalance getPrepaidBalance(String prepaidInstrumentId) throws FPSException { Map<String, String> params = new HashMap<String, String>(); params.put("PrepaidInstrumentId", prepaidInstrumentId); GetMethod method = new GetMethod(); try { GetPrepaidBalanceResponse response = makeRequestInt(method, "GetPrepaidBalance", params, GetPrepaidBalanceResponse.class); com.xerox.amazonws.typica.fps.jaxb.PrepaidBalance balance = response.getPrepaidBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount availableBalance = balance.getAvailableBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount pendingOutBalance = balance.getPendingInBalance(); return new PrepaidBalance( new Amount(new BigDecimal(availableBalance.getAmount()), availableBalance.getCurrencyCode().toString()), new Amount(new BigDecimal(pendingOutBalance.getAmount()), pendingOutBalance.getCurrencyCode().toString()) ); } finally { method.releaseConnection(); } } /** * This operation is used to poll for transaction results that are returned asynchronously. * * @throws FPSException wraps checked exceptions */ public List<TransactionResult> getResults() throws FPSException { return getResults(null, null); } /** * This operation is used to poll for transaction results that are returned asynchronously. * * @param operation Used to filter results based on the operation type (e.g. Pay, Refund, Settle, SettleDebt, WriteOffDebt, FundPrepaid) * @param maxResultsCount Used to specify the maximum results that can be retrieved. The minimum value is 1 and the maximum value is 25. By default the maximum or the available results are returned. * @return the list of transactions * @throws FPSException wraps checked exceptions */ public List<TransactionResult> getResults(FPSOperationFilter operation, Integer maxResultsCount) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (operation != null) params.put("Operation", operation.toString()); if (maxResultsCount != null) params.put("MaxResultsCount", maxResultsCount.toString()); GetMethod method = new GetMethod(); try { GetResultsResponse response = makeRequestInt(method, "GetResults", params, GetResultsResponse.class); List<com.xerox.amazonws.typica.fps.jaxb.TransactionResult> rawTransactions = response.getTransactionResults(); List<TransactionResult> transactionResults = new ArrayList<TransactionResult>(rawTransactions.size()); for (com.xerox.amazonws.typica.fps.jaxb.TransactionResult txn : rawTransactions) { transactionResults.add(new TransactionResult( txn.getTransactionId(), FPSOperation.fromValue(txn.getOperation().value()), txn.getCallerReference(), Transaction.Status.fromValue(txn.getStatus().value()) )); } return transactionResults; } finally { method.releaseConnection(); } } /** * Fetch all the tokens installed on your (caller) account. * * @return the list of tokens * @throws FPSException wraps checked exceptions */ public List<Token> getAllTokens() throws FPSException { return getTokens(null, null, null); } /** * Fetch the tokens installed on your (caller) account, filtered by friendly name. * * @param tokenFriendlyName filter by friendly name * @return the list of tokens * @throws FPSException wraps checked exceptions */ public List<Token> getTokensByFriendlyName(String tokenFriendlyName) throws FPSException { return getTokens(tokenFriendlyName, null, null); } /** * Fetch the tokens installed on your (caller) account, filtered by status. * * @param tokenStatus filter by token status * @return the list of tokens * @throws FPSException wraps checked exceptions */ public List<Token> getTokensByStatus(Token.Status tokenStatus) throws FPSException { return getTokens(null, tokenStatus, null); } /** * Fetch the tokens installed on your (caller) account, filtered by caller reference. * * @param callerReference filter by caller reference * @return the list of tokens * @throws FPSException wraps checked exceptions */ public List<Token> getTokensByCallerReference(String callerReference) throws FPSException { return getTokens(null, null, callerReference); } /** * Fetch the tokens installed on your (caller) account, based on the filtering parameters. * A null parameter means to NOT filter on that parameter. * * @param tokenFriendlyName filter by friendly name * @param tokenStatus filter by token status * @param callerReference filter by caller reference * @return the list of tokens * @throws FPSException wraps checked exceptions */ public List<Token> getTokens(String tokenFriendlyName, Token.Status tokenStatus, String callerReference) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (tokenFriendlyName != null) params.put("TokenFriendlyName", tokenFriendlyName); if (tokenStatus != null) params.put("TokenStatus", tokenStatus.value()); if (callerReference != null) params.put("CallerReference", callerReference); GetMethod method = new GetMethod(); try { GetTokensResponse response = makeRequestInt(method, "GetTokens", params, GetTokensResponse.class); List<com.xerox.amazonws.typica.fps.jaxb.Token> rawTokens = response.getTokens(); List<Token> tokens = new ArrayList<Token>(rawTokens.size()); for (com.xerox.amazonws.typica.fps.jaxb.Token token : rawTokens) { tokens.add(new Token( token.getTokenId(), token.getFriendlyName(), Token.Status.fromValue(token.getStatus().value()), token.getDateInstalled().toGregorianCalendar().getTime(), token.getCallerInstalled(), TokenType.fromValue(token.getTokenType().value()), token.getOldTokenId(), token.getPaymentReason() )); } return tokens; } finally { method.releaseConnection(); } } /** * Fetch the details of a particular token. * * @param tokenID the token Id of the specific token installed on the callers account * @return the token * @throws FPSException wraps checked exceptions */ public Token getTokenByID(String tokenID) throws FPSException { return getToken(tokenID, null); } /** * Fetch the details of a particular token. * * @param callerReference the caller reference that was passed at the time of the token installation * @return the token * @throws FPSException wraps checked exceptions */ public Token getTokenByCaller(String callerReference) throws FPSException { return getToken(null, callerReference); } /** * Fetch the details of a particular token. * * @param tokenID the token Id of the specific token installed on the callers account * @param callerReference the caller reference that was passed at the time of the token installation * @return the token * @throws FPSException wraps checked exceptions */ private Token getToken(String tokenID, String callerReference) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (tokenID == null && callerReference == null) throw new IllegalArgumentException("Either the token ID or the caller reference must be given!"); if (tokenID != null && tokenID.length() != 64) throw new IllegalArgumentException("The token must have a length of 64 bytes"); if (tokenID != null) params.put("TokenId", tokenID); if (callerReference != null) params.put("CallerReference", callerReference); GetMethod method = new GetMethod(); try { GetTokenByCallerResponse response = makeRequestInt(method, "GetTokenByCaller", params, GetTokenByCallerResponse.class); return new Token( response.getToken().getTokenId(), response.getToken().getFriendlyName(), Token.Status.fromValue(response.getToken().getStatus().value()), response.getToken().getDateInstalled().toGregorianCalendar().getTime(), response.getToken().getCallerInstalled(), TokenType.fromValue(response.getToken().getTokenType().value()), response.getToken().getOldTokenId(), response.getToken().getPaymentReason() ); } finally { method.releaseConnection(); } } /** * Fetch the details and usage of a multi-use token. * Note: the usage limit is returned only for the multi-use token and not for the single-use token * @param tokenID the token for which the usage is queried * @return the list of available usage limits on the token * @throws FPSException wraps checked exceptions */ public List<TokenUsageLimit> getTokenUsage(String tokenID) throws FPSException { Map<String, String> params = new HashMap<String, String>(); if (tokenID == null) throw new IllegalArgumentException("Either the token ID or the caller reference must be given!"); if (tokenID.length() != 64) throw new IllegalArgumentException("The token must have a length of 64 bytes"); params.put("TokenId", tokenID); GetMethod method = new GetMethod(); try { GetTokenUsageResponse response = makeRequestInt(method, "GetTokenUsage", params, GetTokenUsageResponse.class); List<TokenUsageLimit> limits = new ArrayList<TokenUsageLimit>(response.getTokenUsageLimits().size()); for (com.xerox.amazonws.typica.fps.jaxb.TokenUsageLimit limit : response.getTokenUsageLimits()) { limits.add(new TokenUsageLimit( limit.getCount(), new Amount( new BigDecimal(limit.getAmount().getAmount()), limit.getAmount().getCurrencyCode().value() ), limit.getLastResetCount(), new Amount( new BigDecimal(limit.getLastResetAmount().getAmount()), limit.getLastResetAmount().getCurrencyCode().value() ), limit.getLastResetTimeStamp().toGregorianCalendar().getTime() )); } return limits; } finally { method.releaseConnection(); } } /** * Returns the total liability held by the recipient corresponding to all the prepaid instruments. * @return the total liability * @throws FPSException wraps checked exceptions */ public OutstandingPrepaidLiability getTotalPrepaidLiability() throws FPSException { Map<String, String> params = new HashMap<String, String>(); GetMethod method = new GetMethod(); try { GetTotalPrepaidLiabilityResponse response = makeRequestInt(method, "GetTotalPrepaidLiability", params, GetTotalPrepaidLiabilityResponse.class); com.xerox.amazonws.typica.fps.jaxb.OutstandingPrepaidLiability liability = response.getOutstandingPrepaidLiability(); return new OutstandingPrepaidLiability( new Amount( new BigDecimal(liability.getOutstandingBalance().getAmount()), liability.getOutstandingBalance().getCurrencyCode().value() ), new Amount( new BigDecimal(liability.getPendingInBalance().getAmount()), liability.getPendingInBalance().getCurrencyCode().value() ) ); } finally { method.releaseConnection(); } } /** * Fetch details of a transaction referred by the <tt>transactionId</tt>. * * @param transactionID a transaction Id for the query * @return the transaction * @throws FPSException wraps checked exceptions */ public TransactionDetail getTransaction(String transactionID) throws FPSException { Map<String, String> params = new HashMap<String, String>(); params.put("TransactionId", transactionID); GetMethod method = new GetMethod(); try { GetTransactionResponse response = makeRequestInt(method, "GetTransaction", params, GetTransactionResponse.class); com.xerox.amazonws.typica.fps.jaxb.TransactionDetail txn = response.getTransaction(); return new TransactionDetail( txn.getTransactionId(), txn.getCallerTransactionDate().toGregorianCalendar().getTime(), txn.getDateReceived().toGregorianCalendar().getTime(), txn.getDateCompleted().toGregorianCalendar().getTime(), new Amount( new BigDecimal(txn.getTransactionAmount().getAmount()), txn.getTransactionAmount().getCurrencyCode().value() ), new Amount( new BigDecimal(txn.getFees().getAmount()), txn.getFees().getCurrencyCode().value() ), txn.getCallerTokenId(), txn.getSenderTokenId(), txn.getRecipientTokenId(), txn.getPrepaidInstrumentId(), txn.getCreditInstrumentId(), FPSOperation.fromValue(txn.getOperation().value()), PaymentMethod.fromValue(txn.getPaymentMethod().value()), Transaction.Status.fromValue(txn.getStatus().value()), txn.getErrorCode(), txn.getErrorMessage(), txn.getMetaData(), txn.getSenderName(), txn.getCallerName(), txn.getRecipientName() ); } finally { method.releaseConnection(); } } /** * Install unrestricted caller token on your own accounts. * * @param callerReference a unique reference to the payment instructions. This is used to recover or retrieve * tokens that are lost or not received after the payment instruction is installed * @return a 64-character alphanumeric string that represents the installed payment instruction * @throws FPSException wraps checked exceptions */ public String installUnrestrictedCallerPaymentInstruction(String callerReference) throws FPSException { return installPaymentInstruction("MyRole == 'Caller' orSay 'Role does not match';", callerReference, callerReference, TokenType.UNRESTRICTED, callerReference); } /** * Install unrestricted recipient token on your own accounts. * * @param callerReference a unique reference to the payment instructions. This is used to recover or retrieve * tokens that are lost or not received after the payment instruction is installed * @return a 64-character alphanumeric string that represents the installed payment instruction * @throws FPSException wraps checked exceptions */ public String installUnrestrictedRecipientPaymentInstruction(String callerReference) throws FPSException { return installPaymentInstruction("MyRole == 'Recipient' orSay 'Role does not match';", callerReference, callerReference, TokenType.UNRESTRICTED, callerReference); } /** * Install tokens (payment instructions) on your own accounts. * * @param paymentInstruction set of rules in the GateKeeper language format to be installed on the caller's account * @param callerReference a unique reference to the payment instructions. This is used to recover or retrieve * tokens that are lost or not received after the payment instruction is installed * @param type the type of token * @return a 64-character alphanumeric string that represents the installed payment instruction * @throws FPSException wraps checked exceptions */ public String installPaymentInstruction(String paymentInstruction, String callerReference, TokenType type) throws FPSException { return installPaymentInstruction(paymentInstruction, null, callerReference, type, null); } /** * Install tokens (payment instructions) on your own accounts. * * @param paymentInstruction set of rules in the GateKeeper language format to be installed on the caller's account * @param tokenFriendlyName a human-friendly, readable name for the payment instruction * @param callerReference a unique reference to the payment instructions. This is used to recover or retrieve * tokens that are lost or not received after the payment instruction is installed * @param type the type of token * @param comment the reason for making the payment * @return a 64-character alphanumeric string that represents the installed payment instruction * @throws FPSException wraps checked exceptions */ public String installPaymentInstruction(String paymentInstruction, String tokenFriendlyName, String callerReference, TokenType type, String comment) throws FPSException { Map<String, String> params = new HashMap<String, String>(); params.put("PaymentInstruction", paymentInstruction); if (tokenFriendlyName != null) params.put("TokenFriendlyName", tokenFriendlyName); params.put("CallerReference", callerReference); params.put("TokenType", type.value()); if (comment != null) params.put("PaymentReason", comment); GetMethod method = new GetMethod(); try { InstallPaymentInstructionResponse response = makeRequestInt(method, "InstallPaymentInstruction", params, InstallPaymentInstructionResponse.class); return response.getTokenId(); } finally { method.releaseConnection(); } } /** * Initiate a transaction to move funds from the sender to the recipient. * * @param senderToken sender token * @param amount amount to be charged to the sender * @param callerReference a unique reference that you specify in your system to identify a transaction * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction pay(String senderToken, Amount amount, String callerReference) throws FPSException { return pay(recipientToken, senderToken, callerToken, amount, new Date(), ChargeFeeTo.RECIPIENT, callerReference, null, null, null, null, null, null, 0, 0, descriptorPolicy); } /** * Initiate a transaction to move funds from the sender to the recipient. * * @param senderToken sender token * @param amount amount to be charged to the sender * @param callerReference a unique reference that you specify in your system to identify a transaction * @param descriptorPolicy the soft descriptor type and the customer service number to pass to the payment processor * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction pay(String senderToken, Amount amount, String callerReference, DescriptorPolicy descriptorPolicy) throws FPSException { return pay(recipientToken, senderToken, callerToken, amount, new Date(), ChargeFeeTo.RECIPIENT, callerReference, null, null, null, null, null, null, 0, 0, descriptorPolicy); } /** * Initiate a transaction to move funds from the sender to the recipient. * * @param recipientToken recipient token * @param senderToken sender token * @param callerToken caller token * @param amount amount to be charged to the sender * @param transactionDate the date specified by the caller and stored with the transaction * @param chargeFeeTo the participant paying the fee for the transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param senderReference any reference that the caller might use to identify the sender in the transaction * @param recipientReference any reference that the caller might use to identify the recipient in the transaction * @param senderDescription 128-byte field to store transaction description * @param recipientDescription 128-byte field to store transaction description * @param callerDescription 128-byte field to store transaction description * @param metadata a 2KB free-form field used to store transaction data * @param marketplaceFixedFee the fee charged by the marketplace developer as a fixed amount of the transaction * @param marketplaceVariableFee the fee charged by the marketplace developer as a variable amount of the transaction * @param descriptorPolicy the soft descriptor type and the customer service number to pass to the payment processor * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction pay(String recipientToken, String senderToken, String callerToken, Amount amount, Date transactionDate, ChargeFeeTo chargeFeeTo, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, double marketplaceFixedFee, int marketplaceVariableFee, DescriptorPolicy descriptorPolicy) throws FPSException { return pay(recipientToken, senderToken, callerToken, amount, transactionDate, chargeFeeTo, callerReference, senderReference, recipientReference, senderDescription, recipientDescription, callerDescription, metadata, marketplaceFixedFee, marketplaceVariableFee, descriptorPolicy, tempDeclinePolicy); } /** * Initiate a transaction to move funds from the sender to the recipient. * * @param recipientToken recipient token * @param senderToken sender token * @param callerToken caller token * @param amount amount to be charged to the sender * @param transactionDate the date specified by the caller and stored with the transaction * @param chargeFeeTo the participant paying the fee for the transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param senderReference any reference that the caller might use to identify the sender in the transaction * @param recipientReference any reference that the caller might use to identify the recipient in the transaction * @param senderDescription 128-byte field to store transaction description * @param recipientDescription 128-byte field to store transaction description * @param callerDescription 128-byte field to store transaction description * @param metadata a 2KB free-form field used to store transaction data * @param marketplaceFixedFee the fee charged by the marketplace developer as a fixed amount of the transaction * @param marketplaceVariableFee the fee charged by the marketplace developer as a variable amount of the transaction * @param descriptorPolicy the soft descriptor type and the customer service number to pass to the payment processor * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction pay(String recipientToken, String senderToken, String callerToken, Amount amount, Date transactionDate, ChargeFeeTo chargeFeeTo, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, double marketplaceFixedFee, int marketplaceVariableFee, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (recipientToken != null && recipientToken.length() != 64) throw new IllegalArgumentException("The recipient token must have a length of 64 bytes"); if (senderToken != null && senderToken.length() != 64) throw new IllegalArgumentException("The sender token must have a length of 64 bytes"); if (callerToken != null && callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (logger.isInfoEnabled()) logger.info("Payment: " + senderToken + " paying " + recipientToken + " for " + amount); Map<String, String> params = new HashMap<String, String>(); if (recipientToken != null) params.put("RecipientTokenId", recipientToken); params.put("SenderTokenId", senderToken); params.put("CallerTokenId", callerToken); params.put("TransactionAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("TransactionAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); params.put("ChargeFeeTo", chargeFeeTo.value()); params.put("CallerReference", callerReference); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (marketplaceFixedFee != 0) params.put("MarketplaceFixedFee", Double.toString(marketplaceFixedFee)); if (marketplaceVariableFee != 0) params.put("MarketplaceVariableFee", Integer.toString(marketplaceVariableFee)); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); - params.put("ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); + params.put("TemporaryDeclinePolicy.ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { PayResponse response = makeRequestInt(method, "Pay", params, PayResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * Refund a successfully completed payment transaction. * * @param senderToken token of the original recipient who is now the sender in the refund * @param transactionID the transaction that is to be refunded * @param callerReference a unique reference that identifies this refund * @return the refund transaction * @throws FPSException FPSException wraps checked exceptions */ public Transaction refund(String senderToken, String transactionID, String callerReference) throws FPSException { return refund(callerToken, senderToken, transactionID, null, ChargeFeeTo.RECIPIENT, new Date(), callerReference, null, null, null, null, null, null, null); } /** * Refund a successfully completed payment transaction. * * @param callerToken the caller token * @param senderToken token of the original recipient who is now the sender in the refund * @param transactionID the transaction that is to be refunded< * @param refundAmount the amount to be refunded<br/> * If this value is not specified, then the remaining funds from the original transaction * is refunded. * @param chargeFeeTo the participant who pays the fee<br/> * Currently Amazon FPS does not charge any fee for the refund and this has no impact on * the transaction * @param transactionDate the date of the transaction from the caller * @param callerReference a unique reference that identifies this refund * @param senderReference the reference created by the recipient of original transaction for this refund transaction * @param recipientReference the reference created by the Sender (of the original transaction) for this refund transaction * @param senderDescription a 128-byte field to store transaction description * @param recipientDescription a 128-byte field to store transaction description * @param callerDescription a 128-byte field to store transaction description * @param metadata a 2KB free form field used to store transaction data * @param policy the refund choice: refund the master transaction, the marketplace fee, or both * @return the refund transaction * @throws FPSException FPSException wraps checked exceptions */ public Transaction refund(String callerToken, String senderToken, String transactionID, Amount refundAmount, ChargeFeeTo chargeFeeTo, Date transactionDate, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, MarketplaceRefundPolicy policy) throws FPSException { if (callerToken == null || callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (logger.isInfoEnabled()) logger.info("Refund: " + senderToken + " refunding transaction " + transactionID + " for " + refundAmount); Map<String, String> params = new HashMap<String, String>(); params.put("CallerTokenId", callerToken); params.put("RefundSenderTokenId", senderToken); params.put("TransactionId", transactionID); if (refundAmount != null) { params.put("RefundAmount.Amount", refundAmount.getAmount().toString()); params.put("RefundAmount.CurrencyCode", refundAmount.getCurrencyCode()); } params.put("ChargeFeeTo", chargeFeeTo.value()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); params.put("CallerReference", callerReference); if (senderReference != null) params.put("RefundSenderReference", senderReference); if (recipientReference != null) params.put("RefundRecipientReference", recipientReference); if (senderDescription != null) params.put("RefundSenderDescription", senderDescription); if (recipientDescription != null) params.put("RefundRecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (policy != null) params.put("MarketplaceRefundPolicy", policy.value()); GetMethod method = new GetMethod(); try { RefundResponse response = makeRequestInt(method, "Refund", params, RefundResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * This operation is part of the Reserve and Settle operations that allow payment transactions when the * authorization and settlement have a time difference. The transaction is not complete until the Settle * operation is executed successfully. A reserve authorization is only valid for 7 days. * Currently, you can't cancel a reserve. * * @param senderToken sender token * @param amount amount to be reserved on the sender account/credit card * @param callerReference a unique reference that you specify in your system to identify a transaction * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction reserve(String senderToken, Amount amount, String callerReference) throws FPSException { return reserve(recipientToken, senderToken, callerToken, amount, new Date(), ChargeFeeTo.RECIPIENT, callerReference, null, null, null, null, null, null, 0, 0, descriptorPolicy, tempDeclinePolicy); } /** * This operation is part of the Reserve and Settle operations that allow payment transactions when the * authorization and settlement have a time difference. The transaction is not complete until the Settle * operation is executed successfully. A reserve authorization is only valid for 7 days. * Currently, you can't cancel a reserve. * * @param recipientToken recipient token * @param senderToken sender token * @param callerToken caller token * @param amount amount to be reserved on the sender account/credit card * @param transactionDate the date specified by the caller and stored with the transaction * @param chargeFeeTo the participant paying the fee for the transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param senderReference any reference that the caller might use to identify the sender in the transaction * @param recipientReference any reference that the caller might use to identify the recipient in the transaction * @param senderDescription 128-byte field to store transaction description * @param recipientDescription 128-byte field to store transaction description * @param callerDescription 128-byte field to store transaction description * @param metadata a 2KB free-form field used to store transaction data * @param marketplaceFixedFee the fee charged by the marketplace developer as a fixed amount of the transaction * @param marketplaceVariableFee the fee charged by the marketplace developer as a variable amount of the transaction * @param descriptorPolicy the soft descriptor type and the customer service number to pass to the payment processor * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction reserve(String recipientToken, String senderToken, String callerToken, Amount amount, Date transactionDate, ChargeFeeTo chargeFeeTo, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, double marketplaceFixedFee, int marketplaceVariableFee, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (recipientToken == null || recipientToken.length() != 64) throw new IllegalArgumentException("The recipient token must have a length of 64 bytes"); if (senderToken == null || senderToken.length() != 64) throw new IllegalArgumentException("The sender token must have a length of 64 bytes"); if (callerToken == null || callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (logger.isInfoEnabled()) logger.info("Reserve: " + recipientToken + " reserving " + senderToken + " for " + amount); Map<String, String> params = new HashMap<String, String>(); params.put("RecipientTokenId", recipientToken); params.put("SenderTokenId", senderToken); params.put("CallerTokenId", callerToken); params.put("TransactionAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("TransactionAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); params.put("ChargeFeeTo", chargeFeeTo.value()); params.put("CallerReference", callerReference); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (marketplaceFixedFee != 0) params.put("MarketplaceFixedFee", Double.toString(marketplaceFixedFee)); if (marketplaceVariableFee != 0) params.put("MarketplaceVariableFee", Integer.toString(marketplaceVariableFee)); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); params.put("ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { ReserveResponse response = makeRequestInt(method, "Reserve", params, ReserveResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * Submits a transaction for processing. * If a transaction was temporarily declined, the transaction can be processed again using the original transaction ID. * * @param transactionID the transaction to retry * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction retryTransaction(String transactionID) throws FPSException { if (transactionID == null || transactionID.length() == 0 || transactionID.length() > 35) throw new IllegalArgumentException("The transaction ID must not be null/empty and has a max size of 35 bytes"); if (logger.isInfoEnabled()) logger.info("Retry tranasction: " + transactionID); Map<String, String> params = new HashMap<String, String>(); params.put("OriginalTransactionId", transactionID); GetMethod method = new GetMethod(); try { RetryTransactionResponse response = makeRequestInt(method, "RetryTransaction", params, RetryTransactionResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * Settles fully or partially the amount that is reserved using the {@link #reserve} operation * * @param reserveTransactionID the transaction ID of the reserve transaction that has to be settled * @param amount amount to be settled * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction settle(String reserveTransactionID, Amount amount) throws FPSException { return settle(reserveTransactionID, amount, null); } /** * Settles fully or partially the amount that is reserved using the {@link #reserve} operation * * @param reserveTransactionID the transaction ID of the reserve transaction that has to be settled * @param amount amount to be settled * @param transactionDate the date of the transaction * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction settle(String reserveTransactionID, Amount amount, Date transactionDate) throws FPSException { if (reserveTransactionID == null || reserveTransactionID.length() == 0 || reserveTransactionID.length() > 35) throw new IllegalArgumentException("The reserve transaction ID must not be null/empty and has a max size of 35 bytes"); if (logger.isInfoEnabled()) logger.info("Settle: " + reserveTransactionID + " for " + amount); Map<String, String> params = new HashMap<String, String>(); params.put("ReserveTransactionId", reserveTransactionID); params.put("TransactionAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("TransactionAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); GetMethod method = new GetMethod(); try { SettleResponse response = makeRequestInt(method, "Settle", params, SettleResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * The SettleDebt operation takes the settlement amount, credit instrument, and the settlement token among other * parameters. Using this operation you can: * <ul> * <li> * Transfer money from sender's payment instrument specified in the settlement token to the recipient's * account balance. The fee charged is deducted from the settlement amount and deposited into recipient's * account balance. * </li> * <li> * Decrement debt balances by the settlement amount. * </li> * </ul> * @param settlementToken the token ID of the settlement token * @param creditInstrument the credit instrument Id returned by the co-branded UI pipeline * @param amount the amount for the settlement * @param callerReference a unique reference that you specify in your system to identify a transaction * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction settleDebt(String settlementToken, String creditInstrument, Amount amount, String callerReference) throws FPSException { return settleDebt(settlementToken, callerToken, creditInstrument, amount, new Date(), null, null, callerReference, ChargeFeeTo.RECIPIENT, null, null, null, null, descriptorPolicy, tempDeclinePolicy); } /** * The SettleDebt operation takes the settlement amount, credit instrument, and the settlement token among other * parameters. Using this operation you can: * <ul> * <li> * Transfer money from sender's payment instrument specified in the settlement token to the recipient's * account balance. The fee charged is deducted from the settlement amount and deposited into recipient's * account balance. * </li> * <li> * Decrement debt balances by the settlement amount. * </li> * </ul> * @param settlementToken the token ID of the settlement token * @param callerToken the callers token * @param creditInstrument the credit instrument Id returned by the co-branded UI pipeline * @param amount the amount for the settlement * @param transactionDate the date of the callers transaction * @param senderReference the unique value that will be used as a reference for the sender in this transaction * @param recipientReference the unique value that will be used as a reference for the recipient in this transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param chargeFeeTo the participant paying the fee for the transaction * @param senderDescription a 128-byte field to store transaction description * @param recipientDescription a 128-byte field to store transaction description * @param callerDescription a 128-byte field to store transaction description * @param metadata a 2KB free form field used to store transaction data * @param descriptorPolicy the descriptor policy to use as descriptive string on credit card statements * @param tempDeclinePolicy the temporary decline policy and the retry time out (in minutes) * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction settleDebt(String settlementToken, String callerToken, String creditInstrument, Amount amount, Date transactionDate, String senderReference, String recipientReference, String callerReference, ChargeFeeTo chargeFeeTo, String senderDescription, String recipientDescription, String callerDescription, String metadata, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (settlementToken == null || settlementToken.length() != 64) throw new IllegalArgumentException("The settlement token must have a length of 64 bytes"); if (callerToken == null || callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); Map<String, String> params = new HashMap<String, String>(); params.put("SenderTokenId", settlementToken); params.put("CallerTokenId", callerToken); params.put("CreditInstrumentId", creditInstrument); params.put("SettlementAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("SettlementAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); params.put("CallerReference", callerReference); params.put("ChargeFeeTo", chargeFeeTo.value()); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); params.put("ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { SettleDebtResponse response = makeRequestInt(method, "SettleDebt", params, SettleDebtResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * Allows callers to subscribe to events that are given out using the web service notification mechanism. * This operation is used for subscribing to the notifications provided to callers through web services. * Amazon FPS supports two events, Transaction results and token deletion that you can subscribe. * @param operationType specify the event types for which the notifications are required * @param webService the URL to your web service * @throws FPSException wraps checked exceptions */ public void subscribeForCallerNotification(NotificationEventType operationType, URL webService) throws FPSException { if (operationType == null) throw new IllegalArgumentException("The notification operation name is required!"); if (webService == null) throw new IllegalArgumentException("The Web Service API URL is required!"); if (logger.isInfoEnabled()) logger.info("Subscribe for caller notification for operations " + operationType + " at " + webService); Map<String, String> params = new HashMap<String, String>(); params.put("NotificationOperationName", operationType.value()); params.put("WebServiceAPIURLt", webService.toString()); GetMethod method = new GetMethod(); try { makeRequestInt(method, "SubscribeForCallerNotification", params, SubscribeForCallerNotificationResponse.class); } finally { method.releaseConnection(); } } /** * Allows callers to unsubscribe to events that are previously subscribed by the calling applications. * @param operationType specify the event types for which the notifications are required * @throws FPSException wraps checked exceptions */ public void unsubscribeForCallerNotification(NotificationEventType operationType) throws FPSException { if (operationType == null) throw new IllegalArgumentException("The notification operation name is required!"); if (logger.isInfoEnabled()) logger.info("Unsubscribe for caller notification for operations " + operationType); Map<String, String> params = new HashMap<String, String>(); params.put("NotificationOperationName", operationType.value()); GetMethod method = new GetMethod(); try { makeRequestInt(method, "UnSubscribeForCallerNotification", params, UnSubscribeForCallerNotificationResponse.class); } finally { method.releaseConnection(); } } /** * Write off the debt accumulated by the recipient on any credit instrument * @param creditInstrument the credit instrument Id returned by the co-branded UI pipeline * @param adjustmentAmount the amount for the settlement<br/> * if the <tt>adjustmentAmount</tt> is not a positive value, * a {@link IllegalArgumentException} is thrown * @param callerReference a unique reference that you specify in your system to identify a transaction * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction writeOffDebt(String creditInstrument, double adjustmentAmount, String callerReference) throws FPSException { return writeOffDebt(callerToken, creditInstrument, adjustmentAmount, new Date(), callerReference, null, null, null, null, null, null); } /** * Write off the debt accumulated by the recipient on any credit instrument * @param callerToken the callers token * @param creditInstrument the credit instrument Id returned by the co-branded UI pipeline * @param adjustmentAmount the amount for the settlement<br/> * if the <tt>adjustmentAmount</tt> is not a positive value, * a {@link IllegalArgumentException} is thrown * @param transactionDate the date of the callers transaction * @param senderReference the unique value that will be used as a reference for the sender in this transaction * @param recipientReference the unique value that will be used as a reference for the recipient in this transaction * @param callerReference a unique reference that you specify in your system to identify a transaction * @param senderDescription a 128-byte field to store transaction description * @param recipientDescription a 128-byte field to store transaction description * @param callerDescription a 128-byte field to store transaction description * @param metadata a 2KB free form field used to store transaction data * @return the transaction * @throws FPSException wraps checked exceptions */ public Transaction writeOffDebt(String callerToken, String creditInstrument, double adjustmentAmount, Date transactionDate, String callerReference, String recipientReference, String senderReference, String senderDescription, String recipientDescription, String callerDescription, String metadata) throws FPSException { if (callerToken == null || callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (adjustmentAmount <= 0) throw new IllegalArgumentException("The adjustment amount should be a positive value"); if (logger.isInfoEnabled()) logger.info("Writing off debt instrument " + creditInstrument + " for an amount of " + adjustmentAmount); Map<String, String> params = new HashMap<String, String>(); params.put("CallerTokenId", callerToken); params.put("CreditInstrumentId", creditInstrument); params.put("AdjustmentAmount.Amount", Double.toString(adjustmentAmount)); params.put("AdjustmentAmount.CurrencyCode", "USD"); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); params.put("CallerReference", callerReference); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); GetMethod method = new GetMethod(); try { WriteOffDebtResponse response = makeRequestInt(method, "WriteOffDebt", params, WriteOffDebtResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } } /** * Get the current balance on your account. * * @return the balance * @throws FPSException wraps checked exceptions */ public AccountBalance getAccountBalance() throws FPSException { Map<String, String> params = new HashMap<String, String>(); GetMethod method = new GetMethod(); try { GetAccountBalanceResponse response = makeRequestInt(method, "GetAccountBalance", params, GetAccountBalanceResponse.class); com.xerox.amazonws.typica.fps.jaxb.AccountBalance balance = response.getAccountBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount available = balance.getTotalBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount pendingIn = balance.getPendingInBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount pendingOut = balance.getPendingOutBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount disburse = balance.getAvailableBalances().getDisburseBalance(); com.xerox.amazonws.typica.fps.jaxb.Amount refund = balance.getAvailableBalances().getRefundBalance(); return new AccountBalance( new Amount(new BigDecimal(available.getAmount()), available.getCurrencyCode().toString()), new Amount(new BigDecimal(pendingIn.getAmount()), pendingIn.getCurrencyCode().toString()), new Amount(new BigDecimal(pendingOut.getAmount()), pendingOut.getCurrencyCode().toString()), new Amount(new BigDecimal(disburse.getAmount()), disburse.getCurrencyCode().toString()), new Amount(new BigDecimal(refund.getAmount()), refund.getCurrencyCode().toString()) ); } finally { method.releaseConnection(); } } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireSingleUseToken(String callerReference, Amount amount, String returnURL, String reason) throws FPSException, MalformedURLException { return acquireSingleUseToken(callerReference, amount, false, null, null, false, true, null, null, null, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireSingleUseToken(String callerReference, Amount amount, PaymentMethod paymentMethod, String returnURL, String reason) throws FPSException, MalformedURLException { return acquireSingleUseToken(callerReference, amount, false, paymentMethod, null, false, true, null, null, null, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireSingleUseToken(String callerReference, Amount amount, boolean reserve, PaymentMethod paymentMethod, String recipientToken, Boolean isRecipientCobranding, Boolean collectShippingAddress, Address address, Amount itemTotal, Amount shipping, Amount handling, Boolean giftWrapping, Amount discount, Amount tax, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReference", callerReference); parameters.put("transactionAmount", amount.getAmount().toString()); parameters.put("currencyCode", amount.getCurrencyCode()); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (recipientToken != null) parameters.put("recipientToken", recipientToken); if (reason != null) parameters.put("paymentReason", reason); if (reserve) parameters.put("reserve", "True"); if (isRecipientCobranding != null) parameters.put("isRecipientCobranding", isRecipientCobranding.toString()); if (collectShippingAddress) parameters.put("collectShippingAddress", "True"); if (address != null) { parameters.put("addressName", address.getName()); parameters.put("addressLine1", address.getLine1()); parameters.put("addressLine2", address.getLine2()); parameters.put("city", address.getCity()); parameters.put("zip", address.getZipCode()); } if (itemTotal != null) parameters.put("itemTotal", itemTotal.getAmount().toString()); if (shipping != null) parameters.put("shipping", shipping.getAmount().toString()); if (handling != null) parameters.put("handling", handling.getAmount().toString()); if (discount != null) parameters.put("discount", discount.getAmount().toString()); if (tax != null) parameters.put("tax", tax.getAmount().toString()); if (giftWrapping != null) parameters.put("giftWrapping", "True"); return generateUIPipelineURL("SingleUse", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireMultiUseToken(String callerReference, Amount amount, Amount globalLimit, String returnURL, String reason) throws MalformedURLException, FPSException { return acquireMultiUseToken(callerReference, amount, null, null, globalLimit, null, null, null, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireMultiUseToken(String callerReference, Amount amount, List<String> recipientTokens, AmountType amountType, Amount globalLimit, List<UsageLimit> usageLimits, Boolean isRecipientCobranding, Boolean collectShippingAddress, Address address, Date validityStart, Date validityExpiry, PaymentMethod paymentMethod, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReference", callerReference); parameters.put("currencyCode", amount.getCurrencyCode()); parameters.put("transactionAmount", amount.getAmount().toString()); if (reason != null) parameters.put("paymentReason", reason); if (recipientTokens != null && recipientTokens.size() > 0) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < recipientTokens.size(); i++) { String token = recipientTokens.get(i); if (i > 0) buffer.append(','); buffer.append(token); } parameters.put("recipientTokenList", buffer.toString()); } if (amountType != null) parameters.put("amountType", amountType.value()); if (validityStart != null) parameters.put("validityStart", DataUtils.encodeDate(validityStart)); if (validityExpiry != null) parameters.put("validityExpiry", DataUtils.encodeDate(validityExpiry)); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (usageLimits != null) { for (int i = 0; i < usageLimits.size(); i++) { UsageLimit limit = usageLimits.get(i); parameters.put("usageLimitType" + i, limit.getType().value()); if (limit.getPeriodicity() != null) parameters.put("usageLimitPeriod" + i, limit.getPeriodicity().toString()); } } if (isRecipientCobranding != null) parameters.put("isRecipientCobranding", isRecipientCobranding.toString()); if (collectShippingAddress != null) parameters.put("collectShippingAddress", collectShippingAddress.toString()); if (address != null) { parameters.put("addressName", address.getName()); parameters.put("addressLine1", address.getLine1()); parameters.put("addressLine2", address.getLine2()); parameters.put("city", address.getCity()); parameters.put("zip", address.getZipCode()); } return generateUIPipelineURL("MultiUse", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireRecurringToken(String callerReference, Amount amount, int recurringInterval, RecurringGranularity recurringGranularity, String returnURL, String reason) throws MalformedURLException, FPSException { return acquireRecurringToken(callerReference, amount, recurringInterval, recurringGranularity, null, null, null, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireRecurringToken(String callerReference, Amount amount, int recurringInterval, RecurringGranularity recurringGranularity, Date validityStart, Date validityExpiry, PaymentMethod paymentMethod, String recipientToken, Boolean isRecipientCobranding, Boolean collectShippingAddress, Address address, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReference", callerReference); parameters.put("transactionAmount", amount.getAmount().toString()); parameters.put("currencyCode", amount.getCurrencyCode()); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (recipientToken != null) parameters.put("recipientToken", recipientToken); if (reason != null) parameters.put("paymentReason", reason); if (validityStart != null) parameters.put("validityStart", DataUtils.encodeDate(validityStart)); if (validityExpiry != null) parameters.put("validityExpiry", DataUtils.encodeDate(validityExpiry)); String recurringPeriod = Integer.toString(recurringInterval) + " " + recurringGranularity.getValue(); parameters.put("recurringPeriod", recurringPeriod); if (isRecipientCobranding != null) parameters.put("isRecipientCobranding", isRecipientCobranding.toString()); if (collectShippingAddress) parameters.put("collectShippingAddress", "True"); if (address != null) { parameters.put("addressName", address.getName()); parameters.put("addressLine1", address.getLine1()); parameters.put("addressLine2", address.getLine2()); parameters.put("city", address.getCity()); parameters.put("zip", address.getZipCode()); } return generateUIPipelineURL("Recurring", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireRecipientToken(String callerReference, Boolean recipientPaysFee, String returnURL, String reason) throws FPSException, MalformedURLException { return acquireRecipientToken(callerReference, null, null, null, recipientPaysFee, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireRecipientToken(String callerReference, Date validityStart, Date validityExpiry, PaymentMethod paymentMethod, Boolean recipientPaysFee, String callerReferenceRefund, Long maxVariableFee, Long maxFixedFee, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReference", callerReference); parameters.put("recipientPaysFee", recipientPaysFee ? "True" : "False"); if (validityStart != null) parameters.put("validityStart", DataUtils.encodeDate(validityStart)); if (validityExpiry != null) parameters.put("validityExpiry", DataUtils.encodeDate(validityExpiry)); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (callerReferenceRefund != null) parameters.put("callerReferenceRefund", callerReferenceRefund); if (maxVariableFee != null) parameters.put("maxVariableFee", maxVariableFee.toString()); if (maxFixedFee != null) parameters.put("maxFixedFee", maxFixedFee.toString()); return generateUIPipelineURL("Recipient", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquirePrepaidToken(String callerReferenceSender, String callerReferenceFunding, Amount amount, String returnURL, String reason) throws FPSException, MalformedURLException { return acquirePrepaidToken(callerReferenceSender, callerReferenceFunding, amount, null, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquirePrepaidToken(String callerReferenceSender, String callerReferenceFunding, Amount amount, PaymentMethod paymentMethod, Date validityStart, Date validityExpiry, Boolean collectShippingAddress, Address address, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReferenceSender", callerReferenceSender); parameters.put("callerReferenceFunding", callerReferenceFunding); parameters.put("currencyCode", amount.getCurrencyCode()); parameters.put("transactionAmount", amount.getAmount().toString()); if (reason != null) parameters.put("paymentReason", reason); if (validityStart != null) parameters.put("validityStart", DataUtils.encodeDate(validityStart)); if (validityExpiry != null) parameters.put("validityExpiry", DataUtils.encodeDate(validityExpiry)); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (collectShippingAddress != null) parameters.put("collectShippingAddress", collectShippingAddress.toString()); if (address != null) { parameters.put("addressName", address.getName()); parameters.put("addressLine1", address.getLine1()); parameters.put("addressLine2", address.getLine2()); parameters.put("city", address.getCity()); parameters.put("zip", address.getZipCode()); } return generateUIPipelineURL("SetupPrepaid", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquirePostPaidToken(String callerReferenceSender, String callerReferenceSettlement, Amount creditLimit, Amount globalAmountLimit, String returnURL, String reason) throws FPSException, MalformedURLException { return acquirePostPaidToken(callerReferenceSender, callerReferenceSettlement, null, null, creditLimit, globalAmountLimit, null, null, null, null, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquirePostPaidToken(String callerReferenceSender, String callerReferenceSettlement, Amount creditLimit, Amount globalAmountLimit, PaymentMethod paymentMethod, String returnURL, String reason) throws FPSException, MalformedURLException { return acquirePostPaidToken(callerReferenceSender, callerReferenceSettlement, null, null, creditLimit, globalAmountLimit, null, null, null, paymentMethod, returnURL, reason); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquirePostPaidToken(String callerReferenceSender, String callerReferenceSettlement, Date validityStart, Date validityExpiry, Amount creditLimit, Amount globalAmountLimit, List<UsageLimit> usageLimits, Boolean collectShippingAddress, Address address, PaymentMethod paymentMethod, String returnURL, String reason) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReferenceSender", callerReferenceSender); parameters.put("callerReferenceSettlement", callerReferenceSettlement); if (validityStart != null) parameters.put("validityStart", DataUtils.encodeDate(validityStart)); if (validityExpiry != null) parameters.put("validityExpiry", DataUtils.encodeDate(validityExpiry)); parameters.put("currencyCode", creditLimit.getCurrencyCode()); parameters.put("creditLimit", creditLimit.getAmount().toString()); parameters.put("globalAmountLimit", globalAmountLimit.getAmount().toString()); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); if (reason != null) parameters.put("paymentReason", reason); if (usageLimits != null) { for (int i = 0; i < usageLimits.size(); i++) { UsageLimit limit = usageLimits.get(i); parameters.put("usageLimitType" + i, limit.getType().value()); if (limit.getPeriodicity() != null) parameters.put("usageLimitPeriod" + i, limit.getPeriodicity().toString()); } } if (collectShippingAddress != null) parameters.put("collectShippingAddress", collectShippingAddress.toString()); if (address != null) { parameters.put("addressName", address.getName()); parameters.put("addressLine1", address.getLine1()); parameters.put("addressLine2", address.getLine2()); parameters.put("city", address.getCity()); parameters.put("zip", address.getZipCode()); } return generateUIPipelineURL("SetupPostpaid", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. */ public String acquireEditToken(String callerReference, String tokenID, PaymentMethod paymentMethod, String returnURL) throws FPSException, MalformedURLException { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("callerReference", callerReference); parameters.put("tokenID", tokenID); if (paymentMethod != null) parameters.put("paymentMethod", paymentMethod.value()); return generateUIPipelineURL("EditToken", returnURL, parameters); } /** * Generate a signed URL for the CBUI pipeline. * * @param pipelineName the name of the pipeline * @param returnURL the URL where the user should be redirected at the end of the pipeline * @param params all CBUI parameters * @return the signed URL * @throws MalformedURLException */ public String generateUIPipelineURL(String pipelineName, String returnURL, Map<String, String> params) throws MalformedURLException { // build the map of parameters SortedMap<String, String> parameters = new TreeMap<String, String>(params); parameters.put("callerKey", super.getAwsAccessKeyId()); parameters.put("pipelineName", pipelineName); parameters.put("returnURL", returnURL); // build the URL StringBuffer url = new StringBuffer(uiPipeline); boolean first = true; for (Map.Entry<String, String> parameter : parameters.entrySet()) { if (first) { url.append('?'); first = false; } else { url.append('&'); } url.append(urlencode(parameter.getKey())).append("=").append(urlencode(parameter.getValue())); } // calculate the signature URL rawURL = new URL(url.toString()); StringBuilder toBeSigned = new StringBuilder(rawURL.getPath()).append('?').append(rawURL.getQuery()); String signature = urlencode(encode(getSecretAccessKey(), toBeSigned.toString(), false)); url.append("&awsSignature=").append(signature); return url.toString(); } /** * Extract the single use token from the CBUI pipeline return. */ public SingleUseInstrument extractSingleUseTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); // extract expiry Date expiry = null; try { String expiryValue = request.getParameter("expiry"); if (expiryValue != null) expiry = DataUtils.decodeDate(expiryValue); } catch (ParseException e) { // do nothing -- this might happen! } return new SingleUseInstrument( request.getParameter("tokenID"), expiry, new Address( request.getParameter("addressName"), request.getParameter("addressLine1"), request.getParameter("addressLine2"), request.getParameter("city"), request.getParameter("state"), request.getParameter("zip") ) ); } /** * Extract the multi use token from the CBUI pipeline return. */ public MultiUseInstrument extractMultiUseTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); // extract expiry Date expiry = null; try { String expiryValue = request.getParameter("expiry"); if (expiryValue != null) expiry = DataUtils.decodeDate(expiryValue); } catch (ParseException e) { // do nothing -- this might happen! } return new MultiUseInstrument( request.getParameter("tokenID"), expiry, new Address( request.getParameter("addressName"), request.getParameter("addressLine1"), request.getParameter("addressLine2"), request.getParameter("city"), request.getParameter("state"), request.getParameter("zip") ) ); } /** * Extract the recurring token from the CBUI pipeline return. */ public RecurringInstrument extractRecurringTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); // extract expiry Date expiry = null; try { String expiryValue = request.getParameter("expiry"); if (expiryValue != null) expiry = DataUtils.decodeDate(expiryValue); } catch (ParseException e) { // do nothing -- this might happen! } return new RecurringInstrument( request.getParameter("tokenID"), expiry, new Address( request.getParameter("addressName"), request.getParameter("addressLine1"), request.getParameter("addressLine2"), request.getParameter("city"), request.getParameter("state"), request.getParameter("zip") ) ); } /** * Extract the recurring token from the CBUI pipeline return. */ public RecipientInstrument extractRecipientTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); return new RecipientInstrument( request.getParameter("tokenID"), request.getParameter("refundTokenID") ); } /** * Extract the recurring token from the CBUI pipeline return. */ public PrepaidInstrument extractPrepaidTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); // extract expiry Date expiry = null; try { String expiryValue = request.getParameter("expiry"); if (expiryValue != null) expiry = DataUtils.decodeDate(expiryValue); } catch (ParseException e) { // do nothing -- this might happen! } return new PrepaidInstrument( request.getParameter("prepaidInstrumentID"), request.getParameter("fundingTokenID"), request.getParameter("prepaidSenderTokenID"), expiry, new Address( request.getParameter("addressName"), request.getParameter("addressLine1"), request.getParameter("addressLine2"), request.getParameter("city"), request.getParameter("state"), request.getParameter("zip") ) ); } /** * Extract the post paid token from the CBUI pipeline return. * * @param request the HTTP request * @return the post paid token ID * @throws MalformedURLException * @throws FPSException */ public PostPaidInstrument extractPostPaidTokenFromCBUI(HttpServletRequest request) throws MalformedURLException, FPSException { // parse status message String status = request.getParameter("status"); String errorMessage = request.getParameter("errorMessage"); String requestID = request.getParameter("RequestId"); if ("SE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("A".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("CE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("PE".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NP".equals(status)) throw new FPSException(requestID, status, errorMessage); else if ("NM".equals(status)) throw new FPSException(requestID, status, errorMessage); if (logger.isDebugEnabled()) { logger.debug("Status: " + status); logger.debug("Error Message: " + errorMessage); } // ensure first that the request is valid if (!isSignatureValid(request)) throw new InvalidSignatureException(request.getParameter("awsSignature"), request.getRequestURI()); // extract expiry Date expiry = null; try { String expiryValue = request.getParameter("expiry"); if (expiryValue != null) expiry = DataUtils.decodeDate(expiryValue); } catch (ParseException e) { // do nothing -- this might happen! } return new PostPaidInstrument( request.getParameter("creditInstrumentID"), request.getParameter("creditSenderTokenID"), request.getParameter("settlementTokenID"), expiry, new Address( request.getParameter("addressName"), request.getParameter("addressLine1"), request.getParameter("addressLine2"), request.getParameter("city"), request.getParameter("state"), request.getParameter("zip") ) ); } @SuppressWarnings("unchecked") public boolean isSignatureValid(HttpServletRequest request) throws MalformedURLException { String signature = urlencode(request.getParameter("awsSignature")); if (signature == null) return false; List<String> parameters = new ArrayList(request.getParameterMap().keySet()); Collator stringCollator = Collator.getInstance(); stringCollator.setStrength(Collator.PRIMARY); Collections.sort(parameters, stringCollator); parameters.remove("awsSignature"); // build the URL to sign in order to ensure this is a valid signature we received StringBuffer url = new StringBuffer(request.getRequestURL()); boolean first = true; for (String parameter : parameters) { if (first) { url.append('?'); first = false; } else { url.append('&'); } url.append(urlencode(parameter)).append("=").append(urlencode(request.getParameter(parameter))); } // sign the URL URL rawURL = new URL(url.toString()); StringBuilder toBeSigned = new StringBuilder(rawURL.getPath()).append('?').append(rawURL.getQuery()); String ourSignature = urlencode(encode(getSecretAccessKey(), toBeSigned.toString(), false)); ourSignature = ourSignature.replaceAll("%2B", "+"); if (logger.isDebugEnabled()) { logger.debug("AWS sig: " + signature); logger.debug("Our sig: " + ourSignature); } return ourSignature.equals(signature); } protected <T> T makeRequestInt(HttpMethodBase method, String action, Map<String, String> params, Class<T> respType) throws FPSException { try { T response = makeRequest(method, action, params, respType); Class responseClass = response.getClass(); ResponseStatus status = (ResponseStatus) responseClass.getMethod("getStatus").invoke(response); if (ResponseStatus.FAILURE.equals(status)) { String requestID = (String) responseClass.getMethod("getRequestId").invoke(response); ServiceErrors rawErrors = (ServiceErrors) responseClass.getMethod("getErrors").invoke(response); List<FPSError> errors = new ArrayList<FPSError>(rawErrors.getErrors().size()); for (ServiceError error : rawErrors.getErrors()) { AWSError.ErrorType type = null; switch (error.getErrorType()) { case BUSINESS: type = AWSError.ErrorType.SENDER; break; case SYSTEM: type = AWSError.ErrorType.RECEIVER; break; } errors.add(new FPSError(type, error.getErrorCode(), error.getReasonText(), error.isIsRetriable())); } throw new FPSException(requestID, errors); } return response; } catch (AWSException ex) { throw new FPSException(ex); } catch (JAXBException ex) { throw new FPSException("Problem parsing returned message.", ex); } catch (HttpException ex) { throw new FPSException(ex.getMessage(), ex); } catch (IOException ex) { throw new FPSException(ex.getMessage(), ex); } catch (InvocationTargetException ex) { throw new FPSException(ex.getMessage(), ex); } catch (NoSuchMethodException ex) { throw new FPSException(ex.getMessage(), ex); } catch (IllegalAccessException ex) { throw new FPSException(ex.getMessage(), ex); } } static void setVersionHeader(AWSQueryConnection connection) { List<String> vals = new ArrayList<String>(); vals.add("2007-01-08"); connection.getHeaders().put("Version", vals); } }
true
true
public Transaction pay(String recipientToken, String senderToken, String callerToken, Amount amount, Date transactionDate, ChargeFeeTo chargeFeeTo, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, double marketplaceFixedFee, int marketplaceVariableFee, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (recipientToken != null && recipientToken.length() != 64) throw new IllegalArgumentException("The recipient token must have a length of 64 bytes"); if (senderToken != null && senderToken.length() != 64) throw new IllegalArgumentException("The sender token must have a length of 64 bytes"); if (callerToken != null && callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (logger.isInfoEnabled()) logger.info("Payment: " + senderToken + " paying " + recipientToken + " for " + amount); Map<String, String> params = new HashMap<String, String>(); if (recipientToken != null) params.put("RecipientTokenId", recipientToken); params.put("SenderTokenId", senderToken); params.put("CallerTokenId", callerToken); params.put("TransactionAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("TransactionAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); params.put("ChargeFeeTo", chargeFeeTo.value()); params.put("CallerReference", callerReference); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (marketplaceFixedFee != 0) params.put("MarketplaceFixedFee", Double.toString(marketplaceFixedFee)); if (marketplaceVariableFee != 0) params.put("MarketplaceVariableFee", Integer.toString(marketplaceVariableFee)); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); params.put("ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { PayResponse response = makeRequestInt(method, "Pay", params, PayResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } }
public Transaction pay(String recipientToken, String senderToken, String callerToken, Amount amount, Date transactionDate, ChargeFeeTo chargeFeeTo, String callerReference, String senderReference, String recipientReference, String senderDescription, String recipientDescription, String callerDescription, String metadata, double marketplaceFixedFee, int marketplaceVariableFee, DescriptorPolicy descriptorPolicy, TemporaryDeclinePolicy tempDeclinePolicy) throws FPSException { if (recipientToken != null && recipientToken.length() != 64) throw new IllegalArgumentException("The recipient token must have a length of 64 bytes"); if (senderToken != null && senderToken.length() != 64) throw new IllegalArgumentException("The sender token must have a length of 64 bytes"); if (callerToken != null && callerToken.length() != 64) throw new IllegalArgumentException("The caller token must have a length of 64 bytes"); if (logger.isInfoEnabled()) logger.info("Payment: " + senderToken + " paying " + recipientToken + " for " + amount); Map<String, String> params = new HashMap<String, String>(); if (recipientToken != null) params.put("RecipientTokenId", recipientToken); params.put("SenderTokenId", senderToken); params.put("CallerTokenId", callerToken); params.put("TransactionAmount.Amount", Double.toString(amount.getAmount().doubleValue())); params.put("TransactionAmount.CurrencyCode", amount.getCurrencyCode()); if (transactionDate != null) params.put("TransactionDate", DataUtils.encodeDate(transactionDate)); params.put("ChargeFeeTo", chargeFeeTo.value()); params.put("CallerReference", callerReference); if (senderReference != null) params.put("SenderReference", senderReference); if (recipientReference != null) params.put("RecipientReference", recipientReference); if (senderDescription != null) params.put("SenderDescription", senderDescription); if (recipientDescription != null) params.put("RecipientDescription", recipientDescription); if (callerDescription != null) params.put("CallerDescription", callerDescription); if (metadata != null) params.put("MetaData", metadata); if (marketplaceFixedFee != 0) params.put("MarketplaceFixedFee", Double.toString(marketplaceFixedFee)); if (marketplaceVariableFee != 0) params.put("MarketplaceVariableFee", Integer.toString(marketplaceVariableFee)); if (descriptorPolicy != null) { params.put("SoftDescriptorType", descriptorPolicy.getSoftDescriptorType().value()); params.put("CSNumberOf", descriptorPolicy.getCSNumberOf().value()); } if (tempDeclinePolicy != null) { params.put("TemporaryDeclinePolicy.TemporaryDeclinePolicyType", tempDeclinePolicy.getTemporaryDeclinePolicyType().value()); params.put("TemporaryDeclinePolicy.ImplicitRetryTimeoutInMins", Integer.toString(tempDeclinePolicy.getImplicitRetryTimeoutInMins())); } GetMethod method = new GetMethod(); try { PayResponse response = makeRequestInt(method, "Pay", params, PayResponse.class); TransactionResponse transactionResponse = response.getTransactionResponse(); return new Transaction( transactionResponse.getTransactionId(), Transaction.Status.fromValue(transactionResponse.getStatus().value()), transactionResponse.getStatusDetail() // todo: transactionResponse.getNewSenderTokenUsage() ); } finally { method.releaseConnection(); } }
diff --git a/src/com/qualcomm/QCARSamples/ImageTargets/GUIManager.java b/src/com/qualcomm/QCARSamples/ImageTargets/GUIManager.java index 77e7955..9ae5e4c 100644 --- a/src/com/qualcomm/QCARSamples/ImageTargets/GUIManager.java +++ b/src/com/qualcomm/QCARSamples/ImageTargets/GUIManager.java @@ -1,374 +1,374 @@ /*============================================================================== Copyright (c) 2010-2011 QUALCOMM Incorporated. All Rights Reserved. Qualcomm Confidential and Proprietary ==============================================================================*/ package com.qualcomm.QCARSamples.ImageTargets; import android.app.Activity; import android.content.Context; import android.graphics.LightingColorFilter; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class GUIManager extends Activity{ // Custom views private View overlayView; private Button pauseButton; private Button unpauseButton; private Button startButton; private Button deleteButton; private Button storeButton; private Button statsButton; private Button upgradeButton; private Button creditsButton; private TextView currentLevel; private TextView currentScore; private TextView currentZen; // The main application context private Context applicationContext; // A Handler for working with the gui from other threads private Handler mainActivityHandler; // Flags for our Handler public static final int SHOW_DELETE_BUTTON = 0; public static final int HIDE_DELETE_BUTTON = 1; public static final int TOGGLE_PAUSE_BUTTON = 2; public static final int SHOW_PAUSE_BUTTON = 3; public static final int HIDE_PAUSE_BUTTON = 4; public static final int SHOW_UNPAUSE_BUTTON = 5; public static final int HIDE_UNPAUSE_BUTTON = 6; public static final int TOGGLE_STORE_BUTTON = 7; public static final int SHOW_STORE_BUTTON = 8; public static final int HIDE_STORE_BUTTON = 9; public static final int SHOW_UPGRADE_BUTTON = 10; public static final int HIDE_UPGRADE_BUTTON = 11; public static final int SHOW_STATS_BUTTON = 12; public static final int HIDE_STATS_BUTTON = 13; public static final int SHOW_CREDITS_BUTTON = 14; public static final int HIDE_CREDITS_BUTTON = 15; public static final int HIDE_START_BUTTON = 16; public static final int DISPLAY_INFO_TOAST = 100; // Native methods to handle button clicks public native void nativePause(); public native void nativeStart(); public native void nativeStore(); public native void nativeLeave(); public native void nativeUnpause(); public native void nativeDelete(); public native void nativeUpgrade(); public native void nativeStats(); public native void nativeCredits(); /** Initialize the GUIManager. */ public GUIManager(Context context) { // Load our overlay view // This view will add content on top of the camera / opengl view overlayView = View.inflate(context, R.layout.interface_overlay, null); // Store the application context applicationContext = context; // Create a Handler from the current thread // This is the only thread that can make changes to the GUI, // so we require a handler for other threads to make changes mainActivityHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_DELETE_BUTTON: if (deleteButton != null) { //deleteButton.setVisibility(View.VISIBLE); deleteButton.setEnabled(true); } break; case HIDE_DELETE_BUTTON: if (deleteButton != null) { deleteButton.setVisibility(View.INVISIBLE); deleteButton.setEnabled(false); } break; case TOGGLE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setChecked(true); } break; case SHOW_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.VISIBLE); - pauseButton.setEnabled(false); + pauseButton.setEnabled(true); } break; case HIDE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.INVISIBLE); pauseButton.setEnabled(false); } break; case SHOW_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.VISIBLE); unpauseButton.setEnabled(true); } break; case HIDE_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.INVISIBLE); unpauseButton.setEnabled(false); } break; case TOGGLE_STORE_BUTTON: if (storeButton != null) { //storeButton.setChecked(true); } break; case SHOW_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.VISIBLE); storeButton.setEnabled(true); } break; case HIDE_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.INVISIBLE); storeButton.setEnabled(false); } break; case SHOW_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.VISIBLE); upgradeButton.setEnabled(true); } break; case HIDE_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.INVISIBLE); upgradeButton.setEnabled(false); } break; case SHOW_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.VISIBLE); } break; case HIDE_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.INVISIBLE); } break; case SHOW_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.VISIBLE); creditsButton.setEnabled(true); } break; case HIDE_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.INVISIBLE); creditsButton.setEnabled(false); } break; case HIDE_START_BUTTON: if (startButton != null) { //startButton.setVisibility(View.INVISIBLE); startButton.setEnabled(false); } break; case DISPLAY_INFO_TOAST: String text = (String) msg.obj; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(applicationContext, text, duration); toast.show(); break; } } }; } /** Button clicks should call corresponding native functions. */ public void initButtons() { if (overlayView == null) return; pauseButton = (Button) overlayView.findViewById(R.id.pause_button); pauseButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000)); unpauseButton = (Button) overlayView.findViewById(R.id.unpause_button); unpauseButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAA0000)); unpauseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { nativeUnpause(); } }); storeButton = (Button) overlayView.findViewById(R.id.store_button); storeButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFF00AA00)); startButton = (Button) overlayView.findViewById(R.id.start_button); startButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFF00AA00)); startButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { pauseButton.setVisibility(View.VISIBLE); nativeStart(); newLevel(String.valueOf(1)); } }); deleteButton = (Button) overlayView.findViewById(R.id.delete_button); deleteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { nativeDelete(); } }); upgradeButton = (Button) overlayView.findViewById(R.id.upgrade_button); upgradeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { nativeUpgrade(); } }); /*statsButton = (Button) overlayView.findViewById(R.id.stats_button); statsButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFF0000AA)); statsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { nativeStats(); } });*/ creditsButton = (Button) overlayView.findViewById(R.id.credits_button); creditsButton.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFAAAA00)); creditsButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { nativeCredits(); } }); pauseButton.setEnabled(false); unpauseButton.setEnabled(false); deleteButton.setEnabled(false); upgradeButton.setEnabled(false); storeButton.setEnabled(false); currentLevel = (TextView) overlayView.findViewById(R.id.current_level); currentLevel.setText("Game Setup!"); currentScore = (TextView) overlayView.findViewById(R.id.current_score); currentScore.setText(String.valueOf(0)); currentZen = (TextView) overlayView.findViewById(R.id.current_zen); currentZen.setText(String.valueOf(5)); } /** Clear the button listeners. */ public void deinitButtons() { if (overlayView == null) return; pauseButton.setOnClickListener(null); startButton.setOnClickListener(null); deleteButton.setOnClickListener(null); storeButton.setOnClickListener(null); pauseButton = null; startButton = null; deleteButton = null; storeButton = null; } /** Send a message to our gui thread handler. */ public void sendThreadSafeGUIMessage(Message message) { mainActivityHandler.sendMessage(message); } public void newScore(String score) { //SCREW YOU FINAL FOR WASTING HOURS final String temp = score; //extended activity. Hopefully not too much overhead? runOnUiThread(new Runnable() { public void run() { currentScore.setText(temp); } }); } public void newZen(String zen) { final String temp = zen; //extended activity. Hopefully not too much overhead? runOnUiThread(new Runnable() { public void run() { currentZen.setText(temp); } }); } public void newLevel(String level) { final String temp = level; //extended activity. Hopefully not too much overhead? runOnUiThread(new Runnable() { public void run() { currentLevel.setText(temp); } }); } public void updateEOL(String level) { //updateApplicationStatus(APPSTATUS_INIT_EOL); /* final String temp = level; //extended activity. Hopefully not too much overhead? runOnUiThread(new Runnable() { public void run() { //currentLevel = (TextView) mGUIManager.getOverlayView().findViewById(R.id.current_level); //currentLevel.setText(temp); } });*/ } /** Getter for the overlay view. */ public View getOverlayView() { return overlayView; } }
true
true
public GUIManager(Context context) { // Load our overlay view // This view will add content on top of the camera / opengl view overlayView = View.inflate(context, R.layout.interface_overlay, null); // Store the application context applicationContext = context; // Create a Handler from the current thread // This is the only thread that can make changes to the GUI, // so we require a handler for other threads to make changes mainActivityHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_DELETE_BUTTON: if (deleteButton != null) { //deleteButton.setVisibility(View.VISIBLE); deleteButton.setEnabled(true); } break; case HIDE_DELETE_BUTTON: if (deleteButton != null) { deleteButton.setVisibility(View.INVISIBLE); deleteButton.setEnabled(false); } break; case TOGGLE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setChecked(true); } break; case SHOW_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.VISIBLE); pauseButton.setEnabled(false); } break; case HIDE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.INVISIBLE); pauseButton.setEnabled(false); } break; case SHOW_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.VISIBLE); unpauseButton.setEnabled(true); } break; case HIDE_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.INVISIBLE); unpauseButton.setEnabled(false); } break; case TOGGLE_STORE_BUTTON: if (storeButton != null) { //storeButton.setChecked(true); } break; case SHOW_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.VISIBLE); storeButton.setEnabled(true); } break; case HIDE_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.INVISIBLE); storeButton.setEnabled(false); } break; case SHOW_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.VISIBLE); upgradeButton.setEnabled(true); } break; case HIDE_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.INVISIBLE); upgradeButton.setEnabled(false); } break; case SHOW_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.VISIBLE); } break; case HIDE_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.INVISIBLE); } break; case SHOW_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.VISIBLE); creditsButton.setEnabled(true); } break; case HIDE_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.INVISIBLE); creditsButton.setEnabled(false); } break; case HIDE_START_BUTTON: if (startButton != null) { //startButton.setVisibility(View.INVISIBLE); startButton.setEnabled(false); } break; case DISPLAY_INFO_TOAST: String text = (String) msg.obj; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(applicationContext, text, duration); toast.show(); break; } } }; }
public GUIManager(Context context) { // Load our overlay view // This view will add content on top of the camera / opengl view overlayView = View.inflate(context, R.layout.interface_overlay, null); // Store the application context applicationContext = context; // Create a Handler from the current thread // This is the only thread that can make changes to the GUI, // so we require a handler for other threads to make changes mainActivityHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_DELETE_BUTTON: if (deleteButton != null) { //deleteButton.setVisibility(View.VISIBLE); deleteButton.setEnabled(true); } break; case HIDE_DELETE_BUTTON: if (deleteButton != null) { deleteButton.setVisibility(View.INVISIBLE); deleteButton.setEnabled(false); } break; case TOGGLE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setChecked(true); } break; case SHOW_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.VISIBLE); pauseButton.setEnabled(true); } break; case HIDE_PAUSE_BUTTON: if (pauseButton != null) { //pauseButton.setVisibility(View.INVISIBLE); pauseButton.setEnabled(false); } break; case SHOW_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.VISIBLE); unpauseButton.setEnabled(true); } break; case HIDE_UNPAUSE_BUTTON: if (unpauseButton != null) { //unpauseButton.setVisibility(View.INVISIBLE); unpauseButton.setEnabled(false); } break; case TOGGLE_STORE_BUTTON: if (storeButton != null) { //storeButton.setChecked(true); } break; case SHOW_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.VISIBLE); storeButton.setEnabled(true); } break; case HIDE_STORE_BUTTON: if (storeButton != null) { //storeButton.setVisibility(View.INVISIBLE); storeButton.setEnabled(false); } break; case SHOW_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.VISIBLE); upgradeButton.setEnabled(true); } break; case HIDE_UPGRADE_BUTTON: if (upgradeButton != null) { //upgradeButton.setVisibility(View.INVISIBLE); upgradeButton.setEnabled(false); } break; case SHOW_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.VISIBLE); } break; case HIDE_STATS_BUTTON: if (statsButton != null) { //statsButton.setVisibility(View.INVISIBLE); } break; case SHOW_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.VISIBLE); creditsButton.setEnabled(true); } break; case HIDE_CREDITS_BUTTON: if (creditsButton != null) { //creditsButton.setVisibility(View.INVISIBLE); creditsButton.setEnabled(false); } break; case HIDE_START_BUTTON: if (startButton != null) { //startButton.setVisibility(View.INVISIBLE); startButton.setEnabled(false); } break; case DISPLAY_INFO_TOAST: String text = (String) msg.obj; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(applicationContext, text, duration); toast.show(); break; } } }; }
diff --git a/src/x/util/BitmapUtils.java b/src/x/util/BitmapUtils.java index a094ac8..9772bf1 100644 --- a/src/x/util/BitmapUtils.java +++ b/src/x/util/BitmapUtils.java @@ -1,203 +1,210 @@ package x.util; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.media.ExifInterface; /** * @Brief Utilities for bitmap processing */ public class BitmapUtils { public static int FLIP_HORIZONTAL = 0x01; public static int FLIP_VERTICAL = 0x10; /** * Resizes a bitmap. Original bitmap is recycled after this method is called. * @param bm The bitmap to resize * @param width The new width * @param height Thew new height * @return The resized bitmap */ public static Bitmap resize(Bitmap bm, int width, int height) { Bitmap newBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); canvas.drawBitmap(bm, new Rect(0, 0, bm.getWidth(), bm.getHeight()), new Rect(0, 0, width, height), new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG)); bm.recycle(); return newBitmap; } /** * Resizes a bitmap to a specific width, maintaining the ratio. Original bitmap is recycled after this method is called. * @param bm The bitmap to resize * @param width The new width * @return The resized bitmap */ public static Bitmap resizeToWidth(Bitmap bm, int width) { // Calculate the new height float ratio = (float)width / (float)bm.getWidth(); int height = (int)((float)bm.getHeight() * ratio); return BitmapUtils.resize(bm, width, height); } /** * Resizes a bitmap to a specific height, maintaining the ratio. Original bitmap is recycled after this method is called. * @param bm The bitmap to resize * @param height The new width * @return The resized bitmap */ public static Bitmap resizeToHeight(Bitmap bm, int height) { // Calculate the new width float ratio = (float)height / (float)bm.getHeight(); int width = (int)((float)bm.getWidth() * ratio); return BitmapUtils.resize(bm, width, height); } /** * Resizes a bitmap to a which ever axis is the largest, maintaining the ratio. Original bitmap is recycled after this method is called. * @param bm The bitmap to resize * @param maxWidth The max width size * @param maxHeight The max height size * @return The resized bitmap */ public static Bitmap maxResize(Bitmap bm, int maxWidth, int maxHeight) { // Calculate what is larger width or height if (bm.getWidth() > bm.getHeight()) { return BitmapUtils.resizeToWidth(bm, maxWidth); } else { return BitmapUtils.resizeToHeight(bm, maxHeight); } } /** * Compresses a bitmap. original bitmap is recycled after this method is called. * @param bm The bitmap to be compressed. * @param compression The compression ratio 0-100. * @return The compressed bitmap. */ public static Bitmap compress(Bitmap bm, int compression) { ByteArrayOutputStream bitmapOutputStream = new ByteArrayOutputStream(); bm.compress(CompressFormat.JPEG, compression, bitmapOutputStream); bm.recycle(); return BitmapFactory.decodeByteArray(bitmapOutputStream.toByteArray(), 0, bitmapOutputStream.size()); } /** * Rotates a bitmap. Original bitmap is recycled after this method is called. * @param bm The bitmap to rotate * @param degrees The degrees to rotate at. 0-360 clockwise. * @return The rotated bitmap */ public static Bitmap rotate(Bitmap bm, int degrees) { Matrix rotateMatrix = new Matrix(); rotateMatrix.setRotate((float)degrees); Bitmap newBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), rotateMatrix, true); bm.recycle(); return newBitmap; } /** * Flips an image * @param bm The image to flip. Original bitmap is recycled after this method is called. * @param mode The mode to flip * @return The flipped bitmap */ public static Bitmap flip(Bitmap bm, int mode) { Bitmap newBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); Matrix flipMatrix = new Matrix(); float xFlip = 1.0f, yFlip = 1.0f; if ((mode & FLIP_HORIZONTAL) == mode) { xFlip = -1.0f; } if ((mode & FLIP_VERTICAL) == mode) { yFlip = -1.0f; } flipMatrix.preScale(xFlip, yFlip); canvas.drawBitmap(bm, flipMatrix, new Paint()); bm.recycle(); return newBitmap; } /** * Fixes the orientation of a bitmap * @param bm The bitmap to fix * @param currentOrientation The current orientation as discripted in {@link ExifInterface} * @return The fixed bitmap */ public static Bitmap fixOrientation(Bitmap bm, int currentOrientation) { switch (currentOrientation) { - case 2: // Horizontal + // Horizontal + case 2: { return flip(bm, FLIP_HORIZONTAL); } - case 3: // 180 rotate left + // 180 rotate left + case 3: { return rotate(bm, -180); } - case 4: // Vertical flip + // Vertical flip + case 4: { return flip(bm, FLIP_VERTICAL); } - case 5: // Vertical flip + 90 rotate right + // Vertical flip + 90 rotate right + case 5: { return rotate(flip(bm, FLIP_VERTICAL), 90); } - case 6: // 90 rotate right + // 90 rotate right + case 6: { return rotate(bm, 90); } - case 7: // horizontal flip + 90 rotate right + // horizontal flip + 90 rotate right + case 7: { return rotate(flip(bm, FLIP_HORIZONTAL), 90); } - case 8: // 90 rotate left + // 90 rotate left + case 8: { return rotate(bm, 90); } } return bm; } }
false
true
public static Bitmap fixOrientation(Bitmap bm, int currentOrientation) { switch (currentOrientation) { case 2: // Horizontal { return flip(bm, FLIP_HORIZONTAL); } case 3: // 180 rotate left { return rotate(bm, -180); } case 4: // Vertical flip { return flip(bm, FLIP_VERTICAL); } case 5: // Vertical flip + 90 rotate right { return rotate(flip(bm, FLIP_VERTICAL), 90); } case 6: // 90 rotate right { return rotate(bm, 90); } case 7: // horizontal flip + 90 rotate right { return rotate(flip(bm, FLIP_HORIZONTAL), 90); } case 8: // 90 rotate left { return rotate(bm, 90); } } return bm; }
public static Bitmap fixOrientation(Bitmap bm, int currentOrientation) { switch (currentOrientation) { // Horizontal case 2: { return flip(bm, FLIP_HORIZONTAL); } // 180 rotate left case 3: { return rotate(bm, -180); } // Vertical flip case 4: { return flip(bm, FLIP_VERTICAL); } // Vertical flip + 90 rotate right case 5: { return rotate(flip(bm, FLIP_VERTICAL), 90); } // 90 rotate right case 6: { return rotate(bm, 90); } // horizontal flip + 90 rotate right case 7: { return rotate(flip(bm, FLIP_HORIZONTAL), 90); } // 90 rotate left case 8: { return rotate(bm, 90); } } return bm; }
diff --git a/src/org/newdawn/slick/BigImage.java b/src/org/newdawn/slick/BigImage.java index 21676a3..f037261 100644 --- a/src/org/newdawn/slick/BigImage.java +++ b/src/org/newdawn/slick/BigImage.java @@ -1,768 +1,768 @@ package org.newdawn.slick; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import org.newdawn.slick.opengl.ImageData; import org.newdawn.slick.opengl.ImageDataFactory; import org.newdawn.slick.opengl.LoadableImageData; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.renderer.SGL; import org.newdawn.slick.opengl.renderer.Renderer; import org.newdawn.slick.util.OperationNotSupportedException; import org.newdawn.slick.util.ResourceLoader; /** * An image implementation that handles loaded images that are larger than the * maximum texture size supported by the card. In most cases it makes sense * to make sure all of your image resources are less than 512x512 in size when * using OpenGL. However, in the rare circumstances where this isn't possible * this implementation can be used to draw a tiled version of the image built * from several smaller textures. * * This implementation does come with limitations and some performance impact * however - so use only when absolutely required. * * TODO: The code in here isn't pretty, really needs revisiting with a comment stick. * * @author kevin */ public class BigImage extends Image { /** The renderer to use for all GL operations */ protected static SGL GL = Renderer.get(); /** * Get the maximum size of an image supported by the underlying * hardware. * * @return The maximum size of the textures supported by the underlying * hardware. */ public static final int getMaxSingleImageSize() { IntBuffer buffer = BufferUtils.createIntBuffer(16); GL.glGetInteger(SGL.GL_MAX_TEXTURE_SIZE, buffer); return buffer.get(0); } /** The last image that we put into "in use" mode */ private static Image lastBind; /** The images building up this sub-image */ private Image[][] images; /** The number of images on the xaxis */ private int xcount; /** The number of images on the yaxis */ private int ycount; /** The real width of the whole image - maintained even when scaled */ private int realWidth; /** The real hieght of the whole image - maintained even when scaled */ private int realHeight; /** * Create a new big image. Empty contructor for cloning only */ private BigImage() { inited = true; } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref) throws SlickException { this(ref, Image.FILTER_NEAREST); } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref,int filter) throws SlickException { build(ref, filter, getMaxSingleImageSize()); } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image * @throws SlickException Indicates we were unable to locate the resource */ public BigImage(String ref, int filter, int tileSize) throws SlickException { build(ref, filter, tileSize); } /** * Create a new big image by loading it from the specified image data * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) */ public BigImage(LoadableImageData data, ByteBuffer imageBuffer, int filter) { build(data, imageBuffer, filter, getMaxSingleImageSize()); } /** * Create a new big image by loading it from the specified image data * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image */ public BigImage(LoadableImageData data, ByteBuffer imageBuffer, int filter, int tileSize) { build(data, imageBuffer, filter, tileSize); } /** * Get a sub tile of this big image. Useful for debugging * * @param x The x tile index * @param y The y tile index * @return The image used for this tile */ public Image getTile(int x, int y) { return images[x][y]; } /** * Create a new big image by loading it from the specified reference * * @param ref The reference to the image to load * @param filter The image filter to apply (@see #Image.FILTER_NEAREST) * @param tileSize The maximum size of the tiles to use to build the bigger image * @throws SlickException Indicates we were unable to locate the resource */ private void build(String ref, int filter, int tileSize) throws SlickException { try { final LoadableImageData data = ImageDataFactory.getImageDataFor(ref); final ByteBuffer imageBuffer = data.loadImage(ResourceLoader.getResourceAsStream(ref), false, null); build(data, imageBuffer, filter, tileSize); } catch (IOException e) { throw new SlickException("Failed to load: "+ref, e); } } /** * Create an big image from a image data source. * * @param data The pixelData to use to create the image * @param imageBuffer The buffer containing texture data * @param filter The filter to use when scaling this image * @param tileSize The maximum size of the tiles to use to build the bigger image */ private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); - final int imageWidth = tileSize; - final int imageHeight = tileSize; + final int imageWidth = Math.min((realWidth - (x*tileSize)), tileSize); + final int imageHeight = Math.min((realHeight - (y*tileSize)), tileSize); - final int xSize = Math.min(dataWidth, imageWidth); - final int ySize = Math.min(dataHeight, imageHeight); + final int xSize = tileSize; + final int ySize = tileSize; final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { - int yo = (((y * (imageWidth < tileSize ? imageWidth : tileSize)) + i) * dataWidth) * components; + int yo = (((y * tileSize) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#bind() */ public void bind() { throw new OperationNotSupportedException("Can't bind big images yet"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#copy() */ public Image copy() { throw new OperationNotSupportedException("Can't copy big images yet"); } /** * @see org.newdawn.slick.Image#draw() */ public void draw() { draw(0,0); } /** * @see org.newdawn.slick.Image#draw(float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, Color filter) { draw(x,y,width,height,filter); } /** * @see org.newdawn.slick.Image#draw(float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float scale, Color filter) { draw(x,y,width*scale,height*scale,filter); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float width, float height, Color filter) { float sx = width / realWidth; float sy = height / realHeight; GL.glTranslatef(x,y,0); GL.glScalef(sx,sy,1); float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.draw(xp,yp,image.getWidth(), image.getHeight(), filter); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } GL.glScalef(1.0f/sx,1.0f/sy,1); GL.glTranslatef(-x,-y,0); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float, float, float) */ public void draw(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); Image subImage = getSubImage((int) srcx,(int) srcy,srcwidth,srcheight); int width = (int) (x2 - x); int height = (int) (y2 - y); subImage.draw(x,y,width,height); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float) */ public void draw(float x, float y, float srcx, float srcy, float srcx2, float srcy2) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); draw(x,y,srcwidth,srcheight,srcx,srcy,srcx2,srcy2); } /** * @see org.newdawn.slick.Image#draw(float, float, float, float) */ public void draw(float x, float y, float width, float height) { draw(x,y,width,height,Color.white); } /** * @see org.newdawn.slick.Image#draw(float, float, float) */ public void draw(float x, float y, float scale) { draw(x,y,scale,Color.white); } /** * @see org.newdawn.slick.Image#draw(float, float) */ public void draw(float x, float y) { draw(x,y,Color.white); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float) */ public void drawEmbedded(float x, float y, float width, float height) { float sx = width / realWidth; float sy = height / realHeight; float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; if ((lastBind == null) || (image.getTexture() != lastBind.getTexture())) { if (lastBind != null) { lastBind.endUse(); } lastBind = image; lastBind.startUse(); } image.drawEmbedded(xp+x,yp+y,image.getWidth(), image.getHeight()); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } } /** * @see org.newdawn.slick.Image#drawFlash(float, float, float, float) */ public void drawFlash(float x, float y, float width, float height) { float sx = width / realWidth; float sy = height / realHeight; GL.glTranslatef(x,y,0); GL.glScalef(sx,sy,1); float xp = 0; float yp = 0; for (int tx=0;tx<xcount;tx++) { yp = 0; for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.drawFlash(xp,yp,image.getWidth(), image.getHeight()); yp += image.getHeight(); if (ty == ycount - 1) { xp += image.getWidth(); } } } GL.glScalef(1.0f/sx,1.0f/sy,1); GL.glTranslatef(-x,-y,0); } /** * @see org.newdawn.slick.Image#drawFlash(float, float) */ public void drawFlash(float x, float y) { drawFlash(x,y,width,height); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#endUse() */ public void endUse() { if (lastBind != null) { lastBind.endUse(); } lastBind = null; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#startUse() */ public void startUse() { } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#ensureInverted() */ public void ensureInverted() { throw new OperationNotSupportedException("Doesn't make sense for tiled operations"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getColor(int, int) */ public Color getColor(int x, int y) { throw new OperationNotSupportedException("Can't use big images as buffers"); } /** * @see org.newdawn.slick.Image#getFlippedCopy(boolean, boolean) */ public Image getFlippedCopy(boolean flipHorizontal, boolean flipVertical) { BigImage image = new BigImage(); image.images = images; image.xcount = xcount; image.ycount = ycount; image.width = width; image.height = height; image.realWidth = realWidth; image.realHeight = realHeight; if (flipHorizontal) { Image[][] images = image.images; image.images = new Image[xcount][ycount]; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { image.images[x][y] = images[xcount-1-x][y].getFlippedCopy(true, false); } } } if (flipVertical) { Image[][] images = image.images; image.images = new Image[xcount][ycount]; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { image.images[x][y] = images[x][ycount-1-y].getFlippedCopy(false, true); } } } return image; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getGraphics() */ public Graphics getGraphics() throws SlickException { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#getScaledCopy(float) */ public Image getScaledCopy(float scale) { return getScaledCopy((int) (scale * width), (int) (scale * height)); } /** * @see org.newdawn.slick.Image#getScaledCopy(int, int) */ public Image getScaledCopy(int width, int height) { BigImage image = new BigImage(); image.images = images; image.xcount = xcount; image.ycount = ycount; image.width = width; image.height = height; image.realWidth = realWidth; image.realHeight = realHeight; return image; } /** * @see org.newdawn.slick.Image#getSubImage(int, int, int, int) */ public Image getSubImage(int x, int y, int width, int height) { BigImage image = new BigImage(); image.width = width; image.height = height; image.realWidth = width; image.realHeight = height; image.images = new Image[this.xcount][this.ycount]; float xp = 0; float yp = 0; int x2 = x+width; int y2 = y+height; int startx = 0; int starty = 0; boolean foundStart = false; for (int xt=0;xt<xcount;xt++) { yp = 0; starty = 0; foundStart = false; for (int yt=0;yt<ycount;yt++) { Image current = images[xt][yt]; int xp2 = (int) (xp + current.getWidth()); int yp2 = (int) (yp + current.getHeight()); // if the top corner of the subimage is inside the area // we want or the bottom corrent of the image is, then consider using the // image // this image contributes to the sub image we're attempt to retrieve int targetX1 = (int) Math.max(x, xp); int targetY1 = (int) Math.max(y, yp); int targetX2 = Math.min(x2, xp2); int targetY2 = Math.min(y2, yp2); int targetWidth = targetX2 - targetX1; int targetHeight = targetY2 - targetY1; if ((targetWidth > 0) && (targetHeight > 0)) { Image subImage = current.getSubImage((int) (targetX1 - xp), (int) (targetY1 - yp), (targetX2 - targetX1), (targetY2 - targetY1)); foundStart = true; image.images[startx][starty] = subImage; starty++; image.ycount = Math.max(image.ycount, starty); } yp += current.getHeight(); if (yt == ycount - 1) { xp += current.getWidth(); } } if (foundStart) { startx++; image.xcount++; } } return image; } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#getTexture() */ public Texture getTexture() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#initImpl() */ protected void initImpl() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * @see org.newdawn.slick.Image#reinit() */ protected void reinit() { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * Not supported in BigImage * * @see org.newdawn.slick.Image#setTexture(org.newdawn.slick.opengl.Texture) */ public void setTexture(Texture texture) { throw new OperationNotSupportedException("Can't use big images as offscreen buffers"); } /** * Get a sub-image that builds up this image. Note that the offsets * used will depend on the maximum texture size on the OpenGL hardware * * @param offsetX The x position of the image to return * @param offsetY The y position of the image to return * @return The image at the specified offset into the big image */ public Image getSubImage(int offsetX, int offsetY) { return images[offsetX][offsetY]; } /** * Get a count of the number images that build this image up horizontally * * @return The number of sub-images across the big image */ public int getHorizontalImageCount() { return xcount; } /** * Get a count of the number images that build this image up vertically * * @return The number of sub-images down the big image */ public int getVerticalImageCount() { return ycount; } /** * @see org.newdawn.slick.Image#toString() */ public String toString() { return "[BIG IMAGE]"; } /** * Destroy the image and release any native resources. * Calls on a destroyed image have undefined results */ public void destroy() throws SlickException { for (int tx=0;tx<xcount;tx++) { for (int ty=0;ty<ycount;ty++) { Image image = images[tx][ty]; image.destroy(); } } } /** * @see org.newdawn.slick.Image#draw(float, float, float, float, float, float, float, float, org.newdawn.slick.Color) */ public void draw(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2, Color filter) { int srcwidth = (int) (srcx2 - srcx); int srcheight = (int) (srcy2 - srcy); Image subImage = getSubImage((int) srcx,(int) srcy,srcwidth,srcheight); int width = (int) (x2 - x); int height = (int) (y2 - y); subImage.draw(x,y,width,height,filter); } /** * @see org.newdawn.slick.Image#drawCentered(float, float) */ public void drawCentered(float x, float y) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float, float, float, float, float, org.newdawn.slick.Color) */ public void drawEmbedded(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2, Color filter) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawEmbedded(float, float, float, float, float, float, float, float) */ public void drawEmbedded(float x, float y, float x2, float y2, float srcx, float srcy, float srcx2, float srcy2) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawFlash(float, float, float, float, org.newdawn.slick.Color) */ public void drawFlash(float x, float y, float width, float height, Color col) { throw new UnsupportedOperationException(); } /** * @see org.newdawn.slick.Image#drawSheared(float, float, float, float) */ public void drawSheared(float x, float y, float hshear, float vshear) { throw new UnsupportedOperationException(); } }
false
true
private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); final int imageWidth = tileSize; final int imageHeight = tileSize; final int xSize = Math.min(dataWidth, imageWidth); final int ySize = Math.min(dataHeight, imageHeight); final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { int yo = (((y * (imageWidth < tileSize ? imageWidth : tileSize)) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; }
private void build(final LoadableImageData data, final ByteBuffer imageBuffer, int filter, int tileSize) { final int dataWidth = data.getTexWidth(); final int dataHeight = data.getTexHeight(); realWidth = width = data.getWidth(); realHeight = height = data.getHeight(); if ((dataWidth <= tileSize) && (dataHeight <= tileSize)) { images = new Image[1][1]; ImageData tempData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return dataHeight; } public ByteBuffer getImageBufferData() { return imageBuffer; } public int getTexHeight() { return dataHeight; } public int getTexWidth() { return dataWidth; } public int getWidth() { return dataWidth; } }; images[0][0] = new Image(tempData, filter); xcount = 1; ycount = 1; inited = true; return; } xcount = ((realWidth-1) / tileSize) + 1; ycount = ((realHeight-1) / tileSize) + 1; images = new Image[xcount][ycount]; int components = data.getDepth() / 8; for (int x=0;x<xcount;x++) { for (int y=0;y<ycount;y++) { int finalX = ((x+1) * tileSize); int finalY = ((y+1) * tileSize); final int imageWidth = Math.min((realWidth - (x*tileSize)), tileSize); final int imageHeight = Math.min((realHeight - (y*tileSize)), tileSize); final int xSize = tileSize; final int ySize = tileSize; final ByteBuffer subBuffer = BufferUtils.createByteBuffer(tileSize*tileSize*components); int xo = x*tileSize*components; byte[] byteData = new byte[xSize*components]; for (int i=0;i<ySize;i++) { int yo = (((y * tileSize) + i) * dataWidth) * components; imageBuffer.position(yo+xo); imageBuffer.get(byteData, 0, xSize*components); subBuffer.put(byteData); } subBuffer.flip(); ImageData imgData = new ImageData() { public int getDepth() { return data.getDepth(); } public int getHeight() { return imageHeight; } public int getWidth() { return imageWidth; } public ByteBuffer getImageBufferData() { return subBuffer; } public int getTexHeight() { return ySize; } public int getTexWidth() { return xSize; } }; images[x][y] = new Image(imgData, filter); } } inited = true; }
diff --git a/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java b/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java index a0afad524..781c39a40 100755 --- a/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java +++ b/src/java/fedora/server/access/dissemination/DatastreamResolverServlet.java @@ -1,539 +1,552 @@ package fedora.server.access.dissemination; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.security.Principal; import java.sql.Timestamp; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import fedora.common.Constants; import fedora.server.Context; import fedora.server.ReadOnlyContext; import fedora.server.Server; import fedora.server.errors.InitializationException; import fedora.server.errors.authorization.AuthzDeniedException; import fedora.server.errors.authorization.AuthzException; import fedora.server.errors.authorization.AuthzOperationalException; import fedora.server.errors.servletExceptionExtensions.RootException; import fedora.server.security.Authorization; import fedora.server.security.BackendPolicies; import fedora.server.security.servletfilters.ExtendedHttpServletRequest; import fedora.server.storage.DOManager; import fedora.server.storage.DOReader; import fedora.server.storage.ExternalContentManager; import fedora.server.storage.types.Datastream; import fedora.server.storage.types.DatastreamMediation; import fedora.server.storage.types.MIMETypedStream; import fedora.server.storage.types.Property; import fedora.server.utilities.ServerUtility; /** * <p> * <b>Title: </b>DatastreamResolverServlet.java * </p> * <p> * <b>Description: </b>This servlet acts as a proxy to resolve the physical * location of datastreams. It requires a single parameter named <code>id</code> * that denotes the temporary id of the requested datastresm. This id is in the * form of a DateTime stamp. The servlet will perform an in-memory hashtable * lookup using the temporary id to obtain the actual physical location of the * datastream and then return the contents of the datastream as a MIME-typed * stream. This servlet is invoked primarily by external mechanisms needing to * retrieve the contents of a datastream. * </p> * <p> * The servlet also requires that an external mechanism request a datastream * within a finite time interval of the tempID's creation. This is to lessen the * risk of unauthorized access. The time interval within which a mechanism must * repond is set by the Fedora configuration parameter named * datastreamMediationLimit and is speci207fied in milliseconds. If this * parameter is not supplied it defaults to 5000 miliseconds. * </p> * * @author [email protected] * @version $Id: DatastreamResolverServlet.java,v 1.50 2006/09/29 20:29:12 wdn5e * Exp $ */ public class DatastreamResolverServlet extends HttpServlet { /** Logger for this class. */ private static final Logger LOG = Logger.getLogger( DatastreamResolverServlet.class.getName()); private static final long serialVersionUID = 1L; private static Server s_server; private static DOManager m_manager; private static Hashtable dsRegistry; private static int datastreamMediationLimit; private static final String HTML_CONTENT_TYPE = "text/html"; private static String fedoraServerHost; private static String fedoraServerPort; private static String fedoraServerRedirectPort; /** * <p> * Initialize servlet. * </p> * * @throws ServletException * If the servet cannot be initialized. */ public void init() throws ServletException { try { s_server = Server.getInstance(new File(Constants.FEDORA_HOME), false); fedoraServerPort = s_server.getParameter("fedoraServerPort"); fedoraServerRedirectPort = s_server .getParameter("fedoraRedirectPort"); fedoraServerHost = s_server.getParameter("fedoraServerHost"); m_manager = (DOManager) s_server .getModule("fedora.server.storage.DOManager"); String expireLimit = s_server .getParameter("datastreamMediationLimit"); if (expireLimit == null || expireLimit.equalsIgnoreCase("")) { LOG.info("datastreamMediationLimit unspecified, using default " + "of 5 seconds"); datastreamMediationLimit = 5000; } else { datastreamMediationLimit = new Integer(expireLimit).intValue(); LOG.info("datastreamMediationLimit: " + datastreamMediationLimit); } } catch (InitializationException ie) { throw new ServletException( "Unable to get an instance of Fedora server " + "-- " + ie.getMessage()); } catch (Throwable th) { LOG.error("Error initializing servlet", th); } } private static final boolean contains(String[] array, String item) { boolean contains = false; for (int i = 0; i < array.length; i++) { if (array[i].equals(item)) { contains = true; break; } } return contains; } public static final String ACTION_LABEL = "Resolve Datastream"; /** * <p> * Processes the servlet request and resolves the physical location of the * specified datastream. * </p> * * @param request * The servlet request. * @param response * servlet The servlet response. * @throws ServletException * If an error occurs that effects the servlet's basic * operation. * @throws IOException * If an error occurrs with an input or output operation. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = null; String dsPhysicalLocation = null; String dsControlGroupType = null; String user = null; String pass = null; MIMETypedStream mimeTypedStream = null; DisseminationService ds = null; Timestamp keyTimestamp = null; Timestamp currentTimestamp = null; PrintWriter out = null; ServletOutputStream outStream = null; String requestURI = request.getRequestURL().toString() + "?" + request.getQueryString(); id = request.getParameter("id").replaceAll("T", " "); LOG.debug("Datastream tempID=" + id); LOG.debug("DRS doGet()"); try { // Check for required id parameter. if (id == null || id.equalsIgnoreCase("")) { String message = "[DatastreamResolverServlet] No datastream ID " + "specified in servlet request: " + request.getRequestURI(); LOG.error(message); response .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } id = id.replaceAll("T", " ").replaceAll("/", "").trim(); // Get in-memory hashtable of mappings from Fedora server. ds = new DisseminationService(); dsRegistry = DisseminationService.dsRegistry; DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id); if (dm == null) { StringBuffer entries = new StringBuffer(); Iterator eIter = dsRegistry.keySet().iterator(); while (eIter.hasNext()) { entries.append("'" + (String) eIter.next() + "' "); } throw new IOException( "Cannot find datastream in temp registry by key: " + id + "\n" + "Reg entries: " + entries.toString()); } dsPhysicalLocation = dm.dsLocation; dsControlGroupType = dm.dsControlGroupType; user = dm.callUsername; pass = dm.callPassword; if (LOG.isDebugEnabled()) { LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: " + dm.dsLocation); LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: " + dm.dsControlGroupType); LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: " + dm.callUsername); LOG.debug("**************************** DatastreamResolverServlet dm.Password: " + dm.callPassword); LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: " + dm.callbackRole); LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: " + dm.callbackBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: " + dm.callBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: " + dm.callbackSSL); LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: " + dm.callSSL); LOG.debug("**************************** DatastreamResolverServlet non ssl port: " + fedoraServerPort); LOG.debug("**************************** DatastreamResolverServlet ssl port: " + fedoraServerRedirectPort); } // DatastreamResolverServlet maps to two distinct servlet mappings // in fedora web.xml. // getDS - is used when the backend service is incapable of // basicAuth or SSL // getDSAuthenticated - is used when the backend service has // basicAuth and SSL enabled // Since both the getDS and getDSAuthenticated servlet targets map // to the same servlet // code and the Context used to initialize policy enforcement is // based on the incoming // HTTPRequest, the code must provide special handling for requests // using the getDS // target. When the incoming URL to DatastreamResolverServlet // contains the getDS target, // there are several conditions that must be checked to insure that // the correct role is // assigned to the request before policy enforcement occurs. // 1) if the mapped dsPhysicalLocation of the request is actually a // callback to the // Fedora server itself, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match those of the getDS // target. // 2) if the mapped dsPhysicalLocation of the request is actually a // Managed Content // or Inline XML Content datastream, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match the getDS target. // 3) Otherwise, leave the targetrole unchanged. if (request.getRequestURI().endsWith("getDS") && (ServerUtility.isURLFedoraServer(dsPhysicalLocation) || dsControlGroupType.equals("M") || dsControlGroupType .equals("X"))) { if (LOG.isDebugEnabled()) LOG.debug("*********************** Changed role from: " + dm.callbackRole + " to: " + BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE); dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE; } // If callback is to fedora server itself and callback is over SSL, // adjust the protocol and port // on the URL to match settings of Fedora server. This is necessary // since the SSL settings for the // backend service may have specified basicAuth=false, but contained // datastreams that are callbacks // to the local Fedora server which requires SSL. The version of // HttpClient currently in use does // not handle autoredirecting from http to https so it is necessary // to set the protocol and port // to the appropriate secure port. if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) { if (dm.callbackSSL) { dsPhysicalLocation = dsPhysicalLocation.replaceFirst( "http:", "https:"); dsPhysicalLocation = dsPhysicalLocation.replaceFirst( fedoraServerPort, fedoraServerRedirectPort); if (LOG.isDebugEnabled()) LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: " + dsPhysicalLocation); } } keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id)); currentTimestamp = new Timestamp(new Date().getTime()); LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation + "dsControlGroupType=" + dsControlGroupType); // Deny mechanism requests that fall outside the specified time // interval. // The expiration limit can be adjusted using the Fedora config // parameter // named "datastreamMediationLimit" which is in milliseconds. long diff = currentTimestamp.getTime() - keyTimestamp.getTime(); LOG.debug("Timestamp diff for mechanism's reponse: " + diff + " ms."); if (diff > (long) datastreamMediationLimit) { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out .println("<br><b>[DatastreamResolverServlet] Error:</b>" + "<font color=\"red\"> Mechanism has failed to respond " + "to the DatastreamResolverServlet within the specified " + "time limit of \"" + datastreamMediationLimit + "\"" + "milliseconds. Datastream access denied."); LOG.error("Mechanism failed to respond to " + "DatastreamResolverServlet within time limit of " + datastreamMediationLimit); out.close(); return; } if (dm.callbackRole == null) { throw new AuthzOperationalException( "no callbackRole for this ticket"); } String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" + dm.callbackRole; // restrict access to role of this // ticket String[] targetRoles = { targetRole }; Context context = ReadOnlyContext.getContext( Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles); if (request.getRemoteUser() == null) { // non-authn: must accept target role of ticket LOG.debug("DatastreamResolverServlet: unAuthenticated request"); } else { // authn: check user roles for target role of ticket /* LOG.debug("DatastreamResolverServlet: Authenticated request getting user"); String[] roles = null; Principal principal = request.getUserPrincipal(); if (principal == null) { // no principal to grok roles from!! } else { try { roles = ReadOnlyContext.getRoles(principal); } catch (Throwable t) { } } if (roles == null) { roles = new String[0]; } */ //XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) { LOG.debug("DatastreamResolverServlet: user==" + request.getRemoteUser()); /* if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) { LOG.debug("DatastreamResolverServlet: user has required role"); } else { LOG.debug("DatastreamResolverServlet: authZ exception in validating user"); throw new AuthzDeniedException("wrong user for this ticket"); } */ } if (LOG.isDebugEnabled()) { LOG.debug("debugging backendService role"); LOG.debug("targetRole=" + targetRole); int targetRolesLength = targetRoles.length; LOG.debug("targetRolesLength=" + targetRolesLength); if (targetRolesLength > 0) { LOG.debug("targetRoles[0]=" + targetRoles[0]); } int nSubjectValues = context.nSubjectValues(targetRole); LOG.debug("nSubjectValues=" + nSubjectValues); if (nSubjectValues > 0) { LOG.debug("context.getSubjectValue(targetRole)=" + context.getSubjectValue(targetRole)); } Iterator it = context.subjectAttributes(); while (it.hasNext()) { String name = (String) it.next(); - String value = context.getSubjectValue(name); - LOG.debug("another subject attribute from context " - + name + "=" + value); + int n = context.nSubjectValues(name); + switch (n) { + case 0: + LOG.debug("no subject attributes for " + name); + break; + case 1: + String value = context.getSubjectValue(name); + LOG.debug("single subject attributes for " + name + "=" + value); + break; + default: + String[] values = context.getSubjectValues(name); + for (int i=0; i<values.length; i++) { + LOG.debug("another subject attribute from context " + + name + "=" + values[i]); + } + } } it = context.environmentAttributes(); while (it.hasNext()) { String name = (String) it.next(); String value = context.getEnvironmentValue(name); LOG.debug("another environment attribute from context " + name + "=" + value); } } /* // Enforcement of Backend Security is temporarily disabled pending refactoring. // LOG.debug("DatastreamResolverServlet: about to do final authZ check"); Authorization authorization = (Authorization) s_server .getModule("fedora.server.security.Authorization"); authorization.enforceResolveDatastream(context, keyTimestamp); LOG.debug("DatastreamResolverServlet: final authZ check suceeded....."); */ if (dsControlGroupType.equalsIgnoreCase("E")) { // testing to see what's in request header that might be of // interest if (LOG.isDebugEnabled()) { for (Enumeration e = request.getHeaderNames(); e .hasMoreElements();) { String name = (String) e.nextElement(); Enumeration headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: " + name + " : " + value); } } // Datastream is ReferencedExternalContent so dsLocation is a // URL string ExternalContentManager externalContentManager = (ExternalContentManager) s_server .getModule("fedora.server.storage.ExternalContentManager"); mimeTypedStream = externalContentManager.getExternalContent( dsPhysicalLocation, context); // had substituted context: // ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, // request)); outStream = response.getOutputStream(); response.setContentType(mimeTypedStream.MIMEType); Property[] headerArray = mimeTypedStream.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !(headerArray[i].name .equalsIgnoreCase("content-type"))) { response.addHeader(headerArray[i].name, headerArray[i].value); LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER " + headerArray[i].name + " : " + headerArray[i].value); } } } int byteStream = 0; byte[] buffer = new byte[255]; while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) { outStream.write(buffer, 0, byteStream); } buffer = null; outStream.flush(); } else if (dsControlGroupType.equalsIgnoreCase("M") || dsControlGroupType.equalsIgnoreCase("X")) { // Datastream is either XMLMetadata or ManagedContent so // dsLocation // is in the form of an internal Fedora ID using the syntax: // PID+DSID+DSVersID; parse the ID and get the datastream // content. String PID = null; String dsVersionID = null; String dsID = null; String[] s = dsPhysicalLocation.split("\\+"); if (s.length != 3) { String message = "[DatastreamResolverServlet] The " + "internal Fedora datastream id: \"" + dsPhysicalLocation + "\" is invalid."; LOG.error(message); throw new ServletException(message); } PID = s[0]; dsID = s[1]; dsVersionID = s[2]; LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID=" + dsVersionID); DOReader doReader = m_manager.getReader( Server.USE_DEFINITIVE_STORE, context, PID); Datastream d = (Datastream) doReader.getDatastream(dsID, dsVersionID); LOG.debug("Got datastream: " + d.DatastreamID); InputStream is = d.getContentStream(); int bytestream = 0; response.setContentType(d.DSMIME); outStream = response.getOutputStream(); byte[] buffer = new byte[255]; while ((bytestream = is.read(buffer)) != -1) { outStream.write(buffer, 0, bytestream); } buffer = null; is.close(); } else { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out.println("<br>[DatastreamResolverServlet] Unknown " + "dsControlGroupType: " + dsControlGroupType + "</br>"); LOG.error("Unknown dsControlGroupType: " + dsControlGroupType); } } catch (AuthzException ae) { LOG.error("Authorization failure resolving datastream" + " (actionLabel=" + ACTION_LABEL + ")", ae); throw RootException.getServletException(ae, request, ACTION_LABEL, new String[0]); } catch (Throwable th) { LOG.error("Error resolving datastream", th); String message = "[DatastreamResolverServlet] returned an error. The " + "underlying error was a \"" + th.getClass().getName() + " The message was \"" + th.getMessage() + "\". "; throw new ServletException(message); } finally { if (out != null) out.close(); if (outStream != null) outStream.close(); dsRegistry.remove(id); } } // Clean up resources public void destroy() { } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = null; String dsPhysicalLocation = null; String dsControlGroupType = null; String user = null; String pass = null; MIMETypedStream mimeTypedStream = null; DisseminationService ds = null; Timestamp keyTimestamp = null; Timestamp currentTimestamp = null; PrintWriter out = null; ServletOutputStream outStream = null; String requestURI = request.getRequestURL().toString() + "?" + request.getQueryString(); id = request.getParameter("id").replaceAll("T", " "); LOG.debug("Datastream tempID=" + id); LOG.debug("DRS doGet()"); try { // Check for required id parameter. if (id == null || id.equalsIgnoreCase("")) { String message = "[DatastreamResolverServlet] No datastream ID " + "specified in servlet request: " + request.getRequestURI(); LOG.error(message); response .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } id = id.replaceAll("T", " ").replaceAll("/", "").trim(); // Get in-memory hashtable of mappings from Fedora server. ds = new DisseminationService(); dsRegistry = DisseminationService.dsRegistry; DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id); if (dm == null) { StringBuffer entries = new StringBuffer(); Iterator eIter = dsRegistry.keySet().iterator(); while (eIter.hasNext()) { entries.append("'" + (String) eIter.next() + "' "); } throw new IOException( "Cannot find datastream in temp registry by key: " + id + "\n" + "Reg entries: " + entries.toString()); } dsPhysicalLocation = dm.dsLocation; dsControlGroupType = dm.dsControlGroupType; user = dm.callUsername; pass = dm.callPassword; if (LOG.isDebugEnabled()) { LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: " + dm.dsLocation); LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: " + dm.dsControlGroupType); LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: " + dm.callUsername); LOG.debug("**************************** DatastreamResolverServlet dm.Password: " + dm.callPassword); LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: " + dm.callbackRole); LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: " + dm.callbackBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: " + dm.callBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: " + dm.callbackSSL); LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: " + dm.callSSL); LOG.debug("**************************** DatastreamResolverServlet non ssl port: " + fedoraServerPort); LOG.debug("**************************** DatastreamResolverServlet ssl port: " + fedoraServerRedirectPort); } // DatastreamResolverServlet maps to two distinct servlet mappings // in fedora web.xml. // getDS - is used when the backend service is incapable of // basicAuth or SSL // getDSAuthenticated - is used when the backend service has // basicAuth and SSL enabled // Since both the getDS and getDSAuthenticated servlet targets map // to the same servlet // code and the Context used to initialize policy enforcement is // based on the incoming // HTTPRequest, the code must provide special handling for requests // using the getDS // target. When the incoming URL to DatastreamResolverServlet // contains the getDS target, // there are several conditions that must be checked to insure that // the correct role is // assigned to the request before policy enforcement occurs. // 1) if the mapped dsPhysicalLocation of the request is actually a // callback to the // Fedora server itself, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match those of the getDS // target. // 2) if the mapped dsPhysicalLocation of the request is actually a // Managed Content // or Inline XML Content datastream, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match the getDS target. // 3) Otherwise, leave the targetrole unchanged. if (request.getRequestURI().endsWith("getDS") && (ServerUtility.isURLFedoraServer(dsPhysicalLocation) || dsControlGroupType.equals("M") || dsControlGroupType .equals("X"))) { if (LOG.isDebugEnabled()) LOG.debug("*********************** Changed role from: " + dm.callbackRole + " to: " + BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE); dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE; } // If callback is to fedora server itself and callback is over SSL, // adjust the protocol and port // on the URL to match settings of Fedora server. This is necessary // since the SSL settings for the // backend service may have specified basicAuth=false, but contained // datastreams that are callbacks // to the local Fedora server which requires SSL. The version of // HttpClient currently in use does // not handle autoredirecting from http to https so it is necessary // to set the protocol and port // to the appropriate secure port. if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) { if (dm.callbackSSL) { dsPhysicalLocation = dsPhysicalLocation.replaceFirst( "http:", "https:"); dsPhysicalLocation = dsPhysicalLocation.replaceFirst( fedoraServerPort, fedoraServerRedirectPort); if (LOG.isDebugEnabled()) LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: " + dsPhysicalLocation); } } keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id)); currentTimestamp = new Timestamp(new Date().getTime()); LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation + "dsControlGroupType=" + dsControlGroupType); // Deny mechanism requests that fall outside the specified time // interval. // The expiration limit can be adjusted using the Fedora config // parameter // named "datastreamMediationLimit" which is in milliseconds. long diff = currentTimestamp.getTime() - keyTimestamp.getTime(); LOG.debug("Timestamp diff for mechanism's reponse: " + diff + " ms."); if (diff > (long) datastreamMediationLimit) { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out .println("<br><b>[DatastreamResolverServlet] Error:</b>" + "<font color=\"red\"> Mechanism has failed to respond " + "to the DatastreamResolverServlet within the specified " + "time limit of \"" + datastreamMediationLimit + "\"" + "milliseconds. Datastream access denied."); LOG.error("Mechanism failed to respond to " + "DatastreamResolverServlet within time limit of " + datastreamMediationLimit); out.close(); return; } if (dm.callbackRole == null) { throw new AuthzOperationalException( "no callbackRole for this ticket"); } String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" + dm.callbackRole; // restrict access to role of this // ticket String[] targetRoles = { targetRole }; Context context = ReadOnlyContext.getContext( Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles); if (request.getRemoteUser() == null) { // non-authn: must accept target role of ticket LOG.debug("DatastreamResolverServlet: unAuthenticated request"); } else { // authn: check user roles for target role of ticket /* LOG.debug("DatastreamResolverServlet: Authenticated request getting user"); String[] roles = null; Principal principal = request.getUserPrincipal(); if (principal == null) { // no principal to grok roles from!! } else { try { roles = ReadOnlyContext.getRoles(principal); } catch (Throwable t) { } } if (roles == null) { roles = new String[0]; } */ //XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) { LOG.debug("DatastreamResolverServlet: user==" + request.getRemoteUser()); /* if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) { LOG.debug("DatastreamResolverServlet: user has required role"); } else { LOG.debug("DatastreamResolverServlet: authZ exception in validating user"); throw new AuthzDeniedException("wrong user for this ticket"); } */ } if (LOG.isDebugEnabled()) { LOG.debug("debugging backendService role"); LOG.debug("targetRole=" + targetRole); int targetRolesLength = targetRoles.length; LOG.debug("targetRolesLength=" + targetRolesLength); if (targetRolesLength > 0) { LOG.debug("targetRoles[0]=" + targetRoles[0]); } int nSubjectValues = context.nSubjectValues(targetRole); LOG.debug("nSubjectValues=" + nSubjectValues); if (nSubjectValues > 0) { LOG.debug("context.getSubjectValue(targetRole)=" + context.getSubjectValue(targetRole)); } Iterator it = context.subjectAttributes(); while (it.hasNext()) { String name = (String) it.next(); String value = context.getSubjectValue(name); LOG.debug("another subject attribute from context " + name + "=" + value); } it = context.environmentAttributes(); while (it.hasNext()) { String name = (String) it.next(); String value = context.getEnvironmentValue(name); LOG.debug("another environment attribute from context " + name + "=" + value); } } /* // Enforcement of Backend Security is temporarily disabled pending refactoring. // LOG.debug("DatastreamResolverServlet: about to do final authZ check"); Authorization authorization = (Authorization) s_server .getModule("fedora.server.security.Authorization"); authorization.enforceResolveDatastream(context, keyTimestamp); LOG.debug("DatastreamResolverServlet: final authZ check suceeded....."); */ if (dsControlGroupType.equalsIgnoreCase("E")) { // testing to see what's in request header that might be of // interest if (LOG.isDebugEnabled()) { for (Enumeration e = request.getHeaderNames(); e .hasMoreElements();) { String name = (String) e.nextElement(); Enumeration headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: " + name + " : " + value); } } // Datastream is ReferencedExternalContent so dsLocation is a // URL string ExternalContentManager externalContentManager = (ExternalContentManager) s_server .getModule("fedora.server.storage.ExternalContentManager"); mimeTypedStream = externalContentManager.getExternalContent( dsPhysicalLocation, context); // had substituted context: // ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, // request)); outStream = response.getOutputStream(); response.setContentType(mimeTypedStream.MIMEType); Property[] headerArray = mimeTypedStream.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !(headerArray[i].name .equalsIgnoreCase("content-type"))) { response.addHeader(headerArray[i].name, headerArray[i].value); LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER " + headerArray[i].name + " : " + headerArray[i].value); } } } int byteStream = 0; byte[] buffer = new byte[255]; while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) { outStream.write(buffer, 0, byteStream); } buffer = null; outStream.flush(); } else if (dsControlGroupType.equalsIgnoreCase("M") || dsControlGroupType.equalsIgnoreCase("X")) { // Datastream is either XMLMetadata or ManagedContent so // dsLocation // is in the form of an internal Fedora ID using the syntax: // PID+DSID+DSVersID; parse the ID and get the datastream // content. String PID = null; String dsVersionID = null; String dsID = null; String[] s = dsPhysicalLocation.split("\\+"); if (s.length != 3) { String message = "[DatastreamResolverServlet] The " + "internal Fedora datastream id: \"" + dsPhysicalLocation + "\" is invalid."; LOG.error(message); throw new ServletException(message); } PID = s[0]; dsID = s[1]; dsVersionID = s[2]; LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID=" + dsVersionID); DOReader doReader = m_manager.getReader( Server.USE_DEFINITIVE_STORE, context, PID); Datastream d = (Datastream) doReader.getDatastream(dsID, dsVersionID); LOG.debug("Got datastream: " + d.DatastreamID); InputStream is = d.getContentStream(); int bytestream = 0; response.setContentType(d.DSMIME); outStream = response.getOutputStream(); byte[] buffer = new byte[255]; while ((bytestream = is.read(buffer)) != -1) { outStream.write(buffer, 0, bytestream); } buffer = null; is.close(); } else { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out.println("<br>[DatastreamResolverServlet] Unknown " + "dsControlGroupType: " + dsControlGroupType + "</br>"); LOG.error("Unknown dsControlGroupType: " + dsControlGroupType); } } catch (AuthzException ae) { LOG.error("Authorization failure resolving datastream" + " (actionLabel=" + ACTION_LABEL + ")", ae); throw RootException.getServletException(ae, request, ACTION_LABEL, new String[0]); } catch (Throwable th) { LOG.error("Error resolving datastream", th); String message = "[DatastreamResolverServlet] returned an error. The " + "underlying error was a \"" + th.getClass().getName() + " The message was \"" + th.getMessage() + "\". "; throw new ServletException(message); } finally { if (out != null) out.close(); if (outStream != null) outStream.close(); dsRegistry.remove(id); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = null; String dsPhysicalLocation = null; String dsControlGroupType = null; String user = null; String pass = null; MIMETypedStream mimeTypedStream = null; DisseminationService ds = null; Timestamp keyTimestamp = null; Timestamp currentTimestamp = null; PrintWriter out = null; ServletOutputStream outStream = null; String requestURI = request.getRequestURL().toString() + "?" + request.getQueryString(); id = request.getParameter("id").replaceAll("T", " "); LOG.debug("Datastream tempID=" + id); LOG.debug("DRS doGet()"); try { // Check for required id parameter. if (id == null || id.equalsIgnoreCase("")) { String message = "[DatastreamResolverServlet] No datastream ID " + "specified in servlet request: " + request.getRequestURI(); LOG.error(message); response .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } id = id.replaceAll("T", " ").replaceAll("/", "").trim(); // Get in-memory hashtable of mappings from Fedora server. ds = new DisseminationService(); dsRegistry = DisseminationService.dsRegistry; DatastreamMediation dm = (DatastreamMediation) dsRegistry.get(id); if (dm == null) { StringBuffer entries = new StringBuffer(); Iterator eIter = dsRegistry.keySet().iterator(); while (eIter.hasNext()) { entries.append("'" + (String) eIter.next() + "' "); } throw new IOException( "Cannot find datastream in temp registry by key: " + id + "\n" + "Reg entries: " + entries.toString()); } dsPhysicalLocation = dm.dsLocation; dsControlGroupType = dm.dsControlGroupType; user = dm.callUsername; pass = dm.callPassword; if (LOG.isDebugEnabled()) { LOG.debug("**************************** DatastreamResolverServlet dm.dsLocation: " + dm.dsLocation); LOG.debug("**************************** DatastreamResolverServlet dm.dsControlGroupType: " + dm.dsControlGroupType); LOG.debug("**************************** DatastreamResolverServlet dm.callUsername: " + dm.callUsername); LOG.debug("**************************** DatastreamResolverServlet dm.Password: " + dm.callPassword); LOG.debug("**************************** DatastreamResolverServlet dm.callbackRole: " + dm.callbackRole); LOG.debug("**************************** DatastreamResolverServlet dm.callbackBasicAuth: " + dm.callbackBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callBasicAuth: " + dm.callBasicAuth); LOG.debug("**************************** DatastreamResolverServlet dm.callbackSSl: " + dm.callbackSSL); LOG.debug("**************************** DatastreamResolverServlet dm.callSSl: " + dm.callSSL); LOG.debug("**************************** DatastreamResolverServlet non ssl port: " + fedoraServerPort); LOG.debug("**************************** DatastreamResolverServlet ssl port: " + fedoraServerRedirectPort); } // DatastreamResolverServlet maps to two distinct servlet mappings // in fedora web.xml. // getDS - is used when the backend service is incapable of // basicAuth or SSL // getDSAuthenticated - is used when the backend service has // basicAuth and SSL enabled // Since both the getDS and getDSAuthenticated servlet targets map // to the same servlet // code and the Context used to initialize policy enforcement is // based on the incoming // HTTPRequest, the code must provide special handling for requests // using the getDS // target. When the incoming URL to DatastreamResolverServlet // contains the getDS target, // there are several conditions that must be checked to insure that // the correct role is // assigned to the request before policy enforcement occurs. // 1) if the mapped dsPhysicalLocation of the request is actually a // callback to the // Fedora server itself, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match those of the getDS // target. // 2) if the mapped dsPhysicalLocation of the request is actually a // Managed Content // or Inline XML Content datastream, then assign the role as // BACKEND_SERVICE_CALL_UNSECURE so // the basicAuth and SSL constraints will match the getDS target. // 3) Otherwise, leave the targetrole unchanged. if (request.getRequestURI().endsWith("getDS") && (ServerUtility.isURLFedoraServer(dsPhysicalLocation) || dsControlGroupType.equals("M") || dsControlGroupType .equals("X"))) { if (LOG.isDebugEnabled()) LOG.debug("*********************** Changed role from: " + dm.callbackRole + " to: " + BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE); dm.callbackRole = BackendPolicies.BACKEND_SERVICE_CALL_UNSECURE; } // If callback is to fedora server itself and callback is over SSL, // adjust the protocol and port // on the URL to match settings of Fedora server. This is necessary // since the SSL settings for the // backend service may have specified basicAuth=false, but contained // datastreams that are callbacks // to the local Fedora server which requires SSL. The version of // HttpClient currently in use does // not handle autoredirecting from http to https so it is necessary // to set the protocol and port // to the appropriate secure port. if (dm.callbackRole.equals(BackendPolicies.FEDORA_INTERNAL_CALL)) { if (dm.callbackSSL) { dsPhysicalLocation = dsPhysicalLocation.replaceFirst( "http:", "https:"); dsPhysicalLocation = dsPhysicalLocation.replaceFirst( fedoraServerPort, fedoraServerRedirectPort); if (LOG.isDebugEnabled()) LOG.debug("*********************** DatastreamResolverServlet -- Was Fedora-to-Fedora call -- modified dsPhysicalLocation: " + dsPhysicalLocation); } } keyTimestamp = Timestamp.valueOf(ds.extractTimestamp(id)); currentTimestamp = new Timestamp(new Date().getTime()); LOG.debug("dsPhysicalLocation=" + dsPhysicalLocation + "dsControlGroupType=" + dsControlGroupType); // Deny mechanism requests that fall outside the specified time // interval. // The expiration limit can be adjusted using the Fedora config // parameter // named "datastreamMediationLimit" which is in milliseconds. long diff = currentTimestamp.getTime() - keyTimestamp.getTime(); LOG.debug("Timestamp diff for mechanism's reponse: " + diff + " ms."); if (diff > (long) datastreamMediationLimit) { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out .println("<br><b>[DatastreamResolverServlet] Error:</b>" + "<font color=\"red\"> Mechanism has failed to respond " + "to the DatastreamResolverServlet within the specified " + "time limit of \"" + datastreamMediationLimit + "\"" + "milliseconds. Datastream access denied."); LOG.error("Mechanism failed to respond to " + "DatastreamResolverServlet within time limit of " + datastreamMediationLimit); out.close(); return; } if (dm.callbackRole == null) { throw new AuthzOperationalException( "no callbackRole for this ticket"); } String targetRole = //Authorization.FEDORA_ROLE_KEY + "=" + dm.callbackRole; // restrict access to role of this // ticket String[] targetRoles = { targetRole }; Context context = ReadOnlyContext.getContext( Constants.HTTP_REQUEST.REST.uri, request); // , targetRoles); if (request.getRemoteUser() == null) { // non-authn: must accept target role of ticket LOG.debug("DatastreamResolverServlet: unAuthenticated request"); } else { // authn: check user roles for target role of ticket /* LOG.debug("DatastreamResolverServlet: Authenticated request getting user"); String[] roles = null; Principal principal = request.getUserPrincipal(); if (principal == null) { // no principal to grok roles from!! } else { try { roles = ReadOnlyContext.getRoles(principal); } catch (Throwable t) { } } if (roles == null) { roles = new String[0]; } */ //XXXXXXXXXXXXXXXXXXXXXXxif (contains(roles, targetRole)) { LOG.debug("DatastreamResolverServlet: user==" + request.getRemoteUser()); /* if (((ExtendedHttpServletRequest)request).isUserInRole(targetRole)) { LOG.debug("DatastreamResolverServlet: user has required role"); } else { LOG.debug("DatastreamResolverServlet: authZ exception in validating user"); throw new AuthzDeniedException("wrong user for this ticket"); } */ } if (LOG.isDebugEnabled()) { LOG.debug("debugging backendService role"); LOG.debug("targetRole=" + targetRole); int targetRolesLength = targetRoles.length; LOG.debug("targetRolesLength=" + targetRolesLength); if (targetRolesLength > 0) { LOG.debug("targetRoles[0]=" + targetRoles[0]); } int nSubjectValues = context.nSubjectValues(targetRole); LOG.debug("nSubjectValues=" + nSubjectValues); if (nSubjectValues > 0) { LOG.debug("context.getSubjectValue(targetRole)=" + context.getSubjectValue(targetRole)); } Iterator it = context.subjectAttributes(); while (it.hasNext()) { String name = (String) it.next(); int n = context.nSubjectValues(name); switch (n) { case 0: LOG.debug("no subject attributes for " + name); break; case 1: String value = context.getSubjectValue(name); LOG.debug("single subject attributes for " + name + "=" + value); break; default: String[] values = context.getSubjectValues(name); for (int i=0; i<values.length; i++) { LOG.debug("another subject attribute from context " + name + "=" + values[i]); } } } it = context.environmentAttributes(); while (it.hasNext()) { String name = (String) it.next(); String value = context.getEnvironmentValue(name); LOG.debug("another environment attribute from context " + name + "=" + value); } } /* // Enforcement of Backend Security is temporarily disabled pending refactoring. // LOG.debug("DatastreamResolverServlet: about to do final authZ check"); Authorization authorization = (Authorization) s_server .getModule("fedora.server.security.Authorization"); authorization.enforceResolveDatastream(context, keyTimestamp); LOG.debug("DatastreamResolverServlet: final authZ check suceeded....."); */ if (dsControlGroupType.equalsIgnoreCase("E")) { // testing to see what's in request header that might be of // interest if (LOG.isDebugEnabled()) { for (Enumeration e = request.getHeaderNames(); e .hasMoreElements();) { String name = (String) e.nextElement(); Enumeration headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); LOG.debug("DATASTREAMRESOLVERSERVLET REQUEST HEADER CONTAINED: " + name + " : " + value); } } // Datastream is ReferencedExternalContent so dsLocation is a // URL string ExternalContentManager externalContentManager = (ExternalContentManager) s_server .getModule("fedora.server.storage.ExternalContentManager"); mimeTypedStream = externalContentManager.getExternalContent( dsPhysicalLocation, context); // had substituted context: // ReadOnlyContext.getContext(Constants.HTTP_REQUEST.REST.uri, // request)); outStream = response.getOutputStream(); response.setContentType(mimeTypedStream.MIMEType); Property[] headerArray = mimeTypedStream.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !(headerArray[i].name .equalsIgnoreCase("content-type"))) { response.addHeader(headerArray[i].name, headerArray[i].value); LOG.debug("THIS WAS ADDED TO DATASTREAMRESOLVERSERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER " + headerArray[i].name + " : " + headerArray[i].value); } } } int byteStream = 0; byte[] buffer = new byte[255]; while ((byteStream = mimeTypedStream.getStream().read(buffer)) != -1) { outStream.write(buffer, 0, byteStream); } buffer = null; outStream.flush(); } else if (dsControlGroupType.equalsIgnoreCase("M") || dsControlGroupType.equalsIgnoreCase("X")) { // Datastream is either XMLMetadata or ManagedContent so // dsLocation // is in the form of an internal Fedora ID using the syntax: // PID+DSID+DSVersID; parse the ID and get the datastream // content. String PID = null; String dsVersionID = null; String dsID = null; String[] s = dsPhysicalLocation.split("\\+"); if (s.length != 3) { String message = "[DatastreamResolverServlet] The " + "internal Fedora datastream id: \"" + dsPhysicalLocation + "\" is invalid."; LOG.error(message); throw new ServletException(message); } PID = s[0]; dsID = s[1]; dsVersionID = s[2]; LOG.debug("PID=" + PID + ", dsID=" + dsID + ", dsVersionID=" + dsVersionID); DOReader doReader = m_manager.getReader( Server.USE_DEFINITIVE_STORE, context, PID); Datastream d = (Datastream) doReader.getDatastream(dsID, dsVersionID); LOG.debug("Got datastream: " + d.DatastreamID); InputStream is = d.getContentStream(); int bytestream = 0; response.setContentType(d.DSMIME); outStream = response.getOutputStream(); byte[] buffer = new byte[255]; while ((bytestream = is.read(buffer)) != -1) { outStream.write(buffer, 0, bytestream); } buffer = null; is.close(); } else { out = response.getWriter(); response.setContentType(HTML_CONTENT_TYPE); out.println("<br>[DatastreamResolverServlet] Unknown " + "dsControlGroupType: " + dsControlGroupType + "</br>"); LOG.error("Unknown dsControlGroupType: " + dsControlGroupType); } } catch (AuthzException ae) { LOG.error("Authorization failure resolving datastream" + " (actionLabel=" + ACTION_LABEL + ")", ae); throw RootException.getServletException(ae, request, ACTION_LABEL, new String[0]); } catch (Throwable th) { LOG.error("Error resolving datastream", th); String message = "[DatastreamResolverServlet] returned an error. The " + "underlying error was a \"" + th.getClass().getName() + " The message was \"" + th.getMessage() + "\". "; throw new ServletException(message); } finally { if (out != null) out.close(); if (outStream != null) outStream.close(); dsRegistry.remove(id); } }
diff --git a/src/share/org/apache/struts/action/ExceptionHandler.java b/src/share/org/apache/struts/action/ExceptionHandler.java index ab9dc6eb7..a6f42fb72 100644 --- a/src/share/org/apache/struts/action/ExceptionHandler.java +++ b/src/share/org/apache/struts/action/ExceptionHandler.java @@ -1,161 +1,162 @@ /* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 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", "Struts", 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 org.apache.struts.action; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.config.ExceptionConfig; import org.apache.struts.util.AppException; public class ExceptionHandler { /** * Handle the exception. * Return the <code>ActionForward</code> instance (if any) returned by * the called <code>ExceptionHandler</code>. * * @param ex The exception to handle * @param ae The ExceptionConfig corresponding to the exception * @param mapping The ActionMapping we are processing * @param formInstance The ActionForm we are processing * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception ServletException if a servlet exception occurs * * @since Struts 1.1 */ public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionForward forward = null; ActionError error = null; String property = null; String path; // Build the forward from the exception mapping if it exists // or from the form input if (ae.getPath() != null) { path = ae.getPath(); } else { path = mapping.getInput(); } // Generate the forward forward = new ActionForward(path); // Figure out the error if (ex instanceof AppException) { error = ((AppException) ex).getError(); property = ((AppException) ex).getProperty(); } else { error = new ActionError(ae.getKey()); property = error.getKey(); } // Store the exception + request.setAttribute(Action.EXCEPTION_KEY, ex); storeException(request, property, error, forward, ae.getScope()); return forward; } /** * Default implementation for handling an <b>ActionError</b> generated * from an Exception during <b>Action</b> delegation. The default * implementation is to set an attribute of the request or session, as * defined by the scope provided (the scope from the exception mapping). An * <b>ActionErrors</b> instance is created, the error is added to the collection * and the collection is set under the Action.ERROR_KEY. * * @param request - The request we are handling * @param property - The property name to use for this error * @param error - The error generated from the exception mapping * @param forward - The forward generated from the input path (from the form or exception mapping) * @param scope - The scope of the exception mapping. * */ protected void storeException(HttpServletRequest request, String property, ActionError error, ActionForward forward, String scope) { ActionErrors errors = new ActionErrors(); errors.add(property, error); if ("request".equals(scope)){ request.setAttribute(Action.ERROR_KEY, errors); } else { request.getSession().setAttribute(Action.ERROR_KEY, errors); } } }
true
true
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionForward forward = null; ActionError error = null; String property = null; String path; // Build the forward from the exception mapping if it exists // or from the form input if (ae.getPath() != null) { path = ae.getPath(); } else { path = mapping.getInput(); } // Generate the forward forward = new ActionForward(path); // Figure out the error if (ex instanceof AppException) { error = ((AppException) ex).getError(); property = ((AppException) ex).getProperty(); } else { error = new ActionError(ae.getKey()); property = error.getKey(); } // Store the exception storeException(request, property, error, forward, ae.getScope()); return forward; }
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException { ActionForward forward = null; ActionError error = null; String property = null; String path; // Build the forward from the exception mapping if it exists // or from the form input if (ae.getPath() != null) { path = ae.getPath(); } else { path = mapping.getInput(); } // Generate the forward forward = new ActionForward(path); // Figure out the error if (ex instanceof AppException) { error = ((AppException) ex).getError(); property = ((AppException) ex).getProperty(); } else { error = new ActionError(ae.getKey()); property = error.getKey(); } // Store the exception request.setAttribute(Action.EXCEPTION_KEY, ex); storeException(request, property, error, forward, ae.getScope()); return forward; }
diff --git a/src/org/eclipse/jface/resource/JFaceResources.java b/src/org/eclipse/jface/resource/JFaceResources.java index 46501f5f..91d18989 100644 --- a/src/org/eclipse/jface/resource/JFaceResources.java +++ b/src/org/eclipse/jface/resource/JFaceResources.java @@ -1,578 +1,580 @@ /******************************************************************************* * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.resource; import java.net.URL; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.internal.JFaceActivator; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.wizard.Wizard; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.osgi.framework.Bundle; /** * Utility methods to access JFace-specific resources. * <p> * All methods declared on this class are static. This class cannot be * instantiated. * </p> * <p> * The following global state is also maintained by this class: * <ul> * <li>a font registry</li> * <li>a color registry</li> * <li>an image registry</li> * <li>a resource bundle</li> * </ul> * </p> */ public class JFaceResources { /** * The path to the icons in the resources. */ private final static String ICONS_PATH = "$nl$/icons/full/";//$NON-NLS-1$ /** * Map of Display onto DeviceResourceManager. Holds all the resources for * the associated display. */ private static final Map registries = new HashMap(); /** * The symbolic font name for the banner font (value * <code>"org.eclipse.jface.bannerfont"</code>). */ public static final String BANNER_FONT = "org.eclipse.jface.bannerfont"; //$NON-NLS-1$ /** * The JFace resource bundle; eagerly initialized. */ private static final ResourceBundle bundle = ResourceBundle .getBundle("org.eclipse.jface.messages"); //$NON-NLS-1$ /** * The JFace color registry; <code>null</code> until lazily initialized or * explicitly set. */ private static ColorRegistry colorRegistry; /** * The symbolic font name for the standard font (value * <code>"org.eclipse.jface.defaultfont"</code>). */ public static final String DEFAULT_FONT = "org.eclipse.jface.defaultfont"; //$NON-NLS-1$ /** * The symbolic font name for the dialog font (value * <code>"org.eclipse.jface.dialogfont"</code>). */ public static final String DIALOG_FONT = "org.eclipse.jface.dialogfont"; //$NON-NLS-1$ /** * The JFace font registry; <code>null</code> until lazily initialized or * explicitly set. */ private static FontRegistry fontRegistry = null; /** * The symbolic font name for the header font (value * <code>"org.eclipse.jface.headerfont"</code>). */ public static final String HEADER_FONT = "org.eclipse.jface.headerfont"; //$NON-NLS-1$ /** * The JFace image registry; <code>null</code> until lazily initialized. */ private static ImageRegistry imageRegistry = null; /** * The symbolic font name for the text font (value * <code>"org.eclipse.jface.textfont"</code>). */ public static final String TEXT_FONT = "org.eclipse.jface.textfont"; //$NON-NLS-1$ /** * The symbolic font name for the viewer font (value * <code>"org.eclipse.jface.viewerfont"</code>). * * @deprecated This font is not in use */ public static final String VIEWER_FONT = "org.eclipse.jface.viewerfont"; //$NON-NLS-1$ /** * The symbolic font name for the window font (value * <code>"org.eclipse.jface.windowfont"</code>). * * @deprecated This font is not in use */ public static final String WINDOW_FONT = "org.eclipse.jface.windowfont"; //$NON-NLS-1$ /** * Returns the formatted message for the given key in JFace's resource * bundle. * * @param key * the resource name * @param args * the message arguments * @return the string */ public static String format(String key, Object[] args) { return MessageFormat.format(getString(key), args); } /** * Returns the JFace's banner font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.BANNER_FONT) * </pre> * * @return the font */ public static Font getBannerFont() { return getFontRegistry().get(BANNER_FONT); } /** * Returns the resource bundle for JFace itself. The resouble bundle is * obtained from * <code>ResourceBundle.getBundle("org.eclipse.jface.jface_nls")</code>. * <p> * Note that several static convenience methods are also provided on this * class for directly accessing resources in this bundle. * </p> * * @return the resource bundle */ public static ResourceBundle getBundle() { return bundle; } /** * Returns the color registry for JFace itself. * <p> * * @return the <code>ColorRegistry</code>. * @since 3.0 */ public static ColorRegistry getColorRegistry() { if (colorRegistry == null) { colorRegistry = new ColorRegistry(); } return colorRegistry; } /** * Returns the global resource manager for the given display * * @since 3.1 * * @param toQuery * display to query * @return the global resource manager for the given display */ public static ResourceManager getResources(final Display toQuery) { ResourceManager reg = (ResourceManager) registries.get(toQuery); if (reg == null) { final DeviceResourceManager mgr = new DeviceResourceManager(toQuery); reg = mgr; registries.put(toQuery, reg); toQuery.disposeExec(new Runnable() { /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ public void run() { mgr.dispose(); registries.remove(toQuery); } }); } return reg; } /** * Returns the ResourceManager for the current display. May only be called * from a UI thread. * * @since 3.1 * * @return the global ResourceManager for the current display */ public static ResourceManager getResources() { return getResources(Display.getCurrent()); } /** * Returns JFace's standard font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.DEFAULT_FONT) * </pre> * * @return the font */ public static Font getDefaultFont() { return getFontRegistry().defaultFont(); } /** * Returns the descriptor for JFace's standard font. Convenience method * equivalent to * * <pre> * JFaceResources.getFontRegistry().getDescriptor(JFaceResources.DEFAULT_FONT) * </pre> * * @return the font * @since 3.3 */ public static FontDescriptor getDefaultFontDescriptor() { return getFontRegistry().defaultFontDescriptor(); } /** * Returns the JFace's dialog font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.DIALOG_FONT) * </pre> * * @return the font */ public static Font getDialogFont() { return getFontRegistry().get(DIALOG_FONT); } /** * Returns the descriptor for JFace's dialog font. Convenience method * equivalent to * * <pre> * JFaceResources.getFontRegistry().getDescriptor(JFaceResources.DIALOG_FONT) * </pre> * * @return the font * @since 3.3 */ public static FontDescriptor getDialogFontDescriptor() { return getFontRegistry().getDescriptor(DIALOG_FONT); } /** * Returns the font in JFace's font registry with the given symbolic font * name. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(symbolicName) * </pre> * * If an error occurs, return the default font. * * @param symbolicName * the symbolic font name * @return the font */ public static Font getFont(String symbolicName) { return getFontRegistry().get(symbolicName); } /** * Returns the font descriptor for in JFace's font registry with the given * symbolic name. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().getDescriptor(symbolicName) * </pre> * * If an error occurs, return the default font. * * @param symbolicName * the symbolic font name * @return the font descriptor (never null) * @since 3.3 */ public static FontDescriptor getFontDescriptor(String symbolicName) { return getFontRegistry().getDescriptor(symbolicName); } /** * Returns the font registry for JFace itself. If the value has not been * established by an earlier call to <code>setFontRegistry</code>, is it * initialized to * <code>new FontRegistry("org.eclipse.jface.resource.jfacefonts")</code>. * <p> * Note that several static convenience methods are also provided on this * class for directly accessing JFace's standard fonts. * </p> * * @return the JFace font registry */ public static FontRegistry getFontRegistry() { if (fontRegistry == null) { fontRegistry = new FontRegistry( "org.eclipse.jface.resource.jfacefonts"); //$NON-NLS-1$ } return fontRegistry; } /** * Returns the JFace's header font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.HEADER_FONT) * </pre> * * @return the font */ public static Font getHeaderFont() { return getFontRegistry().get(HEADER_FONT); } /** * Returns the descriptor for JFace's header font. Convenience method * equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.HEADER_FONT) * </pre> * * @return the font descriptor (never null) * @since 3.3 */ public static FontDescriptor getHeaderFontDescriptor() { return getFontRegistry().getDescriptor(HEADER_FONT); } /** * Returns the image in JFace's image registry with the given key, or * <code>null</code> if none. Convenience method equivalent to * * <pre> * JFaceResources.getImageRegistry().get(key) * </pre> * * @param key * the key * @return the image, or <code>null</code> if none */ public static Image getImage(String key) { return getImageRegistry().get(key); } /** * Returns the image registry for JFace itself. * <p> * Note that the static convenience method <code>getImage</code> is also * provided on this class. * </p> * * @return the JFace image registry */ public static ImageRegistry getImageRegistry() { if (imageRegistry == null) { imageRegistry = new ImageRegistry( getResources(Display.getCurrent())); initializeDefaultImages(); } return imageRegistry; } /** * Initialize default images in JFace's image registry. * */ private static void initializeDefaultImages() { Object bundle = null; try { bundle = JFaceActivator.getBundle(); } catch (NoClassDefFoundError exception) { // Test to see if OSGI is present } declareImage(bundle, Wizard.DEFAULT_IMAGE, ICONS_PATH + "page.gif", //$NON-NLS-1$ Wizard.class, "images/page.gif"); //$NON-NLS-1$ // register default images for dialogs declareImage(bundle, Dialog.DLG_IMG_MESSAGE_INFO, ICONS_PATH + "message_info.gif", Dialog.class, "images/message_info.gif"); //$NON-NLS-1$ //$NON-NLS-2$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_WARNING, ICONS_PATH + "message_warning.gif", Dialog.class, //$NON-NLS-1$ "images/message_warning.gif"); //$NON-NLS-1$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_ERROR, ICONS_PATH + "message_error.gif", Dialog.class, "images/message_error.gif");//$NON-NLS-1$ //$NON-NLS-2$ + declareImage(bundle, Dialog.DLG_IMG_HELP, ICONS_PATH + + "help.gif", Dialog.class, "images/help.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, TitleAreaDialog.DLG_IMG_TITLE_BANNER, ICONS_PATH + "title_banner.png", TitleAreaDialog.class, "images/title_banner.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, PreferenceDialog.PREF_DLG_TITLE_IMG, ICONS_PATH + "pref_dialog_title.gif", PreferenceDialog.class, "images/pref_dialog_title.gif");//$NON-NLS-1$ //$NON-NLS-2$ } /** * Declares a JFace image given the path of the image file (relative to the * JFace plug-in). This is a helper method that creates the image descriptor * and passes it to the main <code>declareImage</code> method. * * @param bundle * the {@link Bundle} or <code>null</code> of the Bundle cannot * be found * @param key * the symbolic name of the image * @param path * the path of the image file relative to the base of the * workbench plug-ins install directory * @param fallback * the {@link Class} where the fallback implementation of the * image is relative to * @param fallbackPath * the path relative to the fallback {@link Class} * */ private static final void declareImage(Object bundle, String key, String path, Class fallback, String fallbackPath) { ImageDescriptor descriptor = null; if (bundle != null) { URL url = FileLocator.find((Bundle) bundle, new Path(path), null); if (url != null) descriptor = ImageDescriptor.createFromURL(url); } // If we failed then load from the backup file if (descriptor == null) descriptor = ImageDescriptor.createFromFile(fallback, fallbackPath); imageRegistry.put(key, descriptor); } /** * Returns the resource object with the given key in JFace's resource * bundle. If there isn't any value under the given key, the key is * returned. * * @param key * the resource name * @return the string */ public static String getString(String key) { try { return bundle.getString(key); } catch (MissingResourceException e) { return key; } } /** * Returns a list of string values corresponding to the given list of keys. * The lookup is done with <code>getString</code>. The values are in the * same order as the keys. * * @param keys * a list of keys * @return a list of corresponding string values */ public static String[] getStrings(String[] keys) { Assert.isNotNull(keys); int length = keys.length; String[] result = new String[length]; for (int i = 0; i < length; i++) { result[i] = getString(keys[i]); } return result; } /** * Returns JFace's text font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT) * </pre> * * @return the font */ public static Font getTextFont() { return getFontRegistry().get(TEXT_FONT); } /** * Returns the descriptor for JFace's text font. Convenience method * equivalent to * * <pre> * JFaceResources.getFontRegistry().getDescriptor(JFaceResources.TEXT_FONT) * </pre> * * @return the font descriptor (never null) * @since 3.3 */ public static FontDescriptor getTextFontDescriptor() { return getFontRegistry().getDescriptor(TEXT_FONT); } /** * Returns JFace's viewer font. Convenience method equivalent to * * <pre> * JFaceResources.getFontRegistry().get(JFaceResources.VIEWER_FONT) * </pre> * * @return the font * @deprecated This font is not in use */ public static Font getViewerFont() { return getFontRegistry().get(VIEWER_FONT); } /** * Sets JFace's font registry to the given value. This method may only be * called once; the call must occur before * <code>JFaceResources.getFontRegistry</code> is invoked (either directly * or indirectly). * * @param registry * a font registry */ public static void setFontRegistry(FontRegistry registry) { Assert.isTrue(fontRegistry == null, "Font registry can only be set once."); //$NON-NLS-1$ fontRegistry = registry; } /* * (non-Javadoc) Declare a private constructor to block instantiation. */ private JFaceResources() { // no-op } }
true
true
private static void initializeDefaultImages() { Object bundle = null; try { bundle = JFaceActivator.getBundle(); } catch (NoClassDefFoundError exception) { // Test to see if OSGI is present } declareImage(bundle, Wizard.DEFAULT_IMAGE, ICONS_PATH + "page.gif", //$NON-NLS-1$ Wizard.class, "images/page.gif"); //$NON-NLS-1$ // register default images for dialogs declareImage(bundle, Dialog.DLG_IMG_MESSAGE_INFO, ICONS_PATH + "message_info.gif", Dialog.class, "images/message_info.gif"); //$NON-NLS-1$ //$NON-NLS-2$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_WARNING, ICONS_PATH + "message_warning.gif", Dialog.class, //$NON-NLS-1$ "images/message_warning.gif"); //$NON-NLS-1$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_ERROR, ICONS_PATH + "message_error.gif", Dialog.class, "images/message_error.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, TitleAreaDialog.DLG_IMG_TITLE_BANNER, ICONS_PATH + "title_banner.png", TitleAreaDialog.class, "images/title_banner.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, PreferenceDialog.PREF_DLG_TITLE_IMG, ICONS_PATH + "pref_dialog_title.gif", PreferenceDialog.class, "images/pref_dialog_title.gif");//$NON-NLS-1$ //$NON-NLS-2$ }
private static void initializeDefaultImages() { Object bundle = null; try { bundle = JFaceActivator.getBundle(); } catch (NoClassDefFoundError exception) { // Test to see if OSGI is present } declareImage(bundle, Wizard.DEFAULT_IMAGE, ICONS_PATH + "page.gif", //$NON-NLS-1$ Wizard.class, "images/page.gif"); //$NON-NLS-1$ // register default images for dialogs declareImage(bundle, Dialog.DLG_IMG_MESSAGE_INFO, ICONS_PATH + "message_info.gif", Dialog.class, "images/message_info.gif"); //$NON-NLS-1$ //$NON-NLS-2$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_WARNING, ICONS_PATH + "message_warning.gif", Dialog.class, //$NON-NLS-1$ "images/message_warning.gif"); //$NON-NLS-1$ declareImage(bundle, Dialog.DLG_IMG_MESSAGE_ERROR, ICONS_PATH + "message_error.gif", Dialog.class, "images/message_error.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage(bundle, Dialog.DLG_IMG_HELP, ICONS_PATH + "help.gif", Dialog.class, "images/help.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, TitleAreaDialog.DLG_IMG_TITLE_BANNER, ICONS_PATH + "title_banner.png", TitleAreaDialog.class, "images/title_banner.gif");//$NON-NLS-1$ //$NON-NLS-2$ declareImage( bundle, PreferenceDialog.PREF_DLG_TITLE_IMG, ICONS_PATH + "pref_dialog_title.gif", PreferenceDialog.class, "images/pref_dialog_title.gif");//$NON-NLS-1$ //$NON-NLS-2$ }
diff --git a/src/impl/com/sun/ws/rest/impl/uri/rules/BaseRule.java b/src/impl/com/sun/ws/rest/impl/uri/rules/BaseRule.java index c0ad97a15..b34ca69ad 100644 --- a/src/impl/com/sun/ws/rest/impl/uri/rules/BaseRule.java +++ b/src/impl/com/sun/ws/rest/impl/uri/rules/BaseRule.java @@ -1,53 +1,53 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License("CDDL") (the "License"). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at: * https://jersey.dev.java.net/license.txt * See the License for the specific language governing permissions and * limitations under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each * file and include the License file at: * https://jersey.dev.java.net/license.txt * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" */ package com.sun.ws.rest.impl.uri.rules; import com.sun.ws.rest.api.uri.UriTemplate; import com.sun.ws.rest.spi.uri.rules.UriRule; import com.sun.ws.rest.spi.uri.rules.UriRuleContext; /** * Abstract class for a rule that manages capturing group names. * * @author [email protected] */ public abstract class BaseRule implements UriRule { private final UriTemplate template; public BaseRule(UriTemplate template) { - assert template != template; + assert template != null; this.template = template; } /** * Set the URI temaplte values. */ protected final void setTemplateValues(UriRuleContext context) { context.setTemplateValues(template.getTemplateVariables()); } protected final UriTemplate getTemplate() { return template; } }
true
true
public BaseRule(UriTemplate template) { assert template != template; this.template = template; }
public BaseRule(UriTemplate template) { assert template != null; this.template = template; }
diff --git a/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/formfield/FormFieldExpressionProvider.java b/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/formfield/FormFieldExpressionProvider.java index 5abeae8202..4f5fdba390 100644 --- a/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/formfield/FormFieldExpressionProvider.java +++ b/bundles/plugins/org.bonitasoft.studio.expression.editor/src/org/bonitasoft/studio/expression/editor/formfield/FormFieldExpressionProvider.java @@ -1,245 +1,246 @@ /** * Copyright (C) 2009 BonitaSoft S.A. * BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble * 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.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.expression.editor.formfield; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bonitasoft.engine.bpm.document.DocumentValue; import org.bonitasoft.studio.common.ExpressionConstants; import org.bonitasoft.studio.common.emf.tools.ModelHelper; import org.bonitasoft.studio.expression.editor.i18n.Messages; import org.bonitasoft.studio.expression.editor.provider.IExpressionEditor; import org.bonitasoft.studio.expression.editor.provider.IExpressionProvider; import org.bonitasoft.studio.model.expression.Expression; import org.bonitasoft.studio.model.expression.ExpressionFactory; import org.bonitasoft.studio.model.form.Duplicable; import org.bonitasoft.studio.model.form.FileWidget; import org.bonitasoft.studio.model.form.Form; import org.bonitasoft.studio.model.form.FormButton; import org.bonitasoft.studio.model.form.FormField; import org.bonitasoft.studio.model.form.Group; import org.bonitasoft.studio.model.form.NextFormButton; import org.bonitasoft.studio.model.form.SubmitFormButton; import org.bonitasoft.studio.model.form.TextFormField; import org.bonitasoft.studio.model.form.Widget; import org.bonitasoft.studio.model.form.WidgetDependency; import org.bonitasoft.studio.model.process.AbstractPageFlow; import org.bonitasoft.studio.model.process.PageFlow; import org.bonitasoft.studio.model.process.ProcessPackage; import org.bonitasoft.studio.model.process.RecapFlow; import org.bonitasoft.studio.model.process.ViewPageFlow; import org.bonitasoft.studio.pics.Pics; import org.bonitasoft.studio.pics.PicsConstants; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.edit.provider.ComposedAdapterFactory; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.swt.graphics.Image; /** * @author Romain Bioteau * */ public class FormFieldExpressionProvider implements IExpressionProvider { private final ComposedAdapterFactory adapterFactory; private final AdapterFactoryLabelProvider adapterLabelProvider; private boolean addContingentFields = true; public FormFieldExpressionProvider(){ adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); adapterLabelProvider = new AdapterFactoryLabelProvider(adapterFactory) ; } public FormFieldExpressionProvider(boolean addContingentFields){ this(); this.addContingentFields = addContingentFields; } public Set<Expression> getExpressions(EObject context) { Set<Expression> result = new HashSet<Expression>() ; EObject relevantParent = getRelevantParent(context) ; if (relevantParent instanceof Widget) { result.add(createExpression((Widget) relevantParent) ) ; if(addContingentFields){ for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){ if(dep.getWidget()!=null){ result.add(createExpression(dep.getWidget())) ; } } } // for the Submit button only, add fields of other widgets if(relevantParent instanceof SubmitFormButton){ - if(relevantParent.eContainer()!= null && relevantParent.eContainer() instanceof Form){ + if(relevantParent.eContainer()!= null && + (relevantParent.eContainer() instanceof Form || relevantParent.eContainer() instanceof Group)){ Form f = ModelHelper.getParentForm(relevantParent); for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof Group){ result.add( createExpression(w) ) ; } } } } //Add all widgets from the pageflow not in the same form final AbstractPageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent); if (pageFlow != null ) { List<? extends Form> forms= getForms(pageFlow, ModelHelper.getForm((Widget) relevantParent)); Form parentForm = ModelHelper.getParentForm(relevantParent); for (Form f : forms){ if(!f.equals(parentForm)){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if (relevantParent instanceof Form && relevantParent.eContainer() != null) { if(relevantParent.eContainer() instanceof AbstractPageFlow){ // get all fields from pageflow final AbstractPageFlow pageFlow = (AbstractPageFlow) relevantParent.eContainer(); if(pageFlow != null){ List<? extends Form> forms= getForms(pageFlow, (Form) relevantParent); for (Form f : forms){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof FormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if(relevantParent instanceof AbstractPageFlow){ // get all fields from pageflow if(relevantParent instanceof PageFlow){ if(relevantParent != null){ for (Form f : ((PageFlow) relevantParent).getForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } if(relevantParent instanceof ViewPageFlow){ for (Form f : ((ViewPageFlow) relevantParent).getViewForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } if(relevantParent instanceof RecapFlow){ for (Form f : ((RecapFlow) relevantParent).getRecapForms()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } } } return result; } private List<? extends Form> getForms(AbstractPageFlow pageFlow, Form form) { EStructuralFeature eContainingFeature = form.eContainingFeature(); if(ProcessPackage.Literals.PAGE_FLOW__FORM.equals(eContainingFeature)){ return ((PageFlow) pageFlow).getForm(); } else if(ProcessPackage.Literals.VIEW_PAGE_FLOW__VIEW_FORM.equals(eContainingFeature)){ return ((ViewPageFlow) pageFlow).getViewForm(); } else if(ProcessPackage.Literals.RECAP_FLOW__RECAP_FORMS.equals(eContainingFeature)){ return ((RecapFlow) pageFlow).getRecapForms(); } return Collections.emptyList(); } private EObject getRelevantParent(EObject context) { EObject parent = context ; while(parent != null && (!(parent instanceof Form) && !(parent instanceof Widget)) && !(parent instanceof PageFlow)){ parent = parent.eContainer() ; } return parent; } private Expression createExpression(Widget w) { Expression exp = ExpressionFactory.eINSTANCE.createExpression() ; exp.setType(getExpressionType()) ; exp.setContent("field_"+w.getName()) ; exp.setName("field_"+w.getName()) ; if(w instanceof Duplicable && ((Duplicable) w).isDuplicate()){ exp.setReturnType(List.class.getName()) ; }else{ if(w instanceof TextFormField && w.getReturnTypeModifier() != null ){ exp.setReturnType(w.getReturnTypeModifier()) ; }else{ if(w instanceof FileWidget){ exp.setReturnType(DocumentValue.class.getName()); }else{ exp.setReturnType(w.getAssociatedReturnType()) ; } } } Widget copy = EcoreUtil.copy(w); copy.getDependOn().clear(); exp.getReferencedElements().add(copy) ; return exp; } public String getExpressionType() { return ExpressionConstants.FORM_FIELD_TYPE; } public Image getIcon(Expression expression) { if(expression.getReferencedElements().isEmpty()){ return null ; } return adapterLabelProvider.getImage(expression.getReferencedElements().get(0)) ; } public String getProposalLabel(Expression expression) { return expression.getName() ; } public boolean isRelevantFor(EObject context) { return context instanceof EObject; } public Image getTypeIcon() { return Pics.getImage(PicsConstants.form); } public String getTypeLabel() { return Messages.formFieldTypeLabel; } public IExpressionEditor getExpressionEditor(Expression expression,EObject context) { return new FormFieldExpressionEditor(); } }
true
true
public Set<Expression> getExpressions(EObject context) { Set<Expression> result = new HashSet<Expression>() ; EObject relevantParent = getRelevantParent(context) ; if (relevantParent instanceof Widget) { result.add(createExpression((Widget) relevantParent) ) ; if(addContingentFields){ for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){ if(dep.getWidget()!=null){ result.add(createExpression(dep.getWidget())) ; } } } // for the Submit button only, add fields of other widgets if(relevantParent instanceof SubmitFormButton){ if(relevantParent.eContainer()!= null && relevantParent.eContainer() instanceof Form){ Form f = ModelHelper.getParentForm(relevantParent); for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof Group){ result.add( createExpression(w) ) ; } } } } //Add all widgets from the pageflow not in the same form final AbstractPageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent); if (pageFlow != null ) { List<? extends Form> forms= getForms(pageFlow, ModelHelper.getForm((Widget) relevantParent)); Form parentForm = ModelHelper.getParentForm(relevantParent); for (Form f : forms){ if(!f.equals(parentForm)){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if (relevantParent instanceof Form && relevantParent.eContainer() != null) { if(relevantParent.eContainer() instanceof AbstractPageFlow){ // get all fields from pageflow final AbstractPageFlow pageFlow = (AbstractPageFlow) relevantParent.eContainer(); if(pageFlow != null){ List<? extends Form> forms= getForms(pageFlow, (Form) relevantParent); for (Form f : forms){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof FormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if(relevantParent instanceof AbstractPageFlow){ // get all fields from pageflow if(relevantParent instanceof PageFlow){ if(relevantParent != null){ for (Form f : ((PageFlow) relevantParent).getForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } if(relevantParent instanceof ViewPageFlow){ for (Form f : ((ViewPageFlow) relevantParent).getViewForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } if(relevantParent instanceof RecapFlow){ for (Form f : ((RecapFlow) relevantParent).getRecapForms()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } } } return result; }
public Set<Expression> getExpressions(EObject context) { Set<Expression> result = new HashSet<Expression>() ; EObject relevantParent = getRelevantParent(context) ; if (relevantParent instanceof Widget) { result.add(createExpression((Widget) relevantParent) ) ; if(addContingentFields){ for(WidgetDependency dep : ((Widget) relevantParent).getDependOn()){ if(dep.getWidget()!=null){ result.add(createExpression(dep.getWidget())) ; } } } // for the Submit button only, add fields of other widgets if(relevantParent instanceof SubmitFormButton){ if(relevantParent.eContainer()!= null && (relevantParent.eContainer() instanceof Form || relevantParent.eContainer() instanceof Group)){ Form f = ModelHelper.getParentForm(relevantParent); for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof Group){ result.add( createExpression(w) ) ; } } } } //Add all widgets from the pageflow not in the same form final AbstractPageFlow pageFlow = ModelHelper.getPageFlow((Widget) relevantParent); if (pageFlow != null ) { List<? extends Form> forms= getForms(pageFlow, ModelHelper.getForm((Widget) relevantParent)); Form parentForm = ModelHelper.getParentForm(relevantParent); for (Form f : forms){ if(!f.equals(parentForm)){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if (relevantParent instanceof Form && relevantParent.eContainer() != null) { if(relevantParent.eContainer() instanceof AbstractPageFlow){ // get all fields from pageflow final AbstractPageFlow pageFlow = (AbstractPageFlow) relevantParent.eContainer(); if(pageFlow != null){ List<? extends Form> forms= getForms(pageFlow, (Form) relevantParent); for (Form f : forms){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof FormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } }else if(relevantParent instanceof AbstractPageFlow){ // get all fields from pageflow if(relevantParent instanceof PageFlow){ if(relevantParent != null){ for (Form f : ((PageFlow) relevantParent).getForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } if(relevantParent instanceof ViewPageFlow){ for (Form f : ((ViewPageFlow) relevantParent).getViewForm()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } if(relevantParent instanceof RecapFlow){ for (Form f : ((RecapFlow) relevantParent).getRecapForms()){ for (Widget w : ModelHelper.getAllAccessibleWidgetInsideForm(f)) { if (w instanceof FormField || w instanceof NextFormButton || w instanceof Group){ result.add( createExpression(w) ) ; } } } } } } } return result; }
diff --git a/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/layout/GridLayoutPattern.java b/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/layout/GridLayoutPattern.java index e1f0ec85c..c07b6668c 100644 --- a/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/layout/GridLayoutPattern.java +++ b/qcadoo-view/src/main/java/com/qcadoo/view/internal/components/layout/GridLayoutPattern.java @@ -1,224 +1,227 @@ /** * *************************************************************************** * Copyright (c) 2010 Qcadoo Limited * Project: Qcadoo Framework * Version: 0.4.1 * * This file is part of Qcadoo. * * Qcadoo 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *************************************************************************** */ package com.qcadoo.view.internal.components.layout; import java.util.Locale; import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.google.common.base.Preconditions; import com.qcadoo.view.internal.ComponentDefinition; import com.qcadoo.view.internal.api.ComponentPattern; import com.qcadoo.view.internal.xml.ViewDefinitionParser; import com.qcadoo.view.internal.xml.ViewDefinitionParserNodeException; public class GridLayoutPattern extends AbstractLayoutPattern { private static final String JS_OBJECT = "QCD.components.containers.layout.GridLayout"; private static final String JSP_PATH = "containers/layout/gridLayout.jsp"; private static final String JS_PATH = "/qcadooView/public/js/crud/qcd/components/containers/layout/gridLayout.js"; private GridLayoutCell[][] cells; private boolean fixedRowHeight = true; public GridLayoutPattern(final ComponentDefinition componentDefinition) { super(componentDefinition); } @Override public void parse(final Node componentNode, final ViewDefinitionParser parser) throws ViewDefinitionParserNodeException { super.parse(componentNode, parser); Integer columns = getIntAttribute(componentNode, "columns", parser); Integer rows = getIntAttribute(componentNode, "rows", parser); fixedRowHeight = parser.getBooleanAttribute(componentNode, "fixedRowHeight", true); - parser.checkState(columns != null, componentNode, "columns nod definied"); - parser.checkState(rows != null, componentNode, "rows nod definied"); + parser.checkState(columns != null, componentNode, "columns not definied"); + parser.checkState(rows != null, componentNode, "rows not definied"); + if (rows == null) { + throw new IllegalStateException("TEST"); + } cells = new GridLayoutCell[rows][]; for (int row = 0; row < cells.length; row++) { cells[row] = new GridLayoutCell[columns]; for (int col = 0; col < cells[row].length; col++) { cells[row][col] = new GridLayoutCell(); } } NodeList childNodes = componentNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } parser.checkState("layoutElement".equals(child.getNodeName()), child, "gridlayout can contains only layoutElements"); Integer column = getIntAttribute(child, "column", parser); Integer row = getIntAttribute(child, "row", parser); GridLayoutCell cell = createGridLayoutCell(child, parser); try { insertCell(cell, column, row); } catch (IllegalStateException e) { throw new ViewDefinitionParserNodeException(child, e); } } if (parser.getBooleanAttribute(componentNode, "hasBorders", true)) { updateBorders(); } } private void updateBorders() { int colsNumber = cells[0].length; boolean[] bordersArray = new boolean[colsNumber]; for (int i = 0; i < colsNumber; i++) { bordersArray[i] = false; } for (int row = 0; row < cells.length; row++) { for (int col = 0; col < cells[row].length; col++) { if (cells[row][col].getComponents() != null) { bordersArray[col + cells[row][col].getColspan() - 1] = true; } } } // remove last border for (int i = colsNumber - 1; i >= 0; i--) { if (bordersArray[i]) { bordersArray[i] = false; break; } } for (int row = 0; row < cells.length; row++) { for (int col = 0; col < cells[row].length; col++) { if (bordersArray[col + cells[row][col].getColspan() - 1]) { cells[row][col].setRightBorder(true); } } } } private GridLayoutCell createGridLayoutCell(final Node child, final ViewDefinitionParser parser) throws ViewDefinitionParserNodeException { Integer colspan = getIntAttribute(child, "width", parser); Integer rowspan = getIntAttribute(child, "height", parser); ComponentPattern elementComponent = null; NodeList elementComponentNodes = child.getChildNodes(); GridLayoutCell cell = new GridLayoutCell(); for (int elementComponentNodesIter = 0; elementComponentNodesIter < elementComponentNodes.getLength(); elementComponentNodesIter++) { Node elementComponentNode = elementComponentNodes.item(elementComponentNodesIter); if (elementComponentNode.getNodeType() != Node.ELEMENT_NODE) { continue; } parser.checkState("component".equals(elementComponentNode.getNodeName()), elementComponentNode, "layoutElement can contains only components"); elementComponent = parser.parseComponent(elementComponentNode, this); this.addChild(elementComponent); cell.addComponent(elementComponent); } if (colspan != null) { cell.setColspan(colspan); } if (rowspan != null) { cell.setRowspan(rowspan); } return cell; } private void insertCell(final GridLayoutCell cell, final int column, final int row) { Preconditions.checkState(column > 0, "column number less than zero"); Preconditions.checkState(row > 0, "row number less than zero"); Preconditions.checkState(column <= cells[0].length, "column number to large"); Preconditions.checkState(row <= cells.length, "row number to large"); Preconditions.checkState(column + cell.getColspan() - 1 <= cells[0].length, "width number to large"); Preconditions.checkState(row + cell.getRowspan() - 1 <= cells.length, "height number to large"); for (int rowIter = row; rowIter < row + cell.getRowspan(); rowIter++) { for (int colIter = column; colIter < column + cell.getColspan(); colIter++) { GridLayoutCell beforeCell = cells[rowIter - 1][colIter - 1]; Preconditions.checkState(beforeCell.isAvailable(), "cell [" + rowIter + "x" + colIter + "] is not available"); beforeCell.setAvailable(false); } } cells[row - 1][column - 1] = cell; } private Integer getIntAttribute(final Node node, final String attribute, final ViewDefinitionParser parser) throws ViewDefinitionParserNodeException { String valueStr = parser.getStringAttribute(node, attribute); if (valueStr == null) { return null; } try { return Integer.parseInt(valueStr); } catch (NumberFormatException e) { throw new ViewDefinitionParserNodeException(node, "value of attribute '" + attribute + "' is not a number"); } } @Override public final Map<String, Object> prepareView(final Locale locale) { Map<String, Object> model = super.prepareView(locale); model.put("cells", cells); return model; } @Override protected JSONObject getJsOptions(final Locale locale) throws JSONException { JSONObject json = new JSONObject(); json.put("colsNumber", cells[0].length); json.put("fixedRowHeight", fixedRowHeight); return json; } @Override public String getJspFilePath() { return JSP_PATH; } @Override public String getJsFilePath() { return JS_PATH; } @Override public String getJsObjectName() { return JS_OBJECT; } }
true
true
public void parse(final Node componentNode, final ViewDefinitionParser parser) throws ViewDefinitionParserNodeException { super.parse(componentNode, parser); Integer columns = getIntAttribute(componentNode, "columns", parser); Integer rows = getIntAttribute(componentNode, "rows", parser); fixedRowHeight = parser.getBooleanAttribute(componentNode, "fixedRowHeight", true); parser.checkState(columns != null, componentNode, "columns nod definied"); parser.checkState(rows != null, componentNode, "rows nod definied"); cells = new GridLayoutCell[rows][]; for (int row = 0; row < cells.length; row++) { cells[row] = new GridLayoutCell[columns]; for (int col = 0; col < cells[row].length; col++) { cells[row][col] = new GridLayoutCell(); } } NodeList childNodes = componentNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } parser.checkState("layoutElement".equals(child.getNodeName()), child, "gridlayout can contains only layoutElements"); Integer column = getIntAttribute(child, "column", parser); Integer row = getIntAttribute(child, "row", parser); GridLayoutCell cell = createGridLayoutCell(child, parser); try { insertCell(cell, column, row); } catch (IllegalStateException e) { throw new ViewDefinitionParserNodeException(child, e); } } if (parser.getBooleanAttribute(componentNode, "hasBorders", true)) { updateBorders(); } }
public void parse(final Node componentNode, final ViewDefinitionParser parser) throws ViewDefinitionParserNodeException { super.parse(componentNode, parser); Integer columns = getIntAttribute(componentNode, "columns", parser); Integer rows = getIntAttribute(componentNode, "rows", parser); fixedRowHeight = parser.getBooleanAttribute(componentNode, "fixedRowHeight", true); parser.checkState(columns != null, componentNode, "columns not definied"); parser.checkState(rows != null, componentNode, "rows not definied"); if (rows == null) { throw new IllegalStateException("TEST"); } cells = new GridLayoutCell[rows][]; for (int row = 0; row < cells.length; row++) { cells[row] = new GridLayoutCell[columns]; for (int col = 0; col < cells[row].length; col++) { cells[row][col] = new GridLayoutCell(); } } NodeList childNodes = componentNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() != Node.ELEMENT_NODE) { continue; } parser.checkState("layoutElement".equals(child.getNodeName()), child, "gridlayout can contains only layoutElements"); Integer column = getIntAttribute(child, "column", parser); Integer row = getIntAttribute(child, "row", parser); GridLayoutCell cell = createGridLayoutCell(child, parser); try { insertCell(cell, column, row); } catch (IllegalStateException e) { throw new ViewDefinitionParserNodeException(child, e); } } if (parser.getBooleanAttribute(componentNode, "hasBorders", true)) { updateBorders(); } }
diff --git a/tm-idea/org.textmapper.idea/src/org/textmapper/idea/lang/syntax/lexer/LapgLexerAdapter.java b/tm-idea/org.textmapper.idea/src/org/textmapper/idea/lang/syntax/lexer/LapgLexerAdapter.java index 5c7919d3..d73f791f 100644 --- a/tm-idea/org.textmapper.idea/src/org/textmapper/idea/lang/syntax/lexer/LapgLexerAdapter.java +++ b/tm-idea/org.textmapper.idea/src/org/textmapper/idea/lang/syntax/lexer/LapgLexerAdapter.java @@ -1,287 +1,287 @@ /** * Copyright (c) 2010-2012 Evgeny Gryaznov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package org.textmapper.idea.lang.syntax.lexer; import com.intellij.lexer.LexerBase; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import org.textmapper.tool.parser.TMLexer; import org.textmapper.tool.parser.TMLexer.LapgSymbol; import org.textmapper.tool.parser.TMLexer.Lexems; import java.io.IOException; import java.io.Reader; import java.io.StringReader; public class LapgLexerAdapter extends LexerBase implements LapgTokenTypes { private CharSequence myText; private TMLexer lexer; private LapgSymbol lexem; private int fDocumentLength; private int fTokenOffset; private int fTokenLength; private int fState; private IElementType current; public LapgLexerAdapter() { } @Override public void start(final CharSequence buffer, int startOffset, int endOffset, int initialState) { myText = buffer; fDocumentLength = endOffset; Reader reader = new StringReader(buffer.toString().substring(startOffset, endOffset)); try { if (lexer == null) { lexer = new IdeaLapgLexer(reader); } else { lexer.reset(reader); } } catch (IOException ex) { /* never happens */ } lexer.setOffset(startOffset); fTokenOffset = startOffset; lexer.setState(initialState); fState = initialState; fTokenLength = 0; lexem = null; current = null; } @Override public int getState() { locateToken(); return fState; } @Override public IElementType getTokenType() { locateToken(); return current; } @Override public int getTokenStart() { locateToken(); return fTokenOffset; } @Override public int getTokenEnd() { locateToken(); return fTokenOffset + fTokenLength; } @Override public void advance() { locateToken(); current = null; } @Override public CharSequence getBufferSequence() { return myText; } @Override public int getBufferEnd() { return fDocumentLength; } private void locateToken() { if (current == null) { current = nextToken(); } } public IElementType nextToken() { fTokenOffset += fTokenLength; if (lexem == null) { fState = lexer.getState(); readNext(); } if (fTokenOffset < lexem.offset) { fTokenLength = lexem.offset - fTokenOffset; return TokenType.BAD_CHARACTER; } int token = lexem.symbol; fTokenLength = lexem.endoffset - fTokenOffset; LapgSymbol currentLexem = lexem; lexem = null; switch (token) { case Lexems.code: return TOKEN_ACTION; case Lexems._skip: return WHITESPACE; case Lexems._skip_comment: return COMMENT; case Lexems.scon: return STRING; case Lexems.icon: return ICON; case Lexems.ID: return ID; case Lexems.regexp: return REGEXP; // operators case Lexems.PERCENT: return OP_PERCENT; case Lexems.COLONCOLONEQUAL: return OP_CCEQ; case Lexems.OR: return OP_OR; case Lexems.EQUAL: return OP_EQ; case Lexems.EQUALGREATER: return OP_EQGT; case Lexems.SEMICOLON: return OP_SEMICOLON; case Lexems.DOT: return OP_DOT; case Lexems.COMMA: return OP_COMMA; case Lexems.COLON: return OP_COLON; case Lexems.COLONCOLON: return OP_COLONCOLON; case Lexems.LSQUARE: return OP_LBRACKET; case Lexems.RSQUARE: return OP_RBRACKET; case Lexems.LPAREN: return OP_LPAREN; case Lexems.RPAREN: return OP_RPAREN; case Lexems.LCURLY: return OP_LCURLY; case Lexems.RCURLY: return OP_RCURLY; case Lexems.LESS: return OP_LT; case Lexems.GREATER: return OP_GT; case Lexems.MULT: return OP_STAR; case Lexems.PLUS: return OP_PLUS; case Lexems.PLUSEQUAL: return OP_PLUSEQ; case Lexems.QUESTIONMARK: return OP_QMARK; // case Lexems.MINUSGREATER: // return OP_ARROW; case Lexems.LPARENQUESTIONMARKEXCLAMATION: return OP_LPAREN_QMARK_EXCL; case Lexems.AMPERSAND: return OP_AND; case Lexems.ATSIGN: return OP_AT; // keywords case Lexems.Ltrue: return KW_TRUE; case Lexems.Lfalse: return KW_FALSE; case Lexems.Lseparator: return KW_SEPARATOR; case Lexems.Lprio: return KW_PRIO; case Lexems.Lshift: return KW_SHIFT; case Lexems.Lreduce: return KW_REDUCE; case Lexems.Linput: return KW_INPUT; case Lexems.Lleft: return KW_LEFT; case Lexems.Lright: return KW_RIGHT; case Lexems.Lnew: return KW_NEW; case Lexems.Lnonassoc: return KW_NONASSOC; case Lexems.Lnoeoi: return KW_NOEOI; case Lexems.Las: return KW_AS; case Lexems.Limport: return KW_IMPORT; case Lexems.Linline: return KW_INLINE; case Lexems.Lreturns: return KW_RETURNS; case Lexems.Linterface: return KW_INTERFACE; case Lexems.Lvoid: return KW_VOID; case Lexems.Llanguage: return KW_LANGUAGE; case Lexems.Llalr: return KW_LALR; case Lexems.Llexer: return KW_LEXER; case Lexems.Lparser: return KW_PARSER; // soft keywords without highlighting case Lexems.Lsoft: return KW_SOFT; case Lexems.Lclass: return KW_CLASS; case Lexems.Lspace: return KW_SPACE; } /* default, eoi */ lexem = currentLexem; assert lexem.symbol == Lexems.eoi; - if (lexem.endoffset < fDocumentLength) { + if (lexem.offset < fDocumentLength) { fTokenLength = fDocumentLength - fTokenOffset; lexem.offset = lexem.endoffset = fDocumentLength; return TEMPLATES; } return null; } private void readNext() { try { lexem = lexer.next(); } catch (IOException e) { /* never happens */ } } private static class IdeaLapgLexer extends TMLexer { public IdeaLapgLexer(Reader stream) throws IOException { super(stream, new ErrorReporter() { @Override public void error(int start, int end, int line, String s) { } }); } @Override protected boolean createToken(LapgSymbol lapg_n, int lexemIndex) throws IOException { super.createToken(lapg_n, lexemIndex); return true; } } }
true
true
public IElementType nextToken() { fTokenOffset += fTokenLength; if (lexem == null) { fState = lexer.getState(); readNext(); } if (fTokenOffset < lexem.offset) { fTokenLength = lexem.offset - fTokenOffset; return TokenType.BAD_CHARACTER; } int token = lexem.symbol; fTokenLength = lexem.endoffset - fTokenOffset; LapgSymbol currentLexem = lexem; lexem = null; switch (token) { case Lexems.code: return TOKEN_ACTION; case Lexems._skip: return WHITESPACE; case Lexems._skip_comment: return COMMENT; case Lexems.scon: return STRING; case Lexems.icon: return ICON; case Lexems.ID: return ID; case Lexems.regexp: return REGEXP; // operators case Lexems.PERCENT: return OP_PERCENT; case Lexems.COLONCOLONEQUAL: return OP_CCEQ; case Lexems.OR: return OP_OR; case Lexems.EQUAL: return OP_EQ; case Lexems.EQUALGREATER: return OP_EQGT; case Lexems.SEMICOLON: return OP_SEMICOLON; case Lexems.DOT: return OP_DOT; case Lexems.COMMA: return OP_COMMA; case Lexems.COLON: return OP_COLON; case Lexems.COLONCOLON: return OP_COLONCOLON; case Lexems.LSQUARE: return OP_LBRACKET; case Lexems.RSQUARE: return OP_RBRACKET; case Lexems.LPAREN: return OP_LPAREN; case Lexems.RPAREN: return OP_RPAREN; case Lexems.LCURLY: return OP_LCURLY; case Lexems.RCURLY: return OP_RCURLY; case Lexems.LESS: return OP_LT; case Lexems.GREATER: return OP_GT; case Lexems.MULT: return OP_STAR; case Lexems.PLUS: return OP_PLUS; case Lexems.PLUSEQUAL: return OP_PLUSEQ; case Lexems.QUESTIONMARK: return OP_QMARK; // case Lexems.MINUSGREATER: // return OP_ARROW; case Lexems.LPARENQUESTIONMARKEXCLAMATION: return OP_LPAREN_QMARK_EXCL; case Lexems.AMPERSAND: return OP_AND; case Lexems.ATSIGN: return OP_AT; // keywords case Lexems.Ltrue: return KW_TRUE; case Lexems.Lfalse: return KW_FALSE; case Lexems.Lseparator: return KW_SEPARATOR; case Lexems.Lprio: return KW_PRIO; case Lexems.Lshift: return KW_SHIFT; case Lexems.Lreduce: return KW_REDUCE; case Lexems.Linput: return KW_INPUT; case Lexems.Lleft: return KW_LEFT; case Lexems.Lright: return KW_RIGHT; case Lexems.Lnew: return KW_NEW; case Lexems.Lnonassoc: return KW_NONASSOC; case Lexems.Lnoeoi: return KW_NOEOI; case Lexems.Las: return KW_AS; case Lexems.Limport: return KW_IMPORT; case Lexems.Linline: return KW_INLINE; case Lexems.Lreturns: return KW_RETURNS; case Lexems.Linterface: return KW_INTERFACE; case Lexems.Lvoid: return KW_VOID; case Lexems.Llanguage: return KW_LANGUAGE; case Lexems.Llalr: return KW_LALR; case Lexems.Llexer: return KW_LEXER; case Lexems.Lparser: return KW_PARSER; // soft keywords without highlighting case Lexems.Lsoft: return KW_SOFT; case Lexems.Lclass: return KW_CLASS; case Lexems.Lspace: return KW_SPACE; } /* default, eoi */ lexem = currentLexem; assert lexem.symbol == Lexems.eoi; if (lexem.endoffset < fDocumentLength) { fTokenLength = fDocumentLength - fTokenOffset; lexem.offset = lexem.endoffset = fDocumentLength; return TEMPLATES; } return null; }
public IElementType nextToken() { fTokenOffset += fTokenLength; if (lexem == null) { fState = lexer.getState(); readNext(); } if (fTokenOffset < lexem.offset) { fTokenLength = lexem.offset - fTokenOffset; return TokenType.BAD_CHARACTER; } int token = lexem.symbol; fTokenLength = lexem.endoffset - fTokenOffset; LapgSymbol currentLexem = lexem; lexem = null; switch (token) { case Lexems.code: return TOKEN_ACTION; case Lexems._skip: return WHITESPACE; case Lexems._skip_comment: return COMMENT; case Lexems.scon: return STRING; case Lexems.icon: return ICON; case Lexems.ID: return ID; case Lexems.regexp: return REGEXP; // operators case Lexems.PERCENT: return OP_PERCENT; case Lexems.COLONCOLONEQUAL: return OP_CCEQ; case Lexems.OR: return OP_OR; case Lexems.EQUAL: return OP_EQ; case Lexems.EQUALGREATER: return OP_EQGT; case Lexems.SEMICOLON: return OP_SEMICOLON; case Lexems.DOT: return OP_DOT; case Lexems.COMMA: return OP_COMMA; case Lexems.COLON: return OP_COLON; case Lexems.COLONCOLON: return OP_COLONCOLON; case Lexems.LSQUARE: return OP_LBRACKET; case Lexems.RSQUARE: return OP_RBRACKET; case Lexems.LPAREN: return OP_LPAREN; case Lexems.RPAREN: return OP_RPAREN; case Lexems.LCURLY: return OP_LCURLY; case Lexems.RCURLY: return OP_RCURLY; case Lexems.LESS: return OP_LT; case Lexems.GREATER: return OP_GT; case Lexems.MULT: return OP_STAR; case Lexems.PLUS: return OP_PLUS; case Lexems.PLUSEQUAL: return OP_PLUSEQ; case Lexems.QUESTIONMARK: return OP_QMARK; // case Lexems.MINUSGREATER: // return OP_ARROW; case Lexems.LPARENQUESTIONMARKEXCLAMATION: return OP_LPAREN_QMARK_EXCL; case Lexems.AMPERSAND: return OP_AND; case Lexems.ATSIGN: return OP_AT; // keywords case Lexems.Ltrue: return KW_TRUE; case Lexems.Lfalse: return KW_FALSE; case Lexems.Lseparator: return KW_SEPARATOR; case Lexems.Lprio: return KW_PRIO; case Lexems.Lshift: return KW_SHIFT; case Lexems.Lreduce: return KW_REDUCE; case Lexems.Linput: return KW_INPUT; case Lexems.Lleft: return KW_LEFT; case Lexems.Lright: return KW_RIGHT; case Lexems.Lnew: return KW_NEW; case Lexems.Lnonassoc: return KW_NONASSOC; case Lexems.Lnoeoi: return KW_NOEOI; case Lexems.Las: return KW_AS; case Lexems.Limport: return KW_IMPORT; case Lexems.Linline: return KW_INLINE; case Lexems.Lreturns: return KW_RETURNS; case Lexems.Linterface: return KW_INTERFACE; case Lexems.Lvoid: return KW_VOID; case Lexems.Llanguage: return KW_LANGUAGE; case Lexems.Llalr: return KW_LALR; case Lexems.Llexer: return KW_LEXER; case Lexems.Lparser: return KW_PARSER; // soft keywords without highlighting case Lexems.Lsoft: return KW_SOFT; case Lexems.Lclass: return KW_CLASS; case Lexems.Lspace: return KW_SPACE; } /* default, eoi */ lexem = currentLexem; assert lexem.symbol == Lexems.eoi; if (lexem.offset < fDocumentLength) { fTokenLength = fDocumentLength - fTokenOffset; lexem.offset = lexem.endoffset = fDocumentLength; return TEMPLATES; } return null; }
diff --git a/oldProject/testConsumer/src/main/java/com/mycompany/testconsumer/App.java b/oldProject/testConsumer/src/main/java/com/mycompany/testconsumer/App.java index 4cb6200..e07a92d 100644 --- a/oldProject/testConsumer/src/main/java/com/mycompany/testconsumer/App.java +++ b/oldProject/testConsumer/src/main/java/com/mycompany/testconsumer/App.java @@ -1,57 +1,57 @@ package com.mycompany.testconsumer; import com.mysql.jdbc.Statement; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import twitter4j.Status; public class App { public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException, ClassNotFoundException { Connection conn = null; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); conn = factory.newConnection(); Channel chan = conn.createChannel(); chan.queueDeclare("testqueue", false, false, false, null); Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://155.246.61.53:3306/newtweets?useUnicode=true&characterEncoding=UTF8"; java.sql.Connection mysqlCon; try { mysqlCon = DriverManager.getConnection(url, "lsa", "stigmergy"); } catch (SQLException ex) { ex.printStackTrace(); return; } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); final String sqlStatement = "INSERT INTO `newtweets`.`tweet` (`tweet_id` ,`tweet_user` ,`tweet_user_login` ,`tweet_date` ,`tweet_text` ,`tweet_retweet` ,`tweet_latitude` ,`tweet_longitude` ,`tweet_place` ,`tweet_language`)VALUES (?,?,?,?,?,?,?,?,?,?);"; System.out.println("URL: " + url); System.out.println("Connection: " + mysqlCon); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(chan); chan.basicConsume("testqueue", true, consumer); - ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); + ExecutorService newCachedThreadPool = Executors.newFixedThreadPool(10); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Worker newWorker = new Worker(delivery, mysqlCon, sqlStatement); newCachedThreadPool.execute(newWorker); } } }
true
true
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException, ClassNotFoundException { Connection conn = null; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); conn = factory.newConnection(); Channel chan = conn.createChannel(); chan.queueDeclare("testqueue", false, false, false, null); Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://155.246.61.53:3306/newtweets?useUnicode=true&characterEncoding=UTF8"; java.sql.Connection mysqlCon; try { mysqlCon = DriverManager.getConnection(url, "lsa", "stigmergy"); } catch (SQLException ex) { ex.printStackTrace(); return; } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); final String sqlStatement = "INSERT INTO `newtweets`.`tweet` (`tweet_id` ,`tweet_user` ,`tweet_user_login` ,`tweet_date` ,`tweet_text` ,`tweet_retweet` ,`tweet_latitude` ,`tweet_longitude` ,`tweet_place` ,`tweet_language`)VALUES (?,?,?,?,?,?,?,?,?,?);"; System.out.println("URL: " + url); System.out.println("Connection: " + mysqlCon); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(chan); chan.basicConsume("testqueue", true, consumer); ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Worker newWorker = new Worker(delivery, mysqlCon, sqlStatement); newCachedThreadPool.execute(newWorker); } }
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException, ClassNotFoundException { Connection conn = null; ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); conn = factory.newConnection(); Channel chan = conn.createChannel(); chan.queueDeclare("testqueue", false, false, false, null); Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://155.246.61.53:3306/newtweets?useUnicode=true&characterEncoding=UTF8"; java.sql.Connection mysqlCon; try { mysqlCon = DriverManager.getConnection(url, "lsa", "stigmergy"); } catch (SQLException ex) { ex.printStackTrace(); return; } DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); final String sqlStatement = "INSERT INTO `newtweets`.`tweet` (`tweet_id` ,`tweet_user` ,`tweet_user_login` ,`tweet_date` ,`tweet_text` ,`tweet_retweet` ,`tweet_latitude` ,`tweet_longitude` ,`tweet_place` ,`tweet_language`)VALUES (?,?,?,?,?,?,?,?,?,?);"; System.out.println("URL: " + url); System.out.println("Connection: " + mysqlCon); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); QueueingConsumer consumer = new QueueingConsumer(chan); chan.basicConsume("testqueue", true, consumer); ExecutorService newCachedThreadPool = Executors.newFixedThreadPool(10); while (true) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(); Worker newWorker = new Worker(delivery, mysqlCon, sqlStatement); newCachedThreadPool.execute(newWorker); } }
diff --git a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/submodules/SubmoduleResolver.java b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/submodules/SubmoduleResolver.java index dfa4d59..932ff2e 100755 --- a/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/submodules/SubmoduleResolver.java +++ b/git-server/src/jetbrains/buildServer/buildTriggers/vcs/git/submodules/SubmoduleResolver.java @@ -1,144 +1,144 @@ /* * Copyright 2000-2011 JetBrains s.r.o. * * 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 jetbrains.buildServer.buildTriggers.vcs.git.submodules; import com.intellij.openapi.diagnostic.Logger; import jetbrains.buildServer.buildTriggers.vcs.git.GitVcsSupport; import jetbrains.buildServer.buildTriggers.vcs.git.VcsAuthenticationException; import org.eclipse.jgit.lib.BlobBasedConfig; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import java.io.FileNotFoundException; import java.io.IOException; /** * The resolver for submodules */ public abstract class SubmoduleResolver { private static Logger LOG = Logger.getInstance(SubmoduleResolver.class.getName()); private final RevCommit myCommit; private final Repository myDb; protected final GitVcsSupport myGitSupport; private SubmodulesConfig myConfig; public SubmoduleResolver(GitVcsSupport gitSupport, Repository db, RevCommit commit) { myGitSupport = gitSupport; myDb = db; myCommit = commit; } /** * Resolve the commit for submodule * * @param path the within repository path * @param commit the commit identifier * @return the the resoled commit in other repository * @throws IOException if there is an IO problem during resolving repository or mapping commit */ public RevCommit getSubmoduleCommit(String path, ObjectId commit) throws IOException, VcsAuthenticationException { ensureConfigLoaded(); String mainRepositoryUrl = myDb.getConfig().getString("teamcity", null, "remote"); if (myConfig == null) { - throw new IOException(String.format("No submodule configuration found. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule commit: '%4$s'.", - mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); + String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but has no .gitmodules configuration at the root directory."; + throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path)); } final Submodule submodule = myConfig.findSubmodule(path); if (submodule == null) { - throw new IOException(String.format("No submodule entry found in .gitmodules. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule commit: '%4$s'.", - mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); + String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but has no entry for this path in .gitmodules configuration."; + throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); } Repository r = resolveRepository(path, submodule.getUrl()); final RevCommit c = myGitSupport.getCommit(r, commit); if (c == null) { - throw new IOException(String.format("Submodule commit is not found. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule repository: '%4$s', submodule commit: '%5$s'.", - mainRepositoryUrl, myCommit.getId().name(), path, submodule.getUrl(), commit.name())); + String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but tracked submodule commit '%4$s' is not found in repository '%5$s'. Forget to push it?"; + throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path, commit.name(), submodule.getUrl())); } return c; } /** * Get repository by the URL. Note that the repository is retrieved but not cleaned up. This should be done by implementer of this component at later time. * * @param path the local path within repository * @param url the URL to resolve @return the resolved repository * @return the resolved repository * @throws IOException if repository could not be resolved */ protected abstract Repository resolveRepository(String path, String url) throws IOException, VcsAuthenticationException; /** * Get submodule resolver for the path * * @param commit the start commit * @param path the local path within repository * @return the submodule resolver that handles submodules inside the specified commit */ public abstract SubmoduleResolver getSubResolver(RevCommit commit, String path); /** * Check if the specified directory is a submodule prefix * * @param path the path to check * @return true if the path contains submodules */ public boolean containsSubmodule(String path) { ensureConfigLoaded(); return myConfig != null && myConfig.isSubmodulePrefix(path); } /** * @return the current repository */ public Repository getRepository() { return myDb; } /** * Get submodule url by it's path in current repository * * @param submodulePath path of submodule in current repository * @return submodule repository url or null if no submodules is registered for specified path */ public String getSubmoduleUrl(String submodulePath) { ensureConfigLoaded(); if (myConfig != null) { Submodule submodule = myConfig.findSubmodule(submodulePath); return submodule != null ? submodule.getUrl() : null; } else { return null; } } /** * Ensure that submodule configuration has been loaded. */ private void ensureConfigLoaded() { if (myConfig == null) { try { myConfig = new SubmodulesConfig(myDb.getConfig(), new BlobBasedConfig(null, myDb, myCommit, ".gitmodules")); } catch (FileNotFoundException e) { // do nothing } catch (Exception e) { LOG.error("Unable to load or parse submodule configuration at: " + myCommit.getId().name(), e); } } } }
false
true
public RevCommit getSubmoduleCommit(String path, ObjectId commit) throws IOException, VcsAuthenticationException { ensureConfigLoaded(); String mainRepositoryUrl = myDb.getConfig().getString("teamcity", null, "remote"); if (myConfig == null) { throw new IOException(String.format("No submodule configuration found. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule commit: '%4$s'.", mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); } final Submodule submodule = myConfig.findSubmodule(path); if (submodule == null) { throw new IOException(String.format("No submodule entry found in .gitmodules. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule commit: '%4$s'.", mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); } Repository r = resolveRepository(path, submodule.getUrl()); final RevCommit c = myGitSupport.getCommit(r, commit); if (c == null) { throw new IOException(String.format("Submodule commit is not found. Main repository: '%1$s', main repository commit: '%2$s', path to submodule: '%3$s', submodule repository: '%4$s', submodule commit: '%5$s'.", mainRepositoryUrl, myCommit.getId().name(), path, submodule.getUrl(), commit.name())); } return c; }
public RevCommit getSubmoduleCommit(String path, ObjectId commit) throws IOException, VcsAuthenticationException { ensureConfigLoaded(); String mainRepositoryUrl = myDb.getConfig().getString("teamcity", null, "remote"); if (myConfig == null) { String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but has no .gitmodules configuration at the root directory."; throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path)); } final Submodule submodule = myConfig.findSubmodule(path); if (submodule == null) { String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but has no entry for this path in .gitmodules configuration."; throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path, commit.name())); } Repository r = resolveRepository(path, submodule.getUrl()); final RevCommit c = myGitSupport.getCommit(r, commit); if (c == null) { String msg = "Repository '%1$s' has submodule in commit '%2$s' at path '%3$s', but tracked submodule commit '%4$s' is not found in repository '%5$s'. Forget to push it?"; throw new IOException(String.format(msg, mainRepositoryUrl, myCommit.getId().name(), path, commit.name(), submodule.getUrl())); } return c; }
diff --git a/troia-server/src/main/java/com/datascience/gal/MultinomialConfusionMatrix.java b/troia-server/src/main/java/com/datascience/gal/MultinomialConfusionMatrix.java index f78794dc..5aff87c3 100644 --- a/troia-server/src/main/java/com/datascience/gal/MultinomialConfusionMatrix.java +++ b/troia-server/src/main/java/com/datascience/gal/MultinomialConfusionMatrix.java @@ -1,311 +1,311 @@ /******************************************************************************* * Copyright (c) 2012 Panagiotis G. Ipeirotis & Josh M. Attenberg * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package com.datascience.gal; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.datascience.core.storages.JSONUtils; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; /** * TODO: implement with logistic regression TODO: bayesian multinomial * * @author panos and josh * */ public class MultinomialConfusionMatrix implements ConfusionMatrix { public static final ConfusionMatrixDeserializer deserializer = new ConfusionMatrixDeserializer(); private Set<String> categories; private Map<CategoryPair, Double> matrix; public Map<String, Double> rowDenominator; private MultinomialConfusionMatrix(Collection<String> categories, Map<CategoryPair, Double> matrix, Map<String, Double> rowDenominator) { this.categories = new HashSet<String>(categories); this.matrix = matrix; this.rowDenominator = rowDenominator; } public MultinomialConfusionMatrix(Collection<Category> categories) { this.categories = new HashSet<String>(); for (Category c : categories) { this.categories.add(c.getName()); } this.matrix = new HashMap<CategoryPair, Double>(); rowDenominator = new HashMap<String, Double>(); // We now initialize the confusion matrix // and we set it to 0.9 in the diagonal and 0.0 elsewhere for (String from : this.categories) { for (String to : this.categories) { double value = 0.1 / (double) (this.categories.size() - 1); if (from.equals(to)) { value = .9; } setErrorRate(from, to, value); incrementRowDenominator(from, value); } } normalize(); } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#incrementRowDenominator(java.lang.String * , double) */ public void incrementRowDenominator(String from, double value) { double old = rowDenominator.containsKey(from) ? rowDenominator .get(from) : 0; rowDenominator.put(from, old + value); } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#decrementRowDenominator(java.lang.String * , double) */ public void decrementRowDenominator(String from, double value) { double old = rowDenominator.containsKey(from) ? rowDenominator .get(from) : 0; rowDenominator.put(from, Math.max(0., old - value)); } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#empty() */ public void empty() { // for (String from : this.categories) { // for (String to : this.categories) { // rowDenominator.put(from, 0.); // setErrorRate(from, to, 0.0); // } // } matrix = new HashMap<CategoryPair, Double>(); rowDenominator = new HashMap<String, Double>(); } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#normalize() */ public void normalize() { for (String from : this.categories) { double from_marginal = rowDenominator.containsKey(from) ? rowDenominator .get(from) : 0; for (String to : this.categories) { double error = getErrorRateBatch(from, to); double error_rate; // If the marginal across the "from" category is 0 // this means that the worker has not even seen an object of the // "from" // category. In this case, we switch to Laplacean smoothing for // computing the matrix if (from_marginal == 0.0) { - // error_rate = Double.NaN; + error_rate = Double.NaN; // System.out.println(from_marginal); - error_rate = (error + 1) - / (from_marginal + this.categories.size()); +// error_rate = (error + 1) +// / (from_marginal + this.categories.size()); } else { error_rate = error / from_marginal; } setErrorRate(from, to, error_rate); } rowDenominator.put(from, 1.); // System.out.println(from + " " + rowDenominator.get(from)); } } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#normalizeLaplacean() */ public void normalizeLaplacean() { for (String from : this.categories) { double from_marginal = rowDenominator.get(from); for (String to : this.categories) { double error = getErrorRateBatch(from, to); setErrorRate(from, to, (error + 1) / (from_marginal + this.categories.size())); } rowDenominator.put(from, 1.); } } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#addError(java.lang.String, * java.lang.String, java.lang.Double) */ public void addError(String from, String to, Double error) { CategoryPair cp = new CategoryPair(from, to); double currentError = matrix.containsKey(cp) ? matrix.get(cp) : 0; incrementRowDenominator(from, error); this.matrix.put(cp, currentError + error); } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#removeError(java.lang.String, * java.lang.String, java.lang.Double) */ public void removeError(String from, String to, Double error) { CategoryPair cp = new CategoryPair(from, to); double currentError = matrix.containsKey(cp) ? matrix.get(cp) : 0; decrementRowDenominator(from, error); this.matrix.put(cp, Math.max(0, currentError - error)); } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#getErrorRateBatch(java.lang.String, * java.lang.String) */ public double getErrorRateBatch(String from, String to) { CategoryPair cp = new CategoryPair(from, to); return matrix.containsKey(cp) ? matrix.get(cp) : 0; } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#getNormalizedErrorRate(java.lang.String * , java.lang.String) */ public double getNormalizedErrorRate(String from, String to) { CategoryPair cp = new CategoryPair(from, to); return matrix.get(cp) / rowDenominator.get(from); } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#getLaplaceNormalizedErrorRate(java. * lang.String, java.lang.String) */ public double getLaplaceNormalizedErrorRate(String from, String to) { CategoryPair cp = new CategoryPair(from, to); return (1. + matrix.get(cp)) / (rowDenominator.get(from) + categories.size()); } /* * (non-Javadoc) * * @see * com.ipeirotis.gal.ConfusionMatrix#getIncrementalErrorRate(java.lang.String * , java.lang.String) */ public double getIncrementalErrorRate(String from, String to) { CategoryPair cp = new CategoryPair(from, to); return matrix.get(cp) / rowDenominator.get(from); } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#setErrorRate(java.lang.String, * java.lang.String, java.lang.Double) */ public void setErrorRate(String from, String to, Double cost) { CategoryPair cp = new CategoryPair(from, to); matrix.put(cp, cost); } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#toString() */ @Override public String toString() { return JSONUtils.gson.toJson(this); } public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof MultinomialConfusionMatrix)) return false; MultinomialConfusionMatrix other = (MultinomialConfusionMatrix) obj; if(!this.categories.equals(other.categories)) { return false; } if (!this.matrix.equals(other.matrix)) { return false; } if (!this.rowDenominator.equals(other.rowDenominator)) { return false; } return true; } /* * (non-Javadoc) * * @see com.ipeirotis.gal.ConfusionMatrix#getCategories() */ public Set<String> getCategories() { return new HashSet<String>(categories); } public static class ConfusionMatrixDeserializer implements JsonDeserializer<MultinomialConfusionMatrix> { @Override public MultinomialConfusionMatrix deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JsonObject jobject = (JsonObject) json; Collection<String> categories = JSONUtils.gson.fromJson( jobject.get("categories"), JSONUtils.stringSetType); Map<CategoryPair, Double> matrix = JSONUtils.gson.fromJson( jobject.get("matrix"), JSONUtils.categoryPairDoubleMapType); Map<String, Double> rowDenominator = JSONUtils.gson.fromJson( jobject.get("rowDenominator"), JSONUtils.stringDoubleMapType); return new MultinomialConfusionMatrix(categories, matrix, rowDenominator); } } }
false
true
public void normalize() { for (String from : this.categories) { double from_marginal = rowDenominator.containsKey(from) ? rowDenominator .get(from) : 0; for (String to : this.categories) { double error = getErrorRateBatch(from, to); double error_rate; // If the marginal across the "from" category is 0 // this means that the worker has not even seen an object of the // "from" // category. In this case, we switch to Laplacean smoothing for // computing the matrix if (from_marginal == 0.0) { // error_rate = Double.NaN; // System.out.println(from_marginal); error_rate = (error + 1) / (from_marginal + this.categories.size()); } else { error_rate = error / from_marginal; } setErrorRate(from, to, error_rate); } rowDenominator.put(from, 1.); // System.out.println(from + " " + rowDenominator.get(from)); } }
public void normalize() { for (String from : this.categories) { double from_marginal = rowDenominator.containsKey(from) ? rowDenominator .get(from) : 0; for (String to : this.categories) { double error = getErrorRateBatch(from, to); double error_rate; // If the marginal across the "from" category is 0 // this means that the worker has not even seen an object of the // "from" // category. In this case, we switch to Laplacean smoothing for // computing the matrix if (from_marginal == 0.0) { error_rate = Double.NaN; // System.out.println(from_marginal); // error_rate = (error + 1) // / (from_marginal + this.categories.size()); } else { error_rate = error / from_marginal; } setErrorRate(from, to, error_rate); } rowDenominator.put(from, 1.); // System.out.println(from + " " + rowDenominator.get(from)); } }