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/src/edu/washington/cs/games/ktuite/pointcraft/PrimitiveVertex.java b/src/edu/washington/cs/games/ktuite/pointcraft/PrimitiveVertex.java index 29c588c..c61a104 100644 --- a/src/edu/washington/cs/games/ktuite/pointcraft/PrimitiveVertex.java +++ b/src/edu/washington/cs/games/ktuite/pointcraft/PrimitiveVertex.java @@ -1,106 +1,106 @@ package edu.washington.cs.games.ktuite.pointcraft; import static org.lwjgl.opengl.GL11.*; import java.io.InputStream; import java.net.URL; import java.util.List; import org.lwjgl.util.vector.Vector3f; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; /* these primitives built out of pellets... * keep a list of pellets and then draw lines or polygons between them. */ public class PrimitiveVertex { private int gl_type; private List<Vector3f> vertices; private float line_width = 5f; private Vector3f pt_1; private Vector3f pt_2; private float a, b, c, d; public PrimitiveVertex(int _gl_type, List<Vector3f> _vertices) { gl_type = _gl_type; vertices = _vertices; } public PrimitiveVertex(int _gl_type, List<Vector3f> _vertices, float _line_width) { gl_type = _gl_type; vertices = _vertices; line_width = _line_width; } public boolean isPolygon() { if (gl_type == GL_POLYGON) return true; else return false; } public boolean isLine() { if (pt_1 != null && pt_2 != null) return true; else return false; } public boolean isPlane() { if (a == 0 && b == 0 && c == 0 && d == 0) return false; else return true; } public void setLine(Vector3f a, Vector3f b){ pt_1 = new Vector3f(a); pt_2 = new Vector3f(b); } public void setPlane(float _a, float _b, float _c, float _d){ a = _a; b = _b; c = _c; d = _d; } public void draw() { if (gl_type == GL_LINES) { glColor3f(0f, .1f, .3f); glLineWidth(line_width); } else if (gl_type == GL_POLYGON) { glColor4f(.9f, .9f, 0, .5f); } glBegin(gl_type); for (Vector3f vertex : vertices) { glVertex3f(vertex.x, vertex.y, vertex.z); } glEnd(); } public float distanceToPoint(Vector3f pos) { float dist = Float.MAX_VALUE; if (isLine()){ // OH GOD THIS LOOKS SO SLOW // TODO: make faster Vector3f temp = new Vector3f(); Vector3f sub1 = new Vector3f(); Vector3f sub2 = new Vector3f(); Vector3f sub3 = new Vector3f(); Vector3f.sub(pos,pt_1,sub1); Vector3f.sub(pos,pt_2,sub2); Vector3f.sub(pt_2, pt_1, sub3); Vector3f.cross(sub1, sub2, temp); dist = temp.length()/sub3.length(); } else if (isPlane()){ dist = (float) ((a*pos.x + b*pos.y + c*pos.z + d)/Math.sqrt(a*a + b*b + d*d)); } System.out.println("distancE: " + dist); - return dist; + return Math.abs(dist); } }
true
true
public float distanceToPoint(Vector3f pos) { float dist = Float.MAX_VALUE; if (isLine()){ // OH GOD THIS LOOKS SO SLOW // TODO: make faster Vector3f temp = new Vector3f(); Vector3f sub1 = new Vector3f(); Vector3f sub2 = new Vector3f(); Vector3f sub3 = new Vector3f(); Vector3f.sub(pos,pt_1,sub1); Vector3f.sub(pos,pt_2,sub2); Vector3f.sub(pt_2, pt_1, sub3); Vector3f.cross(sub1, sub2, temp); dist = temp.length()/sub3.length(); } else if (isPlane()){ dist = (float) ((a*pos.x + b*pos.y + c*pos.z + d)/Math.sqrt(a*a + b*b + d*d)); } System.out.println("distancE: " + dist); return dist; }
public float distanceToPoint(Vector3f pos) { float dist = Float.MAX_VALUE; if (isLine()){ // OH GOD THIS LOOKS SO SLOW // TODO: make faster Vector3f temp = new Vector3f(); Vector3f sub1 = new Vector3f(); Vector3f sub2 = new Vector3f(); Vector3f sub3 = new Vector3f(); Vector3f.sub(pos,pt_1,sub1); Vector3f.sub(pos,pt_2,sub2); Vector3f.sub(pt_2, pt_1, sub3); Vector3f.cross(sub1, sub2, temp); dist = temp.length()/sub3.length(); } else if (isPlane()){ dist = (float) ((a*pos.x + b*pos.y + c*pos.z + d)/Math.sqrt(a*a + b*b + d*d)); } System.out.println("distancE: " + dist); return Math.abs(dist); }
diff --git a/threads/LotteryScheduler.java b/threads/LotteryScheduler.java index c9a4bf5..4b8c3cc 100755 --- a/threads/LotteryScheduler.java +++ b/threads/LotteryScheduler.java @@ -1,193 +1,193 @@ package nachos.threads; import nachos.machine.*; import java.util.Random; import java.util.TreeSet; import java.util.HashSet; import java.util.Iterator; /** * A scheduler that chooses threads using a lottery. * * <p> * A lottery scheduler associates a number of tickets with each thread. When a * thread needs to be dequeued, a random lottery is held, among all the tickets * of all the threads waiting to be dequeued. The thread that holds the winning * ticket is chosen. * * <p> * Note that a lottery scheduler must be able to handle a lot of tickets * (sometimes billions), so it is not acceptable to maintain state for every * ticket. * * <p> * A lottery scheduler must partially solve the priority inversion problem; in * particular, tickets must be transferred through locks, and through joins. * Unlike a priority scheduler, these tickets add (as opposed to just taking * the maximum). */ public class LotteryScheduler extends PriorityScheduler { public static final int priorityMinimum = 1; public static final int priorityMaximum = Integer.MAX_VALUE; /** * Allocate a new lottery scheduler. */ public LotteryScheduler() { } //DONE!!!! protected ThreadState getThreadState(KThread thread) { if (thread.schedulingState == null) thread.schedulingState = new LotteryThreadState(thread); return (ThreadState) thread.schedulingState; } /** * Allocate a new lottery thread queue. * * @param transferPriority <tt>true</tt> if this queue should * transfer tickets from waiting threads * to the owning thread. * @return a new lottery thread queue. */ public ThreadQueue newThreadQueue(boolean transferPriority) { return new LotteryQueue(transferPriority); } protected class LotteryQueue extends PriorityQueue { //In terms of picking the next thread linear in the number of threads on the queue is fine LotteryQueue(boolean transferPriority) { super(transferPriority); } public void updateEntry(ThreadState ts, int newEffectivePriority) { int oldPriority = ts.getEffectivePriority(); ts.effectivePriority = newEffectivePriority; //propagate int difference = newEffectivePriority-oldPriority; if(difference != 0) ts.propagate(difference); } //DONE!!!!! protected ThreadState pickNextThread() { //Set up an Iterator and go through it Random randomGenerator = new Random(); int ticketCount = 0; Iterator<ThreadState> itr = this.waitQueue.iterator(); while(itr.hasNext()) { ticketCount += itr.next().getEffectivePriority(); } if(ticketCount > 0) { int num = randomGenerator.nextInt(ticketCount); itr = this.waitQueue.iterator(); ThreadState temp; while(itr.hasNext()) { temp = itr.next(); num -= temp.effectivePriority; if(num <= 0){ return temp; } } } return null; } } protected class LotteryThreadState extends ThreadState { public LotteryThreadState(KThread thread) { super(thread); } //DONE!!!! public void setPriority(int newPriority) { this.priority = newPriority; this.updateEffectivePriority(); } //DONE!!!! public void propagate(int difference) { if(pqWant != null) { if(pqWant.transferPriority == true) { if(pqWant.holder != null) pqWant.updateEntry(pqWant.holder, pqWant.holder.effectivePriority+difference); } } } //DONE!!!! public void updateEffectivePriority() { //Calculate new effectivePriority checking possible donations from threads that are waiting for me int sumPriority = this.priority; for (PriorityQueue pq: this.pqHave) if (pq.transferPriority == true) { Iterator<ThreadState> itr = pq.waitQueue.iterator(); while(itr.hasNext()) sumPriority += itr.next().getEffectivePriority(); } //If there is a change in priority, update and propagate to other owners if (sumPriority != this.effectivePriority) { int difference = sumPriority - this.effectivePriority; this.effectivePriority = sumPriority; this.propagate(difference); } } //DONE!!!! public void waitForAccess(PriorityQueue pq) { this.pqWant = pq; //this.time = Machine.timer().getTime(); this.time = TickTimer++; pq.waitQueue.add(this); //Propagate this ThreadState's effectivePriority to holder of pq if (pq.transferPriority == true) { if(pq.holder != null) pq.updateEntry(pq.holder, pq.holder.effectivePriority+this.effectivePriority); } } //Added a line to acquire in PriorityScheduler //updateEffectivePriority() at the very end of acquire } public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); - System.out.println("Next Thread Null is: " + (temp == null)); + System.out.println("nextThread == null is: " + (temp == null)); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); - System.out.println("Next Thread Null is: " + (temp == null)); - temp = pq[0].pickNextThread().thread; + System.out.println("nextThread == null is: " + (temp == null)); + temp = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); - System.out.println("Next Thread Null is: " + (temp == null)); + System.out.println("pickNextThread == null is: " + (temp == null)); Machine.interrupt().enable(); } }
false
true
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("Next Thread Null is: " + (temp == null)); Machine.interrupt().enable(); }
public static void selfTest() { LotteryScheduler ls = new LotteryScheduler(); LotteryQueue[] pq = new LotteryQueue[5]; KThread[] t = new KThread[5]; ThreadState lts[] = new LotteryThreadState[5]; for (int i=0; i < 5; i++) pq[i] = ls.new LotteryQueue(true); for (int i=0; i < 5; i++) { t[i] = new KThread(); t[i].setName("thread" + i); lts[i] = ls.getThreadState(t[i]); } Machine.interrupt().disable(); System.out.println("===========LotteryScheduler Test============"); System.out.println("priority defaults to " + lts[0].priority); pq[0].acquire(t[0]); System.out.println("pq[0].acquire(t[0])"); System.out.println("lock holder effective priority is " + pq[0].holder.effectivePriority); lts[0].setPriority(5); System.out.println("lts[0].setPriority(5)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); pq[0].waitForAccess(t[1]); System.out.println("pq[0].waitForAccess(t[1])"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); KThread temp = pq[0].pickNextThread().thread; System.out.println("pq[0].pickNextThread()"); System.out.println("nextThread == null is: " + (temp == null)); lts[1].setPriority(3); System.out.println("lts[1].setPriority(3)"); System.out.println("lock holder effective priority is " + lts[0].effectivePriority); temp = pq[0].nextThread(); System.out.println("pq[0].nextThread()"); System.out.println("nextThread == null is: " + (temp == null)); temp = pq[0].pickNextThread(); System.out.println("pq[0].pickNextThread()"); System.out.println("pickNextThread == null is: " + (temp == null)); Machine.interrupt().enable(); }
diff --git a/api/src/main/java/org/openmrs/util/OpenmrsConstants.java b/api/src/main/java/org/openmrs/util/OpenmrsConstants.java index 635f70aa..69f62474 100644 --- a/api/src/main/java/org/openmrs/util/OpenmrsConstants.java +++ b/api/src/main/java/org/openmrs/util/OpenmrsConstants.java @@ -1,1607 +1,1607 @@ /** * The contents of this file are subject to the OpenMRS Public License * Version 1.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://license.openmrs.org * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.util; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.GlobalProperty; import org.openmrs.api.ConceptService; import org.openmrs.api.handler.ExistingVisitAssignmentHandler; import org.openmrs.customdatatype.datatype.BooleanDatatype; import org.openmrs.hl7.HL7Constants; import org.openmrs.module.ModuleConstants; import org.openmrs.module.ModuleFactory; import org.openmrs.patient.impl.LuhnIdentifierValidator; import org.openmrs.scheduler.SchedulerConstants; /** * Constants used in OpenMRS. Contents built from build properties (version, version_short, and * expected_database). Some are set at runtime (database, database version). This file should * contain all privilege names and global property names. Those strings added to the static CORE_* * methods will be written to the database at startup if they don't exist yet. */ public final class OpenmrsConstants { private static Log log = LogFactory.getLog(OpenmrsConstants.class); /** * This is the hard coded primary key of the order type for DRUG. This has to be done because * some logic in the API acts on this order type */ public static final int ORDERTYPE_DRUG = 2; /** * This is the hard coded primary key of the concept class for DRUG. This has to be done because * some logic in the API acts on this concept class */ public static final int CONCEPT_CLASS_DRUG = 3; /** * hack alert: During an ant build, the openmrs api jar manifest file is loaded with these * values. When constructing the OpenmrsConstants class file, the api jar is read and the values * are copied in as constants */ private static final Package THIS_PACKAGE = OpenmrsConstants.class.getPackage(); /** * This holds the current openmrs code version. This version is a string containing spaces and * words.<br/> * The format is:<br/> * <i>major</i>.<i>minor</i>.<i>maintenance</i> <i>suffix</i> Build <i>buildNumber</i> */ public static final String OPENMRS_VERSION = THIS_PACKAGE.getSpecificationVendor() != null ? THIS_PACKAGE .getSpecificationVendor() : getVersion(); /** * This holds the current openmrs code version in a short space-less string.<br/> * The format is:<br/> * <i>major</i>.<i>minor</i>.<i>maintenance</i>.<i>revision</i>-<i>suffix</i> */ public static final String OPENMRS_VERSION_SHORT = THIS_PACKAGE.getSpecificationVersion() != null ? THIS_PACKAGE .getSpecificationVersion() : getVersion(); /** * Somewhat hacky method to fetch the version from the maven pom.properties file. <br/> * This method should not be used unless in a dev environment. The preferred way to get the * version is from the manifest in the api jar file. More detail is included in the properties * there. * * @return version number defined in maven pom.xml file(s) * @see #OPENMRS_VERSION_SHORT * @see #OPENMRS_VERSION */ private static String getVersion() { Properties props = new Properties(); // Get hold of the path to the properties file // (Maven will make sure it's on the class path) java.net.URL url = OpenmrsConstants.class.getClassLoader().getResource( "META-INF/maven/org.openmrs.api/openmrs-api/pom.properties"); if (url == null) { log.error("Unable to find pom.properties file built by maven"); return null; } // Load the file try { props.load(url.openStream()); return props.getProperty("version"); // this will return "1.9.0-SNAPSHOT" in dev environments } catch (IOException e) { log.error("Unable to get pom.properties file into Properties object"); } return null; } /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ @Deprecated public static final String DATABASE_VERSION_EXPECTED = THIS_PACKAGE.getImplementationVersion(); public static String DATABASE_NAME = "openmrs"; public static String DATABASE_BUSINESS_NAME = "openmrs"; /** * See {@link DatabaseUpdater#updatesRequired()} to see what changesets in the * liquibase-update-to-latest.xml file in the openmrs api jar file need to be run to bring the * db up to date with what the api requires. * * @deprecated the database doesn't have just one main version now that we are using liquibase. */ @Deprecated public static String DATABASE_VERSION = null; /** * Set true from runtime configuration to obscure patients for system demonstrations */ public static boolean OBSCURE_PATIENTS = false; public static String OBSCURE_PATIENTS_GIVEN_NAME = "Demo"; public static String OBSCURE_PATIENTS_MIDDLE_NAME = null; public static String OBSCURE_PATIENTS_FAMILY_NAME = "Person"; public static final String REGEX_LARGE = "[!\"#\\$%&'\\(\\)\\*,+-\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final String REGEX_SMALL = "[!\"#\\$%&'\\(\\)\\*,\\./:;<=>\\?@\\[\\\\\\\\\\]^_`{\\|}~]"; public static final Integer CIVIL_STATUS_CONCEPT_ID = 1054; /** * The directory that will store filesystem data about openmrs like module omods, generated data * exports, etc. This shouldn't be accessed directory, the * OpenmrsUtil.getApplicationDataDirectory() should be used. This should be null here. This * constant will hold the value of the user's runtime property for the * application_data_directory and is set programmatically at startup. This value is set in the * openmrs startup method. If this is null, the getApplicationDataDirectory() uses some OS * heuristics to determine where to put an app data dir. * * @see #APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY * @see OpenmrsUtil#getApplicationDataDirectory() * @see OpenmrsUtil#startup(java.util.Properties) */ public static String APPLICATION_DATA_DIRECTORY = null; /** * The name of the runtime property that a user can set that will specify where openmrs's * application directory is * * @see #APPLICATION_DATA_DIRECTORY */ public static String APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY = "application_data_directory"; /** * The name of the runtime property that a user can set that will specify whether the database * is automatically updated on startup */ public static String AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY = "auto_update_database"; /** * These words are ignored in concept and patient searches * * @return Collection<String> of words that are ignored */ public static final Collection<String> STOP_WORDS() { List<String> stopWords = new Vector<String>(); stopWords.add("A"); stopWords.add("AND"); stopWords.add("AT"); stopWords.add("BUT"); stopWords.add("BY"); stopWords.add("FOR"); stopWords.add("HAS"); stopWords.add("OF"); stopWords.add("THE"); stopWords.add("TO"); return stopWords; } /** * A gender character to gender name map<br/> * TODO issues with localization. How should this be handled? * * @return Map<String, String> of gender character to gender name */ public static final Map<String, String> GENDER() { Map<String, String> genders = new LinkedHashMap<String, String>(); genders.put("M", "Male"); genders.put("F", "Female"); return genders; } // Baked in Privileges: @Deprecated public static final String PRIV_VIEW_CONCEPTS = PrivilegeConstants.VIEW_CONCEPTS; @Deprecated public static final String PRIV_MANAGE_CONCEPTS = PrivilegeConstants.MANAGE_CONCEPTS; @Deprecated public static final String PRIV_PURGE_CONCEPTS = PrivilegeConstants.PURGE_CONCEPTS; @Deprecated public static final String PRIV_MANAGE_CONCEPT_NAME_TAGS = PrivilegeConstants.MANAGE_CONCEPT_NAME_TAGS; @Deprecated public static final String PRIV_VIEW_CONCEPT_PROPOSALS = PrivilegeConstants.VIEW_CONCEPT_PROPOSALS; @Deprecated public static final String PRIV_ADD_CONCEPT_PROPOSALS = PrivilegeConstants.ADD_CONCEPT_PROPOSALS; @Deprecated public static final String PRIV_EDIT_CONCEPT_PROPOSALS = PrivilegeConstants.EDIT_CONCEPT_PROPOSALS; @Deprecated public static final String PRIV_DELETE_CONCEPT_PROPOSALS = PrivilegeConstants.DELETE_CONCEPT_PROPOSALS; @Deprecated public static final String PRIV_PURGE_CONCEPT_PROPOSALS = PrivilegeConstants.PURGE_CONCEPT_PROPOSALS; @Deprecated public static final String PRIV_VIEW_USERS = PrivilegeConstants.VIEW_USERS; @Deprecated public static final String PRIV_ADD_USERS = PrivilegeConstants.ADD_USERS; @Deprecated public static final String PRIV_EDIT_USERS = PrivilegeConstants.EDIT_USERS; @Deprecated public static final String PRIV_DELETE_USERS = PrivilegeConstants.DELETE_USERS; @Deprecated public static final String PRIV_PURGE_USERS = PrivilegeConstants.PURGE_USERS; @Deprecated public static final String PRIV_EDIT_USER_PASSWORDS = PrivilegeConstants.EDIT_USER_PASSWORDS; @Deprecated public static final String PRIV_VIEW_ENCOUNTERS = PrivilegeConstants.VIEW_ENCOUNTERS; @Deprecated public static final String PRIV_ADD_ENCOUNTERS = PrivilegeConstants.ADD_ENCOUNTERS; @Deprecated public static final String PRIV_EDIT_ENCOUNTERS = PrivilegeConstants.EDIT_ENCOUNTERS; @Deprecated public static final String PRIV_DELETE_ENCOUNTERS = PrivilegeConstants.DELETE_ENCOUNTERS; @Deprecated public static final String PRIV_PURGE_ENCOUNTERS = PrivilegeConstants.PURGE_ENCOUNTERS; @Deprecated public static final String PRIV_VIEW_ENCOUNTER_TYPES = PrivilegeConstants.VIEW_ENCOUNTER_TYPES; @Deprecated public static final String PRIV_MANAGE_ENCOUNTER_TYPES = PrivilegeConstants.MANAGE_ENCOUNTER_TYPES; @Deprecated public static final String PRIV_PURGE_ENCOUNTER_TYPES = PrivilegeConstants.PURGE_ENCOUNTER_TYPES; @Deprecated public static final String PRIV_VIEW_LOCATIONS = PrivilegeConstants.VIEW_LOCATIONS; @Deprecated public static final String PRIV_MANAGE_LOCATIONS = PrivilegeConstants.MANAGE_LOCATIONS; @Deprecated public static final String PRIV_PURGE_LOCATIONS = PrivilegeConstants.PURGE_LOCATIONS; @Deprecated public static final String PRIV_MANAGE_LOCATION_TAGS = PrivilegeConstants.MANAGE_LOCATION_TAGS; @Deprecated public static final String PRIV_PURGE_LOCATION_TAGS = PrivilegeConstants.PURGE_LOCATION_TAGS; @Deprecated public static final String PRIV_VIEW_OBS = PrivilegeConstants.VIEW_OBS; @Deprecated public static final String PRIV_ADD_OBS = PrivilegeConstants.ADD_OBS; @Deprecated public static final String PRIV_EDIT_OBS = PrivilegeConstants.EDIT_OBS; @Deprecated public static final String PRIV_DELETE_OBS = PrivilegeConstants.DELETE_OBS; @Deprecated public static final String PRIV_PURGE_OBS = PrivilegeConstants.PURGE_OBS; @Deprecated public static final String PRIV_VIEW_MIME_TYPES = "View Mime Types"; @Deprecated public static final String PRIV_PURGE_MIME_TYPES = "Purge Mime Types"; @Deprecated public static final String PRIV_VIEW_PATIENTS = PrivilegeConstants.VIEW_PATIENTS; @Deprecated public static final String PRIV_ADD_PATIENTS = PrivilegeConstants.ADD_PATIENTS; @Deprecated public static final String PRIV_EDIT_PATIENTS = PrivilegeConstants.EDIT_PATIENTS; @Deprecated public static final String PRIV_DELETE_PATIENTS = PrivilegeConstants.DELETE_PATIENTS; @Deprecated public static final String PRIV_PURGE_PATIENTS = PrivilegeConstants.PURGE_PATIENTS; @Deprecated public static final String PRIV_VIEW_PATIENT_IDENTIFIERS = PrivilegeConstants.VIEW_PATIENT_IDENTIFIERS; @Deprecated public static final String PRIV_ADD_PATIENT_IDENTIFIERS = PrivilegeConstants.ADD_PATIENT_IDENTIFIERS; @Deprecated public static final String PRIV_EDIT_PATIENT_IDENTIFIERS = PrivilegeConstants.EDIT_PATIENT_IDENTIFIERS; @Deprecated public static final String PRIV_DELETE_PATIENT_IDENTIFIERS = PrivilegeConstants.DELETE_PATIENT_IDENTIFIERS; @Deprecated public static final String PRIV_PURGE_PATIENT_IDENTIFIERS = PrivilegeConstants.PURGE_PATIENT_IDENTIFIERS; @Deprecated public static final String PRIV_VIEW_PATIENT_COHORTS = PrivilegeConstants.VIEW_PATIENT_COHORTS; @Deprecated public static final String PRIV_ADD_COHORTS = PrivilegeConstants.ADD_COHORTS; @Deprecated public static final String PRIV_EDIT_COHORTS = PrivilegeConstants.EDIT_COHORTS; @Deprecated public static final String PRIV_DELETE_COHORTS = PrivilegeConstants.DELETE_COHORTS; @Deprecated public static final String PRIV_PURGE_COHORTS = PrivilegeConstants.PURGE_COHORTS; @Deprecated public static final String PRIV_VIEW_ORDERS = PrivilegeConstants.VIEW_ORDERS; @Deprecated public static final String PRIV_ADD_ORDERS = PrivilegeConstants.ADD_ORDERS; @Deprecated public static final String PRIV_EDIT_ORDERS = PrivilegeConstants.EDIT_ORDERS; @Deprecated public static final String PRIV_DELETE_ORDERS = PrivilegeConstants.DELETE_ORDERS; @Deprecated public static final String PRIV_PURGE_ORDERS = PrivilegeConstants.PURGE_ORDERS; @Deprecated public static final String PRIV_VIEW_FORMS = PrivilegeConstants.VIEW_FORMS; @Deprecated public static final String PRIV_MANAGE_FORMS = PrivilegeConstants.MANAGE_FORMS; @Deprecated public static final String PRIV_PURGE_FORMS = PrivilegeConstants.PURGE_FORMS; // This name is historic, since that's what it was originally called in the infopath formentry module @Deprecated public static final String PRIV_FORM_ENTRY = PrivilegeConstants.FORM_ENTRY; @Deprecated public static final String PRIV_VIEW_REPORTS = "View Reports"; @Deprecated public static final String PRIV_ADD_REPORTS = "Add Reports"; @Deprecated public static final String PRIV_EDIT_REPORTS = "Edit Reports"; @Deprecated public static final String PRIV_DELETE_REPORTS = "Delete Reports"; @Deprecated public static final String PRIV_RUN_REPORTS = "Run Reports"; @Deprecated public static final String PRIV_VIEW_REPORT_OBJECTS = "View Report Objects"; @Deprecated public static final String PRIV_ADD_REPORT_OBJECTS = "Add Report Objects"; @Deprecated public static final String PRIV_EDIT_REPORT_OBJECTS = "Edit Report Objects"; @Deprecated public static final String PRIV_DELETE_REPORT_OBJECTS = "Delete Report Objects"; @Deprecated public static final String PRIV_MANAGE_IDENTIFIER_TYPES = PrivilegeConstants.MANAGE_IDENTIFIER_TYPES; @Deprecated public static final String PRIV_VIEW_IDENTIFIER_TYPES = PrivilegeConstants.VIEW_IDENTIFIER_TYPES; @Deprecated public static final String PRIV_PURGE_IDENTIFIER_TYPES = PrivilegeConstants.PURGE_IDENTIFIER_TYPES; @Deprecated public static final String PRIV_MANAGE_MIME_TYPES = "Manage Mime Types"; @Deprecated public static final String PRIV_VIEW_CONCEPT_CLASSES = PrivilegeConstants.VIEW_CONCEPT_CLASSES; @Deprecated public static final String PRIV_MANAGE_CONCEPT_CLASSES = PrivilegeConstants.MANAGE_CONCEPT_CLASSES; @Deprecated public static final String PRIV_PURGE_CONCEPT_CLASSES = PrivilegeConstants.PURGE_CONCEPT_CLASSES; @Deprecated public static final String PRIV_VIEW_CONCEPT_DATATYPES = PrivilegeConstants.VIEW_CONCEPT_DATATYPES; @Deprecated public static final String PRIV_MANAGE_CONCEPT_DATATYPES = PrivilegeConstants.MANAGE_CONCEPT_DATATYPES; @Deprecated public static final String PRIV_PURGE_CONCEPT_DATATYPES = PrivilegeConstants.PURGE_CONCEPT_DATATYPES; @Deprecated public static final String PRIV_VIEW_PRIVILEGES = PrivilegeConstants.VIEW_PRIVILEGES; @Deprecated public static final String PRIV_MANAGE_PRIVILEGES = PrivilegeConstants.MANAGE_PRIVILEGES; @Deprecated public static final String PRIV_PURGE_PRIVILEGES = PrivilegeConstants.PURGE_PRIVILEGES; @Deprecated public static final String PRIV_VIEW_ROLES = PrivilegeConstants.VIEW_ROLES; @Deprecated public static final String PRIV_MANAGE_ROLES = PrivilegeConstants.MANAGE_ROLES; @Deprecated public static final String PRIV_PURGE_ROLES = PrivilegeConstants.PURGE_ROLES; @Deprecated public static final String PRIV_VIEW_FIELD_TYPES = PrivilegeConstants.VIEW_FIELD_TYPES; @Deprecated public static final String PRIV_MANAGE_FIELD_TYPES = PrivilegeConstants.MANAGE_FIELD_TYPES; @Deprecated public static final String PRIV_PURGE_FIELD_TYPES = PrivilegeConstants.PURGE_FIELD_TYPES; @Deprecated public static final String PRIV_VIEW_ORDER_TYPES = PrivilegeConstants.VIEW_ORDER_TYPES; @Deprecated public static final String PRIV_MANAGE_ORDER_TYPES = PrivilegeConstants.MANAGE_ORDER_TYPES; @Deprecated public static final String PRIV_PURGE_ORDER_TYPES = PrivilegeConstants.PURGE_ORDER_TYPES; @Deprecated public static final String PRIV_VIEW_RELATIONSHIP_TYPES = PrivilegeConstants.VIEW_RELATIONSHIP_TYPES; @Deprecated public static final String PRIV_MANAGE_RELATIONSHIP_TYPES = PrivilegeConstants.MANAGE_RELATIONSHIP_TYPES; @Deprecated public static final String PRIV_PURGE_RELATIONSHIP_TYPES = PrivilegeConstants.PURGE_RELATIONSHIP_TYPES; @Deprecated public static final String PRIV_MANAGE_ALERTS = PrivilegeConstants.MANAGE_ALERTS; @Deprecated public static final String PRIV_MANAGE_CONCEPT_SOURCES = PrivilegeConstants.MANAGE_CONCEPT_SOURCES; @Deprecated public static final String PRIV_VIEW_CONCEPT_SOURCES = PrivilegeConstants.VIEW_CONCEPT_SOURCES; @Deprecated public static final String PRIV_PURGE_CONCEPT_SOURCES = PrivilegeConstants.PURGE_CONCEPT_SOURCES; @Deprecated public static final String PRIV_VIEW_NAVIGATION_MENU = PrivilegeConstants.VIEW_NAVIGATION_MENU; @Deprecated public static final String PRIV_VIEW_ADMIN_FUNCTIONS = PrivilegeConstants.VIEW_ADMIN_FUNCTIONS; @Deprecated public static final String PRIV_VIEW_UNPUBLISHED_FORMS = PrivilegeConstants.VIEW_UNPUBLISHED_FORMS; @Deprecated public static final String PRIV_VIEW_PROGRAMS = PrivilegeConstants.VIEW_PROGRAMS; @Deprecated public static final String PRIV_MANAGE_PROGRAMS = PrivilegeConstants.MANAGE_PROGRAMS; @Deprecated public static final String PRIV_VIEW_PATIENT_PROGRAMS = PrivilegeConstants.VIEW_PATIENT_PROGRAMS; @Deprecated public static final String PRIV_ADD_PATIENT_PROGRAMS = PrivilegeConstants.ADD_PATIENT_PROGRAMS; @Deprecated public static final String PRIV_EDIT_PATIENT_PROGRAMS = PrivilegeConstants.EDIT_PATIENT_PROGRAMS; @Deprecated public static final String PRIV_DELETE_PATIENT_PROGRAMS = PrivilegeConstants.DELETE_PATIENT_PROGRAMS; @Deprecated public static final String PRIV_PURGE_PATIENT_PROGRAMS = PrivilegeConstants.PURGE_PATIENT_PROGRAMS; @Deprecated public static final String PRIV_DASHBOARD_OVERVIEW = PrivilegeConstants.DASHBOARD_OVERVIEW; @Deprecated public static final String PRIV_DASHBOARD_REGIMEN = PrivilegeConstants.DASHBOARD_REGIMEN; @Deprecated public static final String PRIV_DASHBOARD_ENCOUNTERS = PrivilegeConstants.DASHBOARD_ENCOUNTERS; @Deprecated public static final String PRIV_DASHBOARD_DEMOGRAPHICS = PrivilegeConstants.DASHBOARD_DEMOGRAPHICS; @Deprecated public static final String PRIV_DASHBOARD_GRAPHS = PrivilegeConstants.DASHBOARD_GRAPHS; @Deprecated public static final String PRIV_DASHBOARD_FORMS = PrivilegeConstants.DASHBOARD_FORMS; @Deprecated public static final String PRIV_DASHBOARD_SUMMARY = PrivilegeConstants.DASHBOARD_SUMMARY; @Deprecated public static final String PRIV_VIEW_GLOBAL_PROPERTIES = PrivilegeConstants.VIEW_GLOBAL_PROPERTIES; @Deprecated public static final String PRIV_MANAGE_GLOBAL_PROPERTIES = PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES; @Deprecated public static final String PRIV_PURGE_GLOBAL_PROPERTIES = PrivilegeConstants.PURGE_GLOBAL_PROPERTIES; @Deprecated public static final String PRIV_MANAGE_MODULES = PrivilegeConstants.MANAGE_MODULES; @Deprecated public static final String PRIV_MANAGE_SCHEDULER = PrivilegeConstants.MANAGE_SCHEDULER; @Deprecated public static final String PRIV_VIEW_PERSON_ATTRIBUTE_TYPES = PrivilegeConstants.VIEW_PERSON_ATTRIBUTE_TYPES; @Deprecated public static final String PRIV_MANAGE_PERSON_ATTRIBUTE_TYPES = PrivilegeConstants.MANAGE_PERSON_ATTRIBUTE_TYPES; @Deprecated public static final String PRIV_PURGE_PERSON_ATTRIBUTE_TYPES = PrivilegeConstants.PURGE_PERSON_ATTRIBUTE_TYPES; @Deprecated public static final String PRIV_VIEW_PERSONS = PrivilegeConstants.VIEW_PERSONS; @Deprecated public static final String PRIV_ADD_PERSONS = PrivilegeConstants.ADD_PERSONS; @Deprecated public static final String PRIV_EDIT_PERSONS = PrivilegeConstants.EDIT_PERSONS; @Deprecated public static final String PRIV_DELETE_PERSONS = PrivilegeConstants.DELETE_PERSONS; @Deprecated public static final String PRIV_PURGE_PERSONS = PrivilegeConstants.PURGE_PERSONS; /** * @deprecated replacing with ADD/EDIT/DELETE privileges */ @Deprecated public static final String PRIV_MANAGE_RELATIONSHIPS = "Manage Relationships"; @Deprecated public static final String PRIV_VIEW_RELATIONSHIPS = PrivilegeConstants.VIEW_RELATIONSHIPS; @Deprecated public static final String PRIV_ADD_RELATIONSHIPS = PrivilegeConstants.ADD_RELATIONSHIPS; @Deprecated public static final String PRIV_EDIT_RELATIONSHIPS = PrivilegeConstants.EDIT_RELATIONSHIPS; @Deprecated public static final String PRIV_DELETE_RELATIONSHIPS = PrivilegeConstants.DELETE_RELATIONSHIPS; @Deprecated public static final String PRIV_PURGE_RELATIONSHIPS = PrivilegeConstants.PURGE_RELATIONSHIPS; @Deprecated public static final String PRIV_VIEW_DATABASE_CHANGES = PrivilegeConstants.VIEW_DATABASE_CHANGES; @Deprecated public static final String PRIV_MANAGE_IMPLEMENTATION_ID = PrivilegeConstants.MANAGE_IMPLEMENTATION_ID; @Deprecated public static final String PRIV_SQL_LEVEL_ACCESS = PrivilegeConstants.SQL_LEVEL_ACCESS; @Deprecated public static final String PRIV_VIEW_PROBLEMS = PrivilegeConstants.VIEW_PROBLEMS; @Deprecated public static final String PRIV_ADD_PROBLEMS = PrivilegeConstants.ADD_PROBLEMS; @Deprecated public static final String PRIV_EDIT_PROBLEMS = PrivilegeConstants.EDIT_PROBLEMS; @Deprecated public static final String PRIV_DELETE_PROBLEMS = PrivilegeConstants.DELETE_PROBLEMS; @Deprecated public static final String PRIV_VIEW_ALLERGIES = PrivilegeConstants.VIEW_ALLERGIES; @Deprecated public static final String PRIV_ADD_ALLERGIES = PrivilegeConstants.ADD_ALLERGIES; @Deprecated public static final String PRIV_EDIT_ALLERGIES = PrivilegeConstants.EDIT_ALLERGIES; @Deprecated public static final String PRIV_DELETE_ALLERGIES = PrivilegeConstants.DELETE_ALLERGIES; /** * These are the privileges that are required by OpenMRS. Upon startup, if any of these * privileges do not exist in the database, they are inserted. These privileges are not allowed * to be deleted. They are marked as 'locked' in the administration screens. * * @return privileges core to the system */ @Deprecated public static final Map<String, String> CORE_PRIVILEGES() { return OpenmrsUtil.getCorePrivileges(); } // Baked in Roles: @Deprecated public static final String SUPERUSER_ROLE = RoleConstants.SUPERUSER; @Deprecated public static final String ANONYMOUS_ROLE = RoleConstants.ANONYMOUS; @Deprecated public static final String AUTHENTICATED_ROLE = RoleConstants.AUTHENTICATED; @Deprecated public static final String PROVIDER_ROLE = RoleConstants.PROVIDER; /** * All roles returned by this method are inserted into the database if they do not exist * already. These roles are also forbidden to be deleted from the administration screens. * * @return roles that are core to the system */ @Deprecated public static final Map<String, String> CORE_ROLES() { return OpenmrsUtil.getCoreRoles(); } /** * These roles are given to a user automatically and cannot be assigned * * @return <code>Collection<String></code> of the auto-assigned roles */ public static final Collection<String> AUTO_ROLES() { List<String> roles = new Vector<String>(); roles.add(ANONYMOUS_ROLE); roles.add(AUTHENTICATED_ROLE); return roles; } public static final String GLOBAL_PROPERTY_DRUG_FREQUENCIES = "dashboard.regimen.displayFrequencies"; public static final String GLOBAL_PROPERTY_CONCEPTS_LOCKED = "concepts.locked"; public static final String GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES = "patient.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES = "patient.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES = "patient.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES = "user.listingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES = "user.viewingAttributeTypes"; public static final String GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES = "user.headerAttributeTypes"; public static final String GLOBAL_PROPERTY_HL7_ARCHIVE_DIRECTORY = "hl7_archive.dir"; public static final String GLOBAL_PROPERTY_DEFAULT_THEME = "default_theme"; public static final String GLOBAL_PROPERTY_APPLICATION_NAME = "application.name"; /** * Array of all core global property names that represent comma-separated lists of * PersonAttributeTypes. (If you rename a PersonAttributeType then these global properties are * potentially modified.) */ public static final String[] GLOBAL_PROPERTIES_OF_PERSON_ATTRIBUTES = { GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES }; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX = "patient.identifierRegex"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX = "patient.identifierPrefix"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX = "patient.identifierSuffix"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SEARCH_PATTERN = "patient.identifierSearchPattern"; public static final String GLOBAL_PROPERTY_PATIENT_NAME_REGEX = "patient.nameValidationRegex"; public static final String GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS = "person.searchMaxResults"; public static final int GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE = 1000; public static final String GLOBAL_PROPERTY_GZIP_ENABLED = "gzip.enabled"; public static final String GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS = "concept.medicalRecordObservations"; public static final String GLOBAL_PROPERTY_PROBLEM_LIST = "concept.problemList"; @Deprecated public static final String GLOBAL_PROPERTY_REPORT_XML_MACROS = "report.xmlMacros"; public static final String GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS = "dashboard.regimen.standardRegimens"; public static final String GLOBAL_PROPERTY_SHOW_PATIENT_NAME = "dashboard.showPatientName"; public static final String GLOBAL_PROPERTY_ENABLE_VISITS = "visits.enabled"; public static final String GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR = "patient.defaultPatientIdentifierValidator"; public static final String GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES = "patient_identifier.importantTypes"; public static final String GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER = "encounterForm.obsSortOrder"; public static final String GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST = "locale.allowed.list"; public static final String GLOBAL_PROPERTY_IMPLEMENTATION_ID = "implementation_id"; public static final String GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS = "newPatientForm.relationships"; public static final String GLOBAL_PROPERTY_COMPLEX_OBS_DIR = "obs.complex_obs_dir"; public static final String GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS = "minSearchCharacters"; public static final int GLOBAL_PROPERTY_DEFAULT_MIN_SEARCH_CHARACTERS = 3; public static final String GLOBAL_PROPERTY_DEFAULT_LOCALE = "default_locale"; public static final String GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME = "default_location"; public static final String GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE = "en_GB"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE = "patientSearch.matchMode"; public static final String GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_ANYWHERE = "ANYWHERE"; public static final String GLOBAL_PROPERTY_DEFAULT_SERIALIZER = "serialization.defaultSerializer"; public static final String GLOBAL_PROPERTY_IGNORE_MISSING_NONLOCAL_PATIENTS = "hl7_processor.ignore_missing_patient_non_local"; public static final String GLOBAL_PROPERTY_TRUE_CONCEPT = "concept.true"; public static final String GLOBAL_PROPERTY_FALSE_CONCEPT = "concept.false"; public static final String GLOBAL_PROPERTY_LOCATION_WIDGET_TYPE = "location.field.style"; public static final String GLOBAL_PROPERTY_REPORT_BUG_URL = "reportProblem.url"; public static final String GLOBAL_PROPERTY_ADDRESS_TEMPLATE = "layout.address.format"; public static final String DEFAULT_ADDRESS_TEMPLATE = "<addressTemplate>\n" + " <nameMappings class=\"properties\">\n" + " <property name=\"postalCode\" value=\"Location.postalCode\"/>\n" + " <property name=\"longitude\" value=\"Location.longitude\"/>\n" + " <property name=\"address2\" value=\"Location.address2\"/>\n" + " <property name=\"address1\" value=\"Location.address1\"/>\n" + " <property name=\"startDate\" value=\"PersonAddress.startDate\"/>\n" + " <property name=\"country\" value=\"Location.country\"/>\n" + " <property name=\"endDate\" value=\"personAddress.endDate\"/>\n" + " <property name=\"stateProvince\" value=\"Location.stateProvince\"/>\n" + " <property name=\"latitude\" value=\"Location.latitude\"/>\n" + " <property name=\"cityVillage\" value=\"Location.cityVillage\"/>\n" + " </nameMappings>\n" + " <sizeMappings class=\"properties\">\n" + " <property name=\"postalCode\" value=\"10\"/>\n" + " <property name=\"longitude\" value=\"10\"/>\n" + " <property name=\"address2\" value=\"40\"/>\n" + " <property name=\"address1\" value=\"40\"/>\n" + " <property name=\"startDate\" value=\"10\"/>\n" + " <property name=\"country\" value=\"10\"/>\n" + " <property name=\"endDate\" value=\"10\"/>\n" + " <property name=\"stateProvince\" value=\"10\"/>\n" + " <property name=\"latitude\" value=\"10\"/>\n" + " <property name=\"cityVillage\" value=\"10\"/>\n" + " </sizeMappings>\n" + " <lineByLineFormat>\n" + " <string>address1</string>\n" + " <string>address2</string>\n" + " <string>cityVillage stateProvince country postalCode</string>\n" + " <string>latitude longitude</string>\n" + " <string>startDate endDate</string>\n" + " </lineByLineFormat>\n" + " </addressTemplate>"; /** * Global property name that allows specification of whether user passwords must contain both * upper and lower case characters. Allowable values are "true", "false", and null */ public static String GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE = "security.passwordRequiresUpperAndLowerCase"; /** * Global property name that allows specification of whether user passwords require non-digits. * Allowable values are "true", "false", and null */ public static String GP_PASSWORD_REQUIRES_NON_DIGIT = "security.passwordRequiresNonDigit"; /** * Global property name that allows specification of whether user passwords must contain digits. * Allowable values are "true", "false", and null */ public static String GP_PASSWORD_REQUIRES_DIGIT = "security.passwordRequiresDigit"; /** * Global property name that allows specification of whether user passwords can match username * or system id. Allowable values are "true", "false", and null */ public static String GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID = "security.passwordCannotMatchUsername"; /** * Global property name that allows specification of whether user passwords have a minimum * length requirement Allowable values are any integer */ public static String GP_PASSWORD_MINIMUM_LENGTH = "security.passwordMinimumLength"; /** * Global property name that allows specification of a regular expression that passwords must * adhere to */ public static String GP_PASSWORD_CUSTOM_REGEX = "security.passwordCustomRegex"; /** * Global property name for absolute color for patient graphs. */ public static final String GP_GRAPH_COLOR_ABSOLUTE = "graph.color.absolute"; /** * Global property name for normal color for patient graphs. */ public static final String GP_GRAPH_COLOR_NORMAL = "graph.color.normal"; /** * Global property name for critical color for patient graphs. */ public static final String GP_GRAPH_COLOR_CRITICAL = "graph.color.critical"; /** * Global property name for the maximum number of search results that are returned by a single * ajax call */ public static final String GP_SEARCH_WIDGET_BATCH_SIZE = "searchWidget.batchSize"; /** * Global property name for the mode the search widgets should run in, this depends on the speed * of the network's connection */ public static final String GP_SEARCH_WIDGET_IN_SERIAL_MODE = "searchWidget.runInSerialMode"; /** * Global property name for the time interval in milliseconds between key up and triggering the * search off */ public static final String GP_SEARCH_WIDGET_DELAY_INTERVAL = "searchWidget.searchDelayInterval"; /** * Global property name for the maximum number of results to return from a single search in the * search widgets */ public static final String GP_SEARCH_WIDGET_MAXIMUM_RESULTS = "searchWidget.maximumResults"; /** * Global property name for enabling/disabling concept map type management */ public static final String GP_ENABLE_CONCEPT_MAP_TYPE_MANAGEMENT = "concept_map_type_management.enable"; /** * Global property name for the handler that assigns visits to encounters */ public static final String GP_VISIT_ASSIGNMENT_HANDLER = "visits.assignmentHandler"; /** * Global property name for mapping encounter types to visit types. */ public static final String GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING = "visits.encounterTypeToVisitTypeMapping"; /** * Global property name for the encounter roles to display on the provider column of the patient * dashboard under the encounters tab. */ public static final String GP_DASHBOARD_PROVIDER_DISPLAY_ENCOUNTER_ROLES = "dashboard.encounters.providerDisplayRoles"; /** * Global property name for optional configuration of the maximum number of encounters to * display on the encounter tab of the patient dashboard */ public static final String GP_DASHBOARD_MAX_NUMBER_OF_ENCOUNTERS_TO_SHOW = "dashboard.encounters.maximumNumberToShow"; /** * Encryption properties; both vector and key are required to utilize a two-way encryption */ public static final String ENCRYPTION_CIPHER_CONFIGURATION = "AES/CBC/PKCS5Padding"; public static final String ENCRYPTION_KEY_SPEC = "AES"; public static final String ENCRYPTION_VECTOR_RUNTIME_PROPERTY = "encryption.vector"; public static final String ENCRYPTION_VECTOR_DEFAULT = "9wyBUNglFCRVSUhMfsTa3Q=="; public static final String ENCRYPTION_KEY_RUNTIME_PROPERTY = "encryption.key"; public static final String ENCRYPTION_KEY_DEFAULT = "dTfyELRrAICGDwzjHDjuhw=="; /** * Global property name for option to enable or disable the scheduled task that automatically * closes open visits */ public static final String GP_ENABLE_AUTO_CLOSE_OPEN_VISITS_TASK = "autoCloseOpenVisitsTask.enable"; /** * Global property name for the visit type(s) to automatically close */ public static final String GP_VISIT_TYPES_TO_AUTO_CLOSE = "autoCloseOpenVisits.visitType"; /** * The name of the scheduled task that automatically stops the active visits */ public static final String AUTO_CLOSE_OPEN_VISIT_TASK_NAME = "Auto Close Open Visits Task"; public static final String GP_CONCEPT_INDEX_UPDATE_TASK_LAST_UPDATED_CONCEPT = "conceptIndexUpdateTask.lastConceptUpdated"; /** * At OpenMRS startup these global properties/default values/descriptions are inserted into the * database if they do not exist yet. * * @return List<GlobalProperty> of the core global properties */ public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients", BooleanDatatype.class, null)); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient", BooleanDatatype.class, null)); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DRUG_FREQUENCIES, "7 days/week,6 days/week,5 days/week,4 days/week,3 days/week,2 days/week,1 days/week", "Frequency of a drug order that appear on the Patient Dashboard. Comma separated list of name of concepts that are defined as drug frequencies.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_ABSOLUTE, "rgb(20,20,20)", "Color of the 'invalid' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_NORMAL, "rgb(255,126,0)", "Color of the 'normal' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_CRITICAL, "rgb(200,0,0)", "Color of the 'critical' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCATION_WIDGET_TYPE, "default", "Type of widget to use for location fields")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props.add(new GlobalProperty(GLOBAL_PROPERTY_ADDRESS_TEMPLATE, DEFAULT_ADDRESS_TEMPLATE, "XML description of address formats")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "if true, do not allow editing concepts", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "", "WARNING: Using this search property can cause a drop in mysql performance with large patient sets. A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used. Example: ^0*@SEARCH@([A-Z]+-[0-9])?$")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SEARCH_PATTERN, "", "If this is empty, the regex or suffix/prefix search is used. Comma separated list of identifiers to check. Allows for faster searching of multiple options rather than the slow regex. e.g. @SEARCH@,0@SEARCH@,@SEARCH-1@-@CHECKDIGIT@,0@SEARCH-1@-@CHECKDIGIT@ would turn a request for \"4127\" into a search for \"in ('4127','04127','412-7','0412-7')\"")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_NAME_REGEX, "^[a-zA-Z \\-]+$", "Names of the patients must pass this regex. Eg : ^[a-zA-Z \\-]+$ contains only english alphabet letters, spaces, and hyphens. A value of .* or the empty string means no validation is done.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS, String .valueOf(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE), "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.", BooleanDatatype.class, null)); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, "org.openmrs.api:" + LOG_LEVEL_INFO, "Logging levels for log4j.xml. Valid format is class:level,class:level. If class not specified, 'org.openmrs.api' presumed. Valid levels are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); props.add(new GlobalProperty(GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, "true", "Configure whether passwords must not match user's username or system id", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_CUSTOM_REGEX, "", "Configure a custom regular expression that a password must match")); props.add(new GlobalProperty(GP_PASSWORD_MINIMUM_LENGTH, "8", "Configure the minimum length required of all passwords")); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_DIGIT, "true", "Configure whether passwords must contain at least one digit", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_NON_DIGIT, "true", "Configure whether passwords must contain at least one non-digit", BooleanDatatype.class, null)); props .add(new GlobalProperty(GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, "true", "Configure whether passwords must contain both upper and lower case characters", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_IGNORE_MISSING_NONLOCAL_PATIENTS, "false", "If true, hl7 messages for patients that are not found and are non-local will silently be dropped/ignored", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_SHOW_PATIENT_NAME, "false", "Whether or not to display the patient name in the patient dashboard title. Note that enabling this could be security risk if multiple users operate on the same computer.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_THEME, "", "Default theme for users. OpenMRS ships with themes of 'green', 'orange', 'purple', and 'legacy'")); props.add(new GlobalProperty(GLOBAL_PROPERTY_HL7_ARCHIVE_DIRECTORY, HL7Constants.HL7_ARCHIVE_DIRECTORY_NAME, "The default name or absolute path for the folder where to write the hl7_in_archives.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_BUG_URL, "http://errors.openmrs.org/scrap", "The openmrs url where to submit bug reports")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_BATCH_SIZE, "200", "The maximum number of search results that are returned by an ajax call")); props .add(new GlobalProperty( GP_SEARCH_WIDGET_IN_SERIAL_MODE, "true", "Specifies whether the search widgets should make ajax requests in serial or parallel order, a value of true is appropriate for implementations running on a slow network connection and vice versa", BooleanDatatype.class, null)); props .add(new GlobalProperty( GP_SEARCH_WIDGET_DELAY_INTERVAL, "400", "Specifies time interval in milliseconds when searching, between keyboard keyup event and triggering the search off, should be higher if most users are slow when typing so as to minimise the load on the server")); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME, "Unknown Location", "The name of the location to use as a system default")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE, "START", "Specifies how patient names are matched while searching patient. Valid values are 'ANYWHERE' or 'START'. Defaults to start if missing or invalid value is present.")); props.add(new GlobalProperty(GP_ENABLE_CONCEPT_MAP_TYPE_MANAGEMENT, "false", - "Enable or disables management of concept map types", BooleanDatatype.class, null)); + "Enables or disables management of concept map types", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENABLE_VISITS, "true", "Set to true to enable the Visits feature. This will replace the 'Encounters' tab with a 'Visits' tab on the dashboard.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_ASSIGNMENT_HANDLER, ExistingVisitAssignmentHandler.class.getName(), "Set to the name of the class responsible for assigning encounters to visits.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_APPLICATION_NAME, "OpenMRS", "The name of this application, as presented to the user, for example on the login and welcome pages.")); props .add(new GlobalProperty( GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "", "Specifies how encounter types are mapped to visit types when automatically assigning encounters to visits. e.g 1:1, 2:1, 3:2 in the format encounterTypeId:visitTypeId")); props .add(new GlobalProperty( GP_DASHBOARD_PROVIDER_DISPLAY_ENCOUNTER_ROLES, "", "A comma-separated list of encounter roles (by name or id). Providers with these roles in an encounter will be displayed on the encounter tab of the patient dashboard.")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_MAXIMUM_RESULTS, "2000", "Specifies the maximum number of results to return from a single search in the search widgets")); props .add(new GlobalProperty( GP_DASHBOARD_MAX_NUMBER_OF_ENCOUNTERS_TO_SHOW, "", "An integer which, if specified, would determine the maximum number of encounters to display on the encounter tab of the patient dashboard.")); props .add(new GlobalProperty( GP_ENABLE_AUTO_CLOSE_OPEN_VISITS_TASK, "false", "Enables or disables the scheduled task that automatically stops any active visits of the specified visit type(s)", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_TYPES_TO_AUTO_CLOSE, "", "comma-separated list of the visit type(s) to automatically close")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; } // ConceptProposal proposed concept identifier keyword public static final String PROPOSED_CONCEPT_IDENTIFIER = "PROPOSED"; // ConceptProposal states public static final String CONCEPT_PROPOSAL_UNMAPPED = "UNMAPPED"; public static final String CONCEPT_PROPOSAL_CONCEPT = "CONCEPT"; public static final String CONCEPT_PROPOSAL_SYNONYM = "SYNONYM"; public static final String CONCEPT_PROPOSAL_REJECT = "REJECT"; public static final Collection<String> CONCEPT_PROPOSAL_STATES() { Collection<String> states = new Vector<String>(); states.add(CONCEPT_PROPOSAL_UNMAPPED); states.add(CONCEPT_PROPOSAL_CONCEPT); states.add(CONCEPT_PROPOSAL_SYNONYM); states.add(CONCEPT_PROPOSAL_REJECT); return states; } public static Locale SPANISH_LANGUAGE = new Locale("es"); public static Locale PORTUGUESE_LANGUAGE = new Locale("pt"); public static Locale ITALIAN_LANGUAGE = new Locale("it"); /** * @return Collection of locales available to openmrs * @deprecated */ public static final Collection<Locale> OPENMRS_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.US); languages.add(Locale.UK); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } /** * @deprecated use {@link LocaleUtility#getDefaultLocale()} */ public static final Locale GLOBAL_DEFAULT_LOCALE = LocaleUtility.DEFAULT_LOCALE; /** * @return Collection of locales that the concept dictionary should be aware of * @see ConceptService#getLocalesOfConceptNames() * @deprecated */ public static final Collection<Locale> OPENMRS_CONCEPT_LOCALES() { List<Locale> languages = new Vector<Locale>(); languages.add(Locale.ENGLISH); languages.add(Locale.FRENCH); languages.add(SPANISH_LANGUAGE); languages.add(PORTUGUESE_LANGUAGE); languages.add(ITALIAN_LANGUAGE); return languages; } @Deprecated private static Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS = null; /** * @return Mapping of Locales to locale specific date pattern * @deprecated use the {@link org.openmrs.api.context.Context#getDateFormat()} */ public static final Map<String, String> OPENMRS_LOCALE_DATE_PATTERNS() { if (OPENMRS_LOCALE_DATE_PATTERNS == null) { Map<String, String> patterns = new HashMap<String, String>(); patterns.put(Locale.US.toString().toLowerCase(), "MM/dd/yyyy"); patterns.put(Locale.UK.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.FRENCH.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(Locale.GERMAN.toString().toLowerCase(), "MM.dd.yyyy"); patterns.put(SPANISH_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(PORTUGUESE_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); patterns.put(ITALIAN_LANGUAGE.toString().toLowerCase(), "dd/MM/yyyy"); OPENMRS_LOCALE_DATE_PATTERNS = patterns; } return OPENMRS_LOCALE_DATE_PATTERNS; } /* * User property names */ public static final String USER_PROPERTY_CHANGE_PASSWORD = "forcePassword"; public static final String USER_PROPERTY_DEFAULT_LOCALE = "defaultLocale"; public static final String USER_PROPERTY_DEFAULT_LOCATION = "defaultLocation"; public static final String USER_PROPERTY_SHOW_RETIRED = "showRetired"; public static final String USER_PROPERTY_SHOW_VERBOSE = "showVerbose"; public static final String USER_PROPERTY_NOTIFICATION = "notification"; public static final String USER_PROPERTY_NOTIFICATION_ADDRESS = "notificationAddress"; public static final String USER_PROPERTY_NOTIFICATION_FORMAT = "notificationFormat"; // text/plain, text/html /** * Name of the user_property that stores the number of unsuccessful login attempts this user has * made */ public static final String USER_PROPERTY_LOGIN_ATTEMPTS = "loginAttempts"; /** * Name of the user_property that stores the time the user was locked out due to too many login * attempts */ public static final String USER_PROPERTY_LOCKOUT_TIMESTAMP = "lockoutTimestamp"; /** * A user property name. The value should be a comma-separated ordered list of fully qualified * locales within which the user is a proficient speaker. The list should be ordered from the * most to the least proficiency. Example: * <code>proficientLocales = en_US, en_GB, en, fr_RW</code> */ public static final String USER_PROPERTY_PROFICIENT_LOCALES = "proficientLocales"; /** * Report object properties */ @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTFILTER = "Patient Filter"; @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTSEARCH = "Patient Search"; @Deprecated public static final String REPORT_OBJECT_TYPE_PATIENTDATAPRODUCER = "Patient Data Producer"; // Used for differences between windows/linux upload capabilities) // Used for determining where to find runtime properties public static final String OPERATING_SYSTEM_KEY = "os.name"; public static final String OPERATING_SYSTEM = System.getProperty(OPERATING_SYSTEM_KEY); public static final String OPERATING_SYSTEM_WINDOWS_XP = "Windows XP"; public static final String OPERATING_SYSTEM_WINDOWS_VISTA = "Windows Vista"; public static final String OPERATING_SYSTEM_LINUX = "Linux"; public static final String OPERATING_SYSTEM_SUNOS = "SunOS"; public static final String OPERATING_SYSTEM_FREEBSD = "FreeBSD"; public static final String OPERATING_SYSTEM_OSX = "Mac OS X"; /** * URL to the concept source id verification server */ public static final String IMPLEMENTATION_ID_REMOTE_CONNECTION_URL = "http://resources.openmrs.org/tools/implementationid"; /** * Shortcut booleans used to make some OS specific checks more generic; note the *nix flavored * check is missing some less obvious choices */ public static final boolean UNIX_BASED_OPERATING_SYSTEM = (OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_LINUX) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_SUNOS) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_FREEBSD) > -1 || OPERATING_SYSTEM.indexOf(OPERATING_SYSTEM_OSX) > -1); public static final boolean WINDOWS_BASED_OPERATING_SYSTEM = OPERATING_SYSTEM.indexOf("Windows") > -1; public static final boolean WINDOWS_VISTA_OPERATING_SYSTEM = OPERATING_SYSTEM.equals(OPERATING_SYSTEM_WINDOWS_VISTA); /** * Marker put into the serialization session map to tell @Replace methods whether or not to do * just the very basic serialization */ public static final String SHORT_SERIALIZATION = "isShortSerialization"; // Global property key for global logger level public static final String GLOBAL_PROPERTY_LOG_LEVEL = "log.level"; // Global logger category public static final String LOG_CLASS_DEFAULT = "org.openmrs.api"; // Log levels public static final String LOG_LEVEL_TRACE = "trace"; public static final String LOG_LEVEL_DEBUG = "debug"; public static final String LOG_LEVEL_INFO = "info"; public static final String LOG_LEVEL_WARN = "warn"; public static final String LOG_LEVEL_ERROR = "error"; public static final String LOG_LEVEL_FATAL = "fatal"; /** * These enumerations should be used in ObsService and PersonService getters to help determine * which type of object to restrict on * * @see org.openmrs.api.ObsService * @see org.openmrs.api.PersonService */ public static enum PERSON_TYPE { PERSON, PATIENT, USER } //Patient Identifier Validators public static final String LUHN_IDENTIFIER_VALIDATOR = LuhnIdentifierValidator.class.getName(); // ComplexObsHandler views public static final String RAW_VIEW = "RAW_VIEW"; public static final String TEXT_VIEW = "TEXT_VIEW"; }
true
true
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients", BooleanDatatype.class, null)); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient", BooleanDatatype.class, null)); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DRUG_FREQUENCIES, "7 days/week,6 days/week,5 days/week,4 days/week,3 days/week,2 days/week,1 days/week", "Frequency of a drug order that appear on the Patient Dashboard. Comma separated list of name of concepts that are defined as drug frequencies.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_ABSOLUTE, "rgb(20,20,20)", "Color of the 'invalid' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_NORMAL, "rgb(255,126,0)", "Color of the 'normal' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_CRITICAL, "rgb(200,0,0)", "Color of the 'critical' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCATION_WIDGET_TYPE, "default", "Type of widget to use for location fields")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props.add(new GlobalProperty(GLOBAL_PROPERTY_ADDRESS_TEMPLATE, DEFAULT_ADDRESS_TEMPLATE, "XML description of address formats")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "if true, do not allow editing concepts", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "", "WARNING: Using this search property can cause a drop in mysql performance with large patient sets. A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used. Example: ^0*@SEARCH@([A-Z]+-[0-9])?$")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SEARCH_PATTERN, "", "If this is empty, the regex or suffix/prefix search is used. Comma separated list of identifiers to check. Allows for faster searching of multiple options rather than the slow regex. e.g. @SEARCH@,0@SEARCH@,@SEARCH-1@-@CHECKDIGIT@,0@SEARCH-1@-@CHECKDIGIT@ would turn a request for \"4127\" into a search for \"in ('4127','04127','412-7','0412-7')\"")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_NAME_REGEX, "^[a-zA-Z \\-]+$", "Names of the patients must pass this regex. Eg : ^[a-zA-Z \\-]+$ contains only english alphabet letters, spaces, and hyphens. A value of .* or the empty string means no validation is done.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS, String .valueOf(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE), "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.", BooleanDatatype.class, null)); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, "org.openmrs.api:" + LOG_LEVEL_INFO, "Logging levels for log4j.xml. Valid format is class:level,class:level. If class not specified, 'org.openmrs.api' presumed. Valid levels are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); props.add(new GlobalProperty(GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, "true", "Configure whether passwords must not match user's username or system id", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_CUSTOM_REGEX, "", "Configure a custom regular expression that a password must match")); props.add(new GlobalProperty(GP_PASSWORD_MINIMUM_LENGTH, "8", "Configure the minimum length required of all passwords")); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_DIGIT, "true", "Configure whether passwords must contain at least one digit", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_NON_DIGIT, "true", "Configure whether passwords must contain at least one non-digit", BooleanDatatype.class, null)); props .add(new GlobalProperty(GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, "true", "Configure whether passwords must contain both upper and lower case characters", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_IGNORE_MISSING_NONLOCAL_PATIENTS, "false", "If true, hl7 messages for patients that are not found and are non-local will silently be dropped/ignored", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_SHOW_PATIENT_NAME, "false", "Whether or not to display the patient name in the patient dashboard title. Note that enabling this could be security risk if multiple users operate on the same computer.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_THEME, "", "Default theme for users. OpenMRS ships with themes of 'green', 'orange', 'purple', and 'legacy'")); props.add(new GlobalProperty(GLOBAL_PROPERTY_HL7_ARCHIVE_DIRECTORY, HL7Constants.HL7_ARCHIVE_DIRECTORY_NAME, "The default name or absolute path for the folder where to write the hl7_in_archives.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_BUG_URL, "http://errors.openmrs.org/scrap", "The openmrs url where to submit bug reports")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_BATCH_SIZE, "200", "The maximum number of search results that are returned by an ajax call")); props .add(new GlobalProperty( GP_SEARCH_WIDGET_IN_SERIAL_MODE, "true", "Specifies whether the search widgets should make ajax requests in serial or parallel order, a value of true is appropriate for implementations running on a slow network connection and vice versa", BooleanDatatype.class, null)); props .add(new GlobalProperty( GP_SEARCH_WIDGET_DELAY_INTERVAL, "400", "Specifies time interval in milliseconds when searching, between keyboard keyup event and triggering the search off, should be higher if most users are slow when typing so as to minimise the load on the server")); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME, "Unknown Location", "The name of the location to use as a system default")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE, "START", "Specifies how patient names are matched while searching patient. Valid values are 'ANYWHERE' or 'START'. Defaults to start if missing or invalid value is present.")); props.add(new GlobalProperty(GP_ENABLE_CONCEPT_MAP_TYPE_MANAGEMENT, "false", "Enable or disables management of concept map types", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENABLE_VISITS, "true", "Set to true to enable the Visits feature. This will replace the 'Encounters' tab with a 'Visits' tab on the dashboard.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_ASSIGNMENT_HANDLER, ExistingVisitAssignmentHandler.class.getName(), "Set to the name of the class responsible for assigning encounters to visits.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_APPLICATION_NAME, "OpenMRS", "The name of this application, as presented to the user, for example on the login and welcome pages.")); props .add(new GlobalProperty( GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "", "Specifies how encounter types are mapped to visit types when automatically assigning encounters to visits. e.g 1:1, 2:1, 3:2 in the format encounterTypeId:visitTypeId")); props .add(new GlobalProperty( GP_DASHBOARD_PROVIDER_DISPLAY_ENCOUNTER_ROLES, "", "A comma-separated list of encounter roles (by name or id). Providers with these roles in an encounter will be displayed on the encounter tab of the patient dashboard.")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_MAXIMUM_RESULTS, "2000", "Specifies the maximum number of results to return from a single search in the search widgets")); props .add(new GlobalProperty( GP_DASHBOARD_MAX_NUMBER_OF_ENCOUNTERS_TO_SHOW, "", "An integer which, if specified, would determine the maximum number of encounters to display on the encounter tab of the patient dashboard.")); props .add(new GlobalProperty( GP_ENABLE_AUTO_CLOSE_OPEN_VISITS_TASK, "false", "Enables or disables the scheduled task that automatically stops any active visits of the specified visit type(s)", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_TYPES_TO_AUTO_CLOSE, "", "comma-separated list of the visit type(s) to automatically close")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
public static final List<GlobalProperty> CORE_GLOBAL_PROPERTIES() { List<GlobalProperty> props = new Vector<GlobalProperty>(); props.add(new GlobalProperty("use_patient_attribute.healthCenter", "false", "Indicates whether or not the 'health center' attribute is shown when viewing/searching for patients", BooleanDatatype.class, null)); props.add(new GlobalProperty("use_patient_attribute.mothersName", "false", "Indicates whether or not mother's name is able to be added/viewed for a patient", BooleanDatatype.class, null)); props.add(new GlobalProperty("new_patient_form.showRelationships", "false", "true/false whether or not to show the relationship editor on the addPatient.htm screen", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.overview.showConcepts", "", "Comma delimited list of concepts ids to show on the patient dashboard overview tab")); props .add(new GlobalProperty("dashboard.encounters.showEmptyFields", "true", "true/false whether or not to show empty fields on the 'View Encounter' window", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.encounters.usePages", "smart", "true/false/smart on how to show the pages on the 'View Encounter' window. 'smart' means that if > 50% of the fields have page numbers defined, show data in pages")); props.add(new GlobalProperty("dashboard.encounters.showViewLink", "true", "true/false whether or not to show the 'View Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("dashboard.encounters.showEditLink", "true", "true/false whether or not to show the 'Edit Encounter' link on the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.header.programs_to_show", "", "List of programs to show Enrollment details of in the patient header. (Should be an ordered comma-separated list of program_ids or names.)")); props .add(new GlobalProperty( "dashboard.header.workflows_to_show", "", "List of programs to show Enrollment details of in the patient header. List of workflows to show current status of in the patient header. These will only be displayed if they belong to a program listed above. (Should be a comma-separated list of program_workflow_ids.)")); props.add(new GlobalProperty("dashboard.relationships.show_types", "", "Types of relationships separated by commas. Doctor/Patient,Parent/Child")); props.add(new GlobalProperty("FormEntry.enableDashboardTab", "true", "true/false whether or not to show a Form Entry tab on the patient dashboard", BooleanDatatype.class, null)); props.add(new GlobalProperty("FormEntry.enableOnEncounterTab", "false", "true/false whether or not to show a Enter Form button on the encounters tab of the patient dashboard", BooleanDatatype.class, null)); props .add(new GlobalProperty( "dashboard.regimen.displayDrugSetIds", "ANTIRETROVIRAL DRUGS,TUBERCULOSIS TREATMENT DRUGS", "Drug sets that appear on the Patient Dashboard Regimen tab. Comma separated list of name of concepts that are defined as drug sets.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DRUG_FREQUENCIES, "7 days/week,6 days/week,5 days/week,4 days/week,3 days/week,2 days/week,1 days/week", "Frequency of a drug order that appear on the Patient Dashboard. Comma separated list of name of concepts that are defined as drug frequencies.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_ABSOLUTE, "rgb(20,20,20)", "Color of the 'invalid' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_NORMAL, "rgb(255,126,0)", "Color of the 'normal' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GP_GRAPH_COLOR_CRITICAL, "rgb(200,0,0)", "Color of the 'critical' section of numeric graphs on the patient dashboard.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCATION_WIDGET_TYPE, "default", "Type of widget to use for location fields")); String standardRegimens = "<list>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>2</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(30) + NVP (Triomune-30)</displayName>" + " <codeName>standardTri30</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>3</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>3TC + d4T(40) + NVP (Triomune-40)</displayName>" + " <codeName>standardTri40</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>39</drugId>" + " <dose>1</dose>" + " <units>tab(s)</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>22</drugId>" + " <dose>200</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + NVP</displayName>" + " <codeName>standardAztNvp</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion reference=\"../../../regimenSuggestion[3]/drugComponents/drugSuggestion\"/>" + " <drugSuggestion>" + " <drugId>11</drugId>" + " <dose>600</dose>" + " <units>mg</units>" + " <frequency>1/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " </drugComponents>" + " <displayName>AZT + 3TC + EFV(600)</displayName>" + " <codeName>standardAztEfv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>5</drugId>" + " <dose>30</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion>" + " <drugId>42</drugId>" + " <dose>150</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(30) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t30Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + " <regimenSuggestion>" + " <drugComponents>" + " <drugSuggestion>" + " <drugId>6</drugId>" + " <dose>40</dose>" + " <units>mg</units>" + " <frequency>2/day x 7 days/week</frequency>" + " <instructions></instructions>" + " </drugSuggestion>" + " <drugSuggestion reference=\"../../../regimenSuggestion[5]/drugComponents/drugSuggestion[2]\"/>" + " <drugSuggestion reference=\"../../../regimenSuggestion[4]/drugComponents/drugSuggestion[2]\"/>" + " </drugComponents>" + " <displayName>d4T(40) + 3TC + EFV(600)</displayName>" + " <codeName>standardD4t40Efv</codeName>" + " <canReplace>ANTIRETROVIRAL DRUGS</canReplace>" + " </regimenSuggestion>" + "</list>"; props.add(new GlobalProperty(GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS, standardRegimens, "XML description of standard drug regimens, to be shown as shortcuts on the dashboard regimen entry tab")); props.add(new GlobalProperty("concept.weight", "5089", "Concept id of the concept defining the WEIGHT concept")); props.add(new GlobalProperty("concept.height", "5090", "Concept id of the concept defining the HEIGHT concept")); props .add(new GlobalProperty("concept.cd4_count", "5497", "Concept id of the concept defining the CD4 count concept")); props.add(new GlobalProperty("concept.causeOfDeath", "5002", "Concept id of the concept defining the CAUSE OF DEATH concept")); props.add(new GlobalProperty("concept.none", "1107", "Concept id of the concept defining the NONE concept")); props.add(new GlobalProperty("concept.otherNonCoded", "5622", "Concept id of the concept defining the OTHER NON-CODED concept")); props.add(new GlobalProperty("concept.patientDied", "1742", "Concept id of the concept defining the PATIENT DIED concept")); props.add(new GlobalProperty("concept.reasonExitedCare", "", "Concept id of the concept defining the REASON EXITED CARE concept")); props.add(new GlobalProperty("concept.reasonOrderStopped", "1812", "Concept id of the concept defining the REASON ORDER STOPPED concept")); props.add(new GlobalProperty("mail.transport_protocol", "smtp", "Transport protocol for the messaging engine. Valid values: smtp")); props.add(new GlobalProperty("mail.smtp_host", "localhost", "SMTP host name")); props.add(new GlobalProperty("mail.smtp_port", "25", "SMTP port")); props.add(new GlobalProperty("mail.from", "[email protected]", "Email address to use as the default from address")); props.add(new GlobalProperty("mail.debug", "false", "true/false whether to print debugging information during mailing")); props.add(new GlobalProperty("mail.smtp_auth", "false", "true/false whether the smtp host requires authentication")); props.add(new GlobalProperty("mail.user", "test", "Username of the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.password", "test", "Password for the SMTP user (if smtp_auth is enabled)")); props.add(new GlobalProperty("mail.default_content_type", "text/plain", "Content type to append to the mail messages")); props.add(new GlobalProperty(ModuleConstants.REPOSITORY_FOLDER_PROPERTY, ModuleConstants.REPOSITORY_FOLDER_PROPERTY_DEFAULT, "Name of the folder in which to store the modules")); props.add(new GlobalProperty(GLOBAL_PROPERTY_ADDRESS_TEMPLATE, DEFAULT_ADDRESS_TEMPLATE, "XML description of address formats")); props.add(new GlobalProperty("layout.name.format", "short", "Format in which to display the person names. Valid values are short, long")); // TODO should be changed to text defaults and constants should be removed props.add(new GlobalProperty("scheduler.username", SchedulerConstants.SCHEDULER_DEFAULT_USERNAME, "Username for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty("scheduler.password", SchedulerConstants.SCHEDULER_DEFAULT_PASSWORD, "Password for the OpenMRS user that will perform the scheduler activities")); props.add(new GlobalProperty(GLOBAL_PROPERTY_CONCEPTS_LOCKED, "false", "if true, do not allow editing concepts", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for patients when _viewing individually_")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PATIENT_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the patient dashboard")); props.add(new GlobalProperty(GLOBAL_PROPERTY_USER_LISTING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users in _lists_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_VIEWING_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that should be displayed for users when _viewing individually_")); props .add(new GlobalProperty(GLOBAL_PROPERTY_USER_HEADER_ATTRIBUTES, "", "A comma delimited list of PersonAttributeType names that will be shown on the user dashboard. (not used in v1.5)")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX, "", "WARNING: Using this search property can cause a drop in mysql performance with large patient sets. A MySQL regular expression for the patient identifier search strings. The @SEARCH@ string is replaced at runtime with the user's search string. An empty regex will cause a simply 'like' sql search to be used. Example: ^0*@SEARCH@([A-Z]+-[0-9])?$")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SUFFIX, "", "This property is only used if " + GLOBAL_PROPERTY_PATIENT_IDENTIFIER_REGEX + " is empty. The string here is prepended to the sql indentifier search string. The sql becomes \"... where identifier like '<PREFIX><QUERY STRING><SUFFIX>';\". Typically this value is either a percent sign (%) or empty.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_SEARCH_PATTERN, "", "If this is empty, the regex or suffix/prefix search is used. Comma separated list of identifiers to check. Allows for faster searching of multiple options rather than the slow regex. e.g. @SEARCH@,0@SEARCH@,@SEARCH-1@-@CHECKDIGIT@,0@SEARCH-1@-@CHECKDIGIT@ would turn a request for \"4127\" into a search for \"in ('4127','04127','412-7','0412-7')\"")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_NAME_REGEX, "^[a-zA-Z \\-]+$", "Names of the patients must pass this regex. Eg : ^[a-zA-Z \\-]+$ contains only english alphabet letters, spaces, and hyphens. A value of .* or the empty string means no validation is done.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS, String .valueOf(GLOBAL_PROPERTY_PERSON_SEARCH_MAX_RESULTS_DEFAULT_VALUE), "The maximum number of results returned by patient searches")); props .add(new GlobalProperty( GLOBAL_PROPERTY_GZIP_ENABLED, "false", "Set to 'true' to turn on OpenMRS's gzip filter, and have the webapp compress data before sending it to any client that supports it. Generally use this if you are running Tomcat standalone. If you are running Tomcat behind Apache, then you'd want to use Apache to do gzip compression.", BooleanDatatype.class, null)); props .add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_XML_MACROS, "", "Macros that will be applied to Report Schema XMLs when they are interpreted. This should be java.util.properties format.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238", "The concept id of the MEDICAL_RECORD_OBSERVATIONS concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PROBLEM_LIST, "1284", "The concept id of the PROBLEM LIST concept. This concept_id is presumed to be the generic grouping (obr) concept in hl7 messages. An obs_group row is not created for this concept.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_LOG_LEVEL, "org.openmrs.api:" + LOG_LEVEL_INFO, "Logging levels for log4j.xml. Valid format is class:level,class:level. If class not specified, 'org.openmrs.api' presumed. Valid levels are trace, debug, info, warn, error or fatal")); props .add(new GlobalProperty( GLOBAL_PROPERTY_DEFAULT_PATIENT_IDENTIFIER_VALIDATOR, LUHN_IDENTIFIER_VALIDATOR, "This property sets the default patient identifier validator. The default validator is only used in a handful of (mostly legacy) instances. For example, it's used to generate the isValidCheckDigit calculated column and to append the string \"(default)\" to the name of the default validator on the editPatientIdentifierType form.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_IDENTIFIER_IMPORTANT_TYPES, "", "A comma delimited list of PatientIdentifier names : PatientIdentifier locations that will be displayed on the patient dashboard. E.g.: TRACnet ID:Rwanda,ELDID:Kenya")); props.add(new GlobalProperty(GLOBAL_PROPERTY_COMPLEX_OBS_DIR, "complex_obs", "Default directory for storing complex obs.")); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER, "number", "The sort order for the obs listed on the encounter edit form. 'number' sorts on the associated numbering from the form schema. 'weight' sorts on the order displayed in the form schema.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en, es, fr, it, pt", "Comma delimited list of locales allowed for use on system")); props .add(new GlobalProperty( GLOBAL_PROPERTY_NEWPATIENTFORM_RELATIONSHIPS, "", "Comma separated list of the RelationshipTypes to show on the new/short patient form. The list is defined like '3a, 4b, 7a'. The number is the RelationshipTypeId and the 'a' vs 'b' part is which side of the relationship is filled in by the user.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_MIN_SEARCH_CHARACTERS, "3", "Number of characters user must input before searching is started.")); props .add(new GlobalProperty( OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE, "Specifies the default locale. You can specify both the language code(ISO-639) and the country code(ISO-3166), e.g. 'en_GB' or just country: e.g. 'en'")); props.add(new GlobalProperty(GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, "true", "Configure whether passwords must not match user's username or system id", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_CUSTOM_REGEX, "", "Configure a custom regular expression that a password must match")); props.add(new GlobalProperty(GP_PASSWORD_MINIMUM_LENGTH, "8", "Configure the minimum length required of all passwords")); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_DIGIT, "true", "Configure whether passwords must contain at least one digit", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_PASSWORD_REQUIRES_NON_DIGIT, "true", "Configure whether passwords must contain at least one non-digit", BooleanDatatype.class, null)); props .add(new GlobalProperty(GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, "true", "Configure whether passwords must contain both upper and lower case characters", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_IGNORE_MISSING_NONLOCAL_PATIENTS, "false", "If true, hl7 messages for patients that are not found and are non-local will silently be dropped/ignored", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_SHOW_PATIENT_NAME, "false", "Whether or not to display the patient name in the patient dashboard title. Note that enabling this could be security risk if multiple users operate on the same computer.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_THEME, "", "Default theme for users. OpenMRS ships with themes of 'green', 'orange', 'purple', and 'legacy'")); props.add(new GlobalProperty(GLOBAL_PROPERTY_HL7_ARCHIVE_DIRECTORY, HL7Constants.HL7_ARCHIVE_DIRECTORY_NAME, "The default name or absolute path for the folder where to write the hl7_in_archives.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_REPORT_BUG_URL, "http://errors.openmrs.org/scrap", "The openmrs url where to submit bug reports")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_BATCH_SIZE, "200", "The maximum number of search results that are returned by an ajax call")); props .add(new GlobalProperty( GP_SEARCH_WIDGET_IN_SERIAL_MODE, "true", "Specifies whether the search widgets should make ajax requests in serial or parallel order, a value of true is appropriate for implementations running on a slow network connection and vice versa", BooleanDatatype.class, null)); props .add(new GlobalProperty( GP_SEARCH_WIDGET_DELAY_INTERVAL, "400", "Specifies time interval in milliseconds when searching, between keyboard keyup event and triggering the search off, should be higher if most users are slow when typing so as to minimise the load on the server")); props.add(new GlobalProperty(GLOBAL_PROPERTY_DEFAULT_LOCATION_NAME, "Unknown Location", "The name of the location to use as a system default")); props .add(new GlobalProperty( GLOBAL_PROPERTY_PATIENT_SEARCH_MATCH_MODE, "START", "Specifies how patient names are matched while searching patient. Valid values are 'ANYWHERE' or 'START'. Defaults to start if missing or invalid value is present.")); props.add(new GlobalProperty(GP_ENABLE_CONCEPT_MAP_TYPE_MANAGEMENT, "false", "Enables or disables management of concept map types", BooleanDatatype.class, null)); props .add(new GlobalProperty( GLOBAL_PROPERTY_ENABLE_VISITS, "true", "Set to true to enable the Visits feature. This will replace the 'Encounters' tab with a 'Visits' tab on the dashboard.", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_ASSIGNMENT_HANDLER, ExistingVisitAssignmentHandler.class.getName(), "Set to the name of the class responsible for assigning encounters to visits.")); props.add(new GlobalProperty(GLOBAL_PROPERTY_APPLICATION_NAME, "OpenMRS", "The name of this application, as presented to the user, for example on the login and welcome pages.")); props .add(new GlobalProperty( GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "", "Specifies how encounter types are mapped to visit types when automatically assigning encounters to visits. e.g 1:1, 2:1, 3:2 in the format encounterTypeId:visitTypeId")); props .add(new GlobalProperty( GP_DASHBOARD_PROVIDER_DISPLAY_ENCOUNTER_ROLES, "", "A comma-separated list of encounter roles (by name or id). Providers with these roles in an encounter will be displayed on the encounter tab of the patient dashboard.")); props.add(new GlobalProperty(GP_SEARCH_WIDGET_MAXIMUM_RESULTS, "2000", "Specifies the maximum number of results to return from a single search in the search widgets")); props .add(new GlobalProperty( GP_DASHBOARD_MAX_NUMBER_OF_ENCOUNTERS_TO_SHOW, "", "An integer which, if specified, would determine the maximum number of encounters to display on the encounter tab of the patient dashboard.")); props .add(new GlobalProperty( GP_ENABLE_AUTO_CLOSE_OPEN_VISITS_TASK, "false", "Enables or disables the scheduled task that automatically stops any active visits of the specified visit type(s)", BooleanDatatype.class, null)); props.add(new GlobalProperty(GP_VISIT_TYPES_TO_AUTO_CLOSE, "", "comma-separated list of the visit type(s) to automatically close")); for (GlobalProperty gp : ModuleFactory.getGlobalProperties()) { props.add(gp); } return props; }
diff --git a/src/main/java/org/jboss/logging/LoggerProviders.java b/src/main/java/org/jboss/logging/LoggerProviders.java index 7240187..e4e695f 100644 --- a/src/main/java/org/jboss/logging/LoggerProviders.java +++ b/src/main/java/org/jboss/logging/LoggerProviders.java @@ -1,67 +1,68 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging; import java.util.logging.LogManager; final class LoggerProviders { static final LoggerProvider PROVIDER = findProvider(); private static LoggerProvider findProvider() { try { final LogManager jdkLogManager = LogManager.getLogManager(); if (jdkLogManager.getClass().getName().equals("org.jboss.logmanager.LogManager")) { + Class.forName("org.jboss.logmanager.Logger$AttachmentKey", false, LoggerProviders.class.getClassLoader()); return new JBossLogManagerProvider(); } } catch (Throwable t) { // nope... } final ClassLoader cl = getClassLoader(); try { Class.forName("org.apache.log4j.LogManager", true, cl); // JBLOGGING-65 - slf4j can disguise itself as log4j. Test for a class that slf4j doesn't provide. Class.forName("org.apache.log4j.Hierarchy", true, cl); return new Log4jLoggerProvider(); } catch (Throwable t) { // nope... } try { // only use slf4j if Logback is in use Class.forName("ch.qos.logback.classic.Logger", false, cl); return new Slf4jLoggerProvider(); } catch (Throwable t) { // nope... } return new JDKLoggerProvider(); } private static ClassLoader getClassLoader() { // Since the impl classes refer to the back-end frameworks directly, if this classloader can't find the target // log classes, then it doesn't really matter if they're possibly available from the TCCL because we won't be // able to find it anyway return LoggerProviders.class.getClassLoader(); } private LoggerProviders() { } }
true
true
private static LoggerProvider findProvider() { try { final LogManager jdkLogManager = LogManager.getLogManager(); if (jdkLogManager.getClass().getName().equals("org.jboss.logmanager.LogManager")) { return new JBossLogManagerProvider(); } } catch (Throwable t) { // nope... } final ClassLoader cl = getClassLoader(); try { Class.forName("org.apache.log4j.LogManager", true, cl); // JBLOGGING-65 - slf4j can disguise itself as log4j. Test for a class that slf4j doesn't provide. Class.forName("org.apache.log4j.Hierarchy", true, cl); return new Log4jLoggerProvider(); } catch (Throwable t) { // nope... } try { // only use slf4j if Logback is in use Class.forName("ch.qos.logback.classic.Logger", false, cl); return new Slf4jLoggerProvider(); } catch (Throwable t) { // nope... } return new JDKLoggerProvider(); }
private static LoggerProvider findProvider() { try { final LogManager jdkLogManager = LogManager.getLogManager(); if (jdkLogManager.getClass().getName().equals("org.jboss.logmanager.LogManager")) { Class.forName("org.jboss.logmanager.Logger$AttachmentKey", false, LoggerProviders.class.getClassLoader()); return new JBossLogManagerProvider(); } } catch (Throwable t) { // nope... } final ClassLoader cl = getClassLoader(); try { Class.forName("org.apache.log4j.LogManager", true, cl); // JBLOGGING-65 - slf4j can disguise itself as log4j. Test for a class that slf4j doesn't provide. Class.forName("org.apache.log4j.Hierarchy", true, cl); return new Log4jLoggerProvider(); } catch (Throwable t) { // nope... } try { // only use slf4j if Logback is in use Class.forName("ch.qos.logback.classic.Logger", false, cl); return new Slf4jLoggerProvider(); } catch (Throwable t) { // nope... } return new JDKLoggerProvider(); }
diff --git a/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/project/ProjectCreator.java b/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/project/ProjectCreator.java index feff5af96..52c60088a 100644 --- a/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/project/ProjectCreator.java +++ b/sdkmanager/libs/sdklib/src/com/android/sdklib/internal/project/ProjectCreator.java @@ -1,1308 +1,1312 @@ /* * Copyright (C) 2007 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.sdklib.internal.project; import com.android.AndroidConstants; import com.android.io.FileWrapper; import com.android.io.FolderWrapper; import com.android.sdklib.IAndroidTarget; import com.android.sdklib.ISdkLog; import com.android.sdklib.SdkConstants; import com.android.sdklib.SdkManager; import com.android.sdklib.internal.project.ProjectProperties.PropertyType; import com.android.sdklib.xml.AndroidManifest; import com.android.sdklib.xml.AndroidXPathFactory; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; /** * Creates the basic files needed to get an Android project up and running. * * @hide */ public class ProjectCreator { /** Version of the build.xml. Stored in version-tag */ private final static int MIN_BUILD_VERSION_TAG = 1; /** Package path substitution string used in template files, i.e. "PACKAGE_PATH" */ private final static String PH_JAVA_FOLDER = "PACKAGE_PATH"; /** Package name substitution string used in template files, i.e. "PACKAGE" */ private final static String PH_PACKAGE = "PACKAGE"; /** Activity name substitution string used in template files, i.e. "ACTIVITY_NAME". * @deprecated This is only used for older templates. For new ones see * {@link #PH_ACTIVITY_ENTRY_NAME}, and {@link #PH_ACTIVITY_CLASS_NAME}. */ @Deprecated private final static String PH_ACTIVITY_NAME = "ACTIVITY_NAME"; /** Activity name substitution string used in manifest templates, i.e. "ACTIVITY_ENTRY_NAME".*/ private final static String PH_ACTIVITY_ENTRY_NAME = "ACTIVITY_ENTRY_NAME"; /** Activity name substitution string used in class templates, i.e. "ACTIVITY_CLASS_NAME".*/ private final static String PH_ACTIVITY_CLASS_NAME = "ACTIVITY_CLASS_NAME"; /** Activity FQ-name substitution string used in class templates, i.e. "ACTIVITY_FQ_NAME".*/ private final static String PH_ACTIVITY_FQ_NAME = "ACTIVITY_FQ_NAME"; /** Original Activity class name substitution string used in class templates, i.e. * "ACTIVITY_TESTED_CLASS_NAME".*/ private final static String PH_ACTIVITY_TESTED_CLASS_NAME = "ACTIVITY_TESTED_CLASS_NAME"; /** Project name substitution string used in template files, i.e. "PROJECT_NAME". */ private final static String PH_PROJECT_NAME = "PROJECT_NAME"; /** Application icon substitution string used in the manifest template */ private final static String PH_ICON = "ICON"; /** Version tag name substitution string used in template files, i.e. "VERSION_TAG". */ private final static String PH_VERSION_TAG = "VERSION_TAG"; /** The xpath to find a project name in an Ant build file. */ private static final String XPATH_PROJECT_NAME = "/project/@name"; /** Pattern for characters accepted in a project name. Since this will be used as a * directory name, we're being a bit conservative on purpose: dot and space cannot be used. */ public static final Pattern RE_PROJECT_NAME = Pattern.compile("[a-zA-Z0-9_]+"); /** List of valid characters for a project name. Used for display purposes. */ public final static String CHARS_PROJECT_NAME = "a-z A-Z 0-9 _"; /** Pattern for characters accepted in a package name. A package is list of Java identifier * separated by a dot. We need to have at least one dot (e.g. a two-level package name). * A Java identifier cannot start by a digit. */ public static final Pattern RE_PACKAGE_NAME = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*(?:\\.[a-zA-Z_][a-zA-Z0-9_]*)+"); /** List of valid characters for a project name. Used for display purposes. */ public final static String CHARS_PACKAGE_NAME = "a-z A-Z 0-9 _"; /** Pattern for characters accepted in an activity name, which is a Java identifier. */ public static final Pattern RE_ACTIVITY_NAME = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*"); /** List of valid characters for a project name. Used for display purposes. */ public final static String CHARS_ACTIVITY_NAME = "a-z A-Z 0-9 _"; public enum OutputLevel { /** Silent mode. Project creation will only display errors. */ SILENT, /** Normal mode. Project creation will display what's being done, display * error but not warnings. */ NORMAL, /** Verbose mode. Project creation will display what's being done, errors and warnings. */ VERBOSE; } /** * Exception thrown when a project creation fails, typically because a template * file cannot be written. */ private static class ProjectCreateException extends Exception { /** default UID. This will not be serialized anyway. */ private static final long serialVersionUID = 1L; @SuppressWarnings("unused") ProjectCreateException(String message) { super(message); } ProjectCreateException(Throwable t, String format, Object... args) { super(format != null ? String.format(format, args) : format, t); } ProjectCreateException(String format, Object... args) { super(String.format(format, args)); } } /** The {@link OutputLevel} verbosity. */ private final OutputLevel mLevel; /** Logger for errors and output. Cannot be null. */ private final ISdkLog mLog; /** The OS path of the SDK folder. */ private final String mSdkFolder; /** The {@link SdkManager} instance. */ private final SdkManager mSdkManager; /** * Helper class to create android projects. * * @param sdkManager The {@link SdkManager} instance. * @param sdkFolder The OS path of the SDK folder. * @param level The {@link OutputLevel} verbosity. * @param log Logger for errors and output. Cannot be null. */ public ProjectCreator(SdkManager sdkManager, String sdkFolder, OutputLevel level, ISdkLog log) { mSdkManager = sdkManager; mSdkFolder = sdkFolder; mLevel = level; mLog = log; } /** * Creates a new project. * <p/> * The caller should have already checked and sanitized the parameters. * * @param folderPath the folder of the project to create. * @param projectName the name of the project. The name must match the * {@link #RE_PROJECT_NAME} regex. * @param packageName the package of the project. The name must match the * {@link #RE_PACKAGE_NAME} regex. * @param activityEntry the activity of the project as it will appear in the manifest. Can be * null if no activity should be created. The name must match the * {@link #RE_ACTIVITY_NAME} regex. * @param target the project target. * @param library whether the project is a library. * @param pathToMainProject if non-null the project will be setup to test a main project * located at the given path. */ public void createProject(String folderPath, String projectName, String packageName, String activityEntry, IAndroidTarget target, boolean library, String pathToMainProject) { // create project folder if it does not exist File projectFolder = checkNewProjectLocation(folderPath); if (projectFolder == null) { return; } try { boolean isTestProject = pathToMainProject != null; // first create the project properties. // location of the SDK goes in localProperty ProjectPropertiesWorkingCopy localProperties = ProjectProperties.create(folderPath, PropertyType.LOCAL); localProperties.setProperty(ProjectProperties.PROPERTY_SDK, mSdkFolder); localProperties.save(); // target goes in default properties ProjectPropertiesWorkingCopy defaultProperties = ProjectProperties.create(folderPath, PropertyType.PROJECT); defaultProperties.setProperty(ProjectProperties.PROPERTY_TARGET, target.hashString()); if (library) { defaultProperties.setProperty(ProjectProperties.PROPERTY_LIBRARY, "true"); } defaultProperties.save(); // create a build.properties file with just the application package ProjectPropertiesWorkingCopy buildProperties = ProjectProperties.create(folderPath, PropertyType.ANT); if (isTestProject) { buildProperties.setProperty(ProjectProperties.PROPERTY_TESTED_PROJECT, pathToMainProject); } buildProperties.save(); // create the map for place-holders of values to replace in the templates final HashMap<String, String> keywords = new HashMap<String, String>(); // create the required folders. // compute src folder path final String packagePath = stripString(packageName.replace(".", File.separator), File.separatorChar); // put this path in the place-holder map for project files that needs to list // files manually. keywords.put(PH_JAVA_FOLDER, packagePath); keywords.put(PH_PACKAGE, packageName); keywords.put(PH_VERSION_TAG, Integer.toString(MIN_BUILD_VERSION_TAG)); // compute some activity related information String fqActivityName = null, activityPath = null, activityClassName = null; String originalActivityEntry = activityEntry; String originalActivityClassName = null; if (activityEntry != null) { if (isTestProject) { // append Test so that it doesn't collide with the main project activity. activityEntry += "Test"; // get the classname from the original activity entry. int pos = originalActivityEntry.lastIndexOf('.'); if (pos != -1) { originalActivityClassName = originalActivityEntry.substring(pos + 1); } else { originalActivityClassName = originalActivityEntry; } } // get the fully qualified name of the activity fqActivityName = AndroidManifest.combinePackageAndClassName(packageName, activityEntry); // get the activity path (replace the . to /) activityPath = stripString(fqActivityName.replace(".", File.separator), File.separatorChar); // remove the last segment, so that we only have the path to the activity, but // not the activity filename itself. activityPath = activityPath.substring(0, activityPath.lastIndexOf(File.separatorChar)); // finally, get the class name for the activity activityClassName = fqActivityName.substring(fqActivityName.lastIndexOf('.') + 1); } // at this point we have the following for the activity: // activityEntry: this is the manifest entry. For instance .MyActivity // fqActivityName: full-qualified class name: com.foo.MyActivity // activityClassName: only the classname: MyActivity // originalActivityClassName: the classname of the activity being tested (if applicable) // Add whatever activity info is needed in the place-holder map. // Older templates only expect ACTIVITY_NAME to be the same (and unmodified for tests). if (target.getVersion().getApiLevel() < 4) { // legacy if (originalActivityEntry != null) { keywords.put(PH_ACTIVITY_NAME, originalActivityEntry); } } else { // newer templates make a difference between the manifest entries, classnames, // as well as the main and test classes. if (activityEntry != null) { keywords.put(PH_ACTIVITY_ENTRY_NAME, activityEntry); keywords.put(PH_ACTIVITY_CLASS_NAME, activityClassName); keywords.put(PH_ACTIVITY_FQ_NAME, fqActivityName); if (originalActivityClassName != null) { keywords.put(PH_ACTIVITY_TESTED_CLASS_NAME, originalActivityClassName); } } } // Take the project name from the command line if there's one if (projectName != null) { keywords.put(PH_PROJECT_NAME, projectName); } else { if (activityClassName != null) { // Use the activity class name as project name keywords.put(PH_PROJECT_NAME, activityClassName); } else { // We need a project name. Just pick up the basename of the project // directory. projectName = projectFolder.getName(); keywords.put(PH_PROJECT_NAME, projectName); } } // create the source folder for the activity if (activityClassName != null) { String srcActivityFolderPath = SdkConstants.FD_SOURCES + File.separator + activityPath; File sourceFolder = createDirs(projectFolder, srcActivityFolderPath); String javaTemplate = isTestProject ? "java_tests_file.template" : "java_file.template"; String activityFileName = activityClassName + ".java"; installTargetTemplate(javaTemplate, new File(sourceFolder, activityFileName), keywords, target); } else { // we should at least create 'src' createDirs(projectFolder, SdkConstants.FD_SOURCES); } // create other useful folders File resourceFolder = createDirs(projectFolder, SdkConstants.FD_RESOURCES); createDirs(projectFolder, SdkConstants.FD_OUTPUT); createDirs(projectFolder, SdkConstants.FD_NATIVE_LIBS); if (isTestProject == false) { /* Make res files only for non test projects */ File valueFolder = createDirs(resourceFolder, AndroidConstants.FD_RES_VALUES); installTargetTemplate("strings.template", new File(valueFolder, "strings.xml"), keywords, target); File layoutFolder = createDirs(resourceFolder, AndroidConstants.FD_RES_LAYOUT); installTargetTemplate("layout.template", new File(layoutFolder, "main.xml"), keywords, target); // create the icons if (installIcons(resourceFolder, target)) { keywords.put(PH_ICON, "android:icon=\"@drawable/ic_launcher\""); } else { keywords.put(PH_ICON, ""); } } /* Make AndroidManifest.xml and build.xml files */ String manifestTemplate = "AndroidManifest.template"; if (isTestProject) { manifestTemplate = "AndroidManifest.tests.template"; } installTargetTemplate(manifestTemplate, new File(projectFolder, SdkConstants.FN_ANDROID_MANIFEST_XML), keywords, target); installTemplate("build.template", new File(projectFolder, SdkConstants.FN_BUILD_XML), keywords); // install the proguard config file. installTemplate(SdkConstants.FN_PROGUARD_CFG, new File(projectFolder, SdkConstants.FN_PROGUARD_CFG), null /*keywords*/); } catch (Exception e) { mLog.error(e, null); } } private File checkNewProjectLocation(String folderPath) { File projectFolder = new File(folderPath); if (!projectFolder.exists()) { boolean created = false; Throwable t = null; try { created = projectFolder.mkdirs(); } catch (Exception e) { t = e; } if (created) { println("Created project directory: %1$s", projectFolder); } else { mLog.error(t, "Could not create directory: %1$s", projectFolder); return null; } } else { Exception e = null; String error = null; try { String[] content = projectFolder.list(); if (content == null) { error = "Project folder '%1$s' is not a directory."; } else if (content.length != 0) { error = "Project folder '%1$s' is not empty. Please consider using '%2$s update' instead."; } } catch (Exception e1) { e = e1; } if (e != null || error != null) { mLog.error(e, error, projectFolder, SdkConstants.androidCmdName()); } } return projectFolder; } /** * Updates an existing project. * <p/> * Workflow: * <ul> * <li> Check AndroidManifest.xml is present (required) * <li> Check if there's a legacy properties file and convert it * <li> Check there's a project.properties with a target *or* --target was specified * <li> Update default.prop if --target was specified * <li> Refresh/create "sdk" in local.properties * <li> Build.xml: create if not present or if version-tag is found or not. version-tag:custom * prevent any overwrite. version-tag:[integer] will override. missing version-tag will query * the dev. * </ul> * * @param folderPath the folder of the project to update. This folder must exist. * @param target the project target. Can be null. * @param projectName The project name from --name. Can be null. * @param libraryPath the path to a library to add to the references. Can be null. * @return true if the project was successfully updated. */ @SuppressWarnings("deprecation") public boolean updateProject(String folderPath, IAndroidTarget target, String projectName, String libraryPath) { // since this is an update, check the folder does point to a project FileWrapper androidManifest = checkProjectFolder(folderPath, SdkConstants.FN_ANDROID_MANIFEST_XML); if (androidManifest == null) { return false; } // get the parent folder. FolderWrapper projectFolder = (FolderWrapper) androidManifest.getParentFolder(); boolean hasProguard = false; // Check there's a project.properties with a target *or* --target was specified IAndroidTarget originalTarget = null; boolean writeProjectProp = false; ProjectProperties props = ProjectProperties.load(projectFolder, PropertyType.PROJECT); if (props == null) { // no project.properties, try to load default.properties props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_DEFAULT); writeProjectProp = true; } if (props != null) { String targetHash = props.getProperty(ProjectProperties.PROPERTY_TARGET); originalTarget = mSdkManager.getTargetFromHashString(targetHash); // if the project is already setup with proguard, we won't copy the proguard config. hasProguard = props.getProperty(ProjectProperties.PROPERTY_PROGUARD_CONFIG) != null; } if (originalTarget == null && target == null) { mLog.error(null, "The project either has no target set or the target is invalid.\n" + "Please provide a --target to the '%1$s update' command.", SdkConstants.androidCmdName()); return false; } boolean saveProjectProps = false; ProjectPropertiesWorkingCopy propsWC = null; // Update default.prop if --target was specified if (target != null || writeProjectProp) { // we already attempted to load the file earlier, if that failed, create it. if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.PROJECT); } else { propsWC = props.makeWorkingCopy(PropertyType.PROJECT); } // set or replace the target if (target != null) { propsWC.setProperty(ProjectProperties.PROPERTY_TARGET, target.hashString()); } saveProjectProps = true; } if (libraryPath != null) { // At this point, the default properties already exists, either because they were // already there or because they were created with a new target if (propsWC == null) { assert props != null; propsWC = props.makeWorkingCopy(); } // check the reference is valid File libProject = new File(libraryPath); String resolvedPath; if (libProject.isAbsolute() == false) { libProject = new File(projectFolder, libraryPath); try { resolvedPath = libProject.getCanonicalPath(); } catch (IOException e) { mLog.error(e, "Unable to resolve path to library project: %1$s", libraryPath); return false; } } else { resolvedPath = libProject.getAbsolutePath(); } println("Resolved location of library project to: %1$s", resolvedPath); // check the lib project exists if (checkProjectFolder(resolvedPath, SdkConstants.FN_ANDROID_MANIFEST_XML) == null) { mLog.error(null, "No Android Manifest at: %1$s", resolvedPath); return false; } // look for other references to figure out the index int index = 1; while (true) { String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); assert props != null; + if (props == null) { + // This should not happen yet SDK bug 20535 says it can, not sure how. + break; + } String ref = props.getProperty(propName); if (ref == null) { break; } else { index++; } } String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); propsWC.setProperty(propName, libraryPath); saveProjectProps = true; } // save the default props if needed. if (saveProjectProps) { try { assert propsWC != null; propsWC.save(); if (writeProjectProp) { println("Updated and renamed %1$s to %2$s", PropertyType.LEGACY_DEFAULT.getFilename(), PropertyType.PROJECT.getFilename()); } else { println("Updated %1$s", PropertyType.PROJECT.getFilename()); } } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.PROJECT.getFilename(), folderPath); return false; } if (writeProjectProp) { // need to delete the default prop file. ProjectProperties.delete(projectFolder, PropertyType.LEGACY_DEFAULT); } } // Refresh/create "sdk" in local.properties // because the file may already exists and contain other values (like apk config), // we first try to load it. props = ProjectProperties.load(projectFolder, PropertyType.LOCAL); if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.LOCAL); } else { propsWC = props.makeWorkingCopy(); } // set or replace the sdk location. propsWC.setProperty(ProjectProperties.PROPERTY_SDK, mSdkFolder); try { propsWC.save(); println("Updated %1$s", PropertyType.LOCAL.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.LOCAL.getFilename(), folderPath); return false; } // legacy: check if build.properties must be renamed to ant.properties. props = ProjectProperties.load(projectFolder, PropertyType.ANT); if (props == null) { props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_BUILD); if (props != null) { try { // get a working copy with the new property type propsWC = props.makeWorkingCopy(PropertyType.ANT); propsWC.save(); // delete the old file ProjectProperties.delete(projectFolder, PropertyType.LEGACY_BUILD); println("Renamed %1$s to %2$s", PropertyType.LEGACY_BUILD.getFilename(), PropertyType.ANT.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.ANT.getFilename(), folderPath); return false; } } } // Build.xml: create if not present or no <androidinit/> in it File buildXml = new File(projectFolder, SdkConstants.FN_BUILD_XML); boolean needsBuildXml = projectName != null || !buildXml.exists(); // if it seems there's no need for a new build.xml, look for inside the file // to try to detect old ones that may need updating. if (!needsBuildXml) { // we are looking for version-tag: followed by either an integer or "custom". if (checkFileContainsRegexp(buildXml, "version-tag:\\s*custom") != null) { //$NON-NLS-1$ println("%1$s: Found version-tag: custom. File will not be updated.", SdkConstants.FN_BUILD_XML); } else { Matcher m = checkFileContainsRegexp(buildXml, "version-tag:\\s*(\\d+)"); //$NON-NLS-1$ if (m == null) { println("----------\n" + "%1$s: Failed to find version-tag string. File must be updated.\n" + "In order to not erase potential customizations, the file will not be automatically regenerated.\n" + "If no changes have been made to the file, delete it manually and run the command again.\n" + "If you have made customizations to the build process, the file must be manually updated.\n" + "It is recommended to:\n" + "\t* Copy current file to a safe location.\n" + "\t* Delete original file.\n" + "\t* Run command again to generate a new file.\n" + "\t* Port customizations to the new file, by looking at the new rules file\n" + "\t located at <SDK>/tools/ant/build.xml\n" + "\t* Update file to contain\n" + "\t version-tag: custom\n" + "\t to prevent file from being rewritten automatically by the SDK tools.\n" + "----------\n", SdkConstants.FN_BUILD_XML); } else { String versionStr = m.group(1); if (versionStr != null) { // can't fail due to regexp above. int version = Integer.parseInt(versionStr); if (version < MIN_BUILD_VERSION_TAG) { println("%1$s: Found version-tag: %2$d. Expected version-tag: %3$d: file must be updated.", SdkConstants.FN_BUILD_XML, version, MIN_BUILD_VERSION_TAG); needsBuildXml = true; } } } } } if (needsBuildXml) { // create the map for place-holders of values to replace in the templates final HashMap<String, String> keywords = new HashMap<String, String>(); // put the current version-tag value keywords.put(PH_VERSION_TAG, Integer.toString(MIN_BUILD_VERSION_TAG)); // if there was no project name on the command line, figure one out. if (projectName == null) { // otherwise, take it from the existing build.xml if it exists already. if (buildXml.exists()) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); projectName = xpath.evaluate(XPATH_PROJECT_NAME, new InputSource(new FileInputStream(buildXml))); } catch (XPathExpressionException e) { // this is ok since we're going to recreate the file. mLog.error(e, "Unable to find existing project name from %1$s", SdkConstants.FN_BUILD_XML); } catch (FileNotFoundException e) { // can't happen since we check above. } } // if the project is still null, then we find another way. if (projectName == null) { extractPackageFromManifest(androidManifest, keywords); if (keywords.containsKey(PH_ACTIVITY_ENTRY_NAME)) { String activity = keywords.get(PH_ACTIVITY_ENTRY_NAME); // keep only the last segment if applicable int pos = activity.lastIndexOf('.'); if (pos != -1) { activity = activity.substring(pos + 1); } // Use the activity as project name projectName = activity; println("No project name specified, using Activity name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", activity, SdkConstants.FN_BUILD_XML); } else { // We need a project name. Just pick up the basename of the project // directory. File projectCanonicalFolder = projectFolder; try { projectCanonicalFolder = projectCanonicalFolder.getCanonicalFile(); } catch (IOException e) { // ignore, keep going } // Use the folder name as project name projectName = projectCanonicalFolder.getName(); println("No project name specified, using project folder name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", projectName, SdkConstants.FN_BUILD_XML); } } } // put the project name in the map for replacement during the template installation. keywords.put(PH_PROJECT_NAME, projectName); if (mLevel == OutputLevel.VERBOSE) { println("Regenerating %1$s with project name %2$s", SdkConstants.FN_BUILD_XML, keywords.get(PH_PROJECT_NAME)); } try { installTemplate("build.template", buildXml, keywords); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } if (hasProguard == false) { try { installTemplate(SdkConstants.FN_PROGUARD_CFG, new File(projectFolder, SdkConstants.FN_PROGUARD_CFG), null /*placeholderMap*/); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } return true; } /** * Updates a test project with a new path to the main (tested) project. * @param folderPath the path of the test project. * @param pathToMainProject the path to the main project, relative to the test project. */ @SuppressWarnings("deprecation") public void updateTestProject(final String folderPath, final String pathToMainProject, final SdkManager sdkManager) { // since this is an update, check the folder does point to a project if (checkProjectFolder(folderPath, SdkConstants.FN_ANDROID_MANIFEST_XML) == null) { return; } // check the path to the main project is valid. File mainProject = new File(pathToMainProject); String resolvedPath; if (mainProject.isAbsolute() == false) { mainProject = new File(folderPath, pathToMainProject); try { resolvedPath = mainProject.getCanonicalPath(); } catch (IOException e) { mLog.error(e, "Unable to resolve path to main project: %1$s", pathToMainProject); return; } } else { resolvedPath = mainProject.getAbsolutePath(); } println("Resolved location of main project to: %1$s", resolvedPath); // check the main project exists if (checkProjectFolder(resolvedPath, SdkConstants.FN_ANDROID_MANIFEST_XML) == null) { mLog.error(null, "No Android Manifest at: %1$s", resolvedPath); return; } // now get the target from the main project ProjectProperties projectProp = ProjectProperties.load(resolvedPath, PropertyType.PROJECT); if (projectProp == null) { // legacy support for older file name. projectProp = ProjectProperties.load(resolvedPath, PropertyType.LEGACY_DEFAULT); if (projectProp == null) { mLog.error(null, "No %1$s at: %2$s", PropertyType.PROJECT.getFilename(), resolvedPath); return; } } String targetHash = projectProp.getProperty(ProjectProperties.PROPERTY_TARGET); if (targetHash == null) { mLog.error(null, "%1$s in the main project has no target property.", PropertyType.PROJECT.getFilename()); return; } IAndroidTarget target = sdkManager.getTargetFromHashString(targetHash); if (target == null) { mLog.error(null, "Main project target %1$s is not a valid target.", targetHash); return; } // update test-project does not support the --name parameter, therefore the project // name should generally not be passed to updateProject(). // However if build.xml does not exist then updateProject() will recreate it. In this // case we will need the project name. // To do this, we look for the parent project name and add "test" to it. // If the main project does not have a project name (yet), then the default behavior // will be used (look for activity and then folder name) String projectName = null; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); File testBuildXml = new File(folderPath, SdkConstants.FN_BUILD_XML); if (testBuildXml.isFile() == false) { File mainBuildXml = new File(resolvedPath, SdkConstants.FN_BUILD_XML); if (mainBuildXml.isFile()) { try { // get the name of the main project and add Test to it. String mainProjectName = xpath.evaluate(XPATH_PROJECT_NAME, new InputSource(new FileInputStream(mainBuildXml))); projectName = mainProjectName + "Test"; } catch (XPathExpressionException e) { // it's ok, updateProject() will figure out a name automatically. // We do log the error though as the build.xml file may be broken. mLog.warning("Failed to parse %1$s.\n" + "File may not be valid. Consider running 'android update project' on the main project.", mainBuildXml.getPath()); } catch (FileNotFoundException e) { // should not happen since we check first. } } } // now update the project as if it's a normal project if (updateProject(folderPath, target, projectName, null /*libraryPath*/) == false) { // error message has already been displayed. return; } // add the test project specific properties. // At this point, we know build.prop has been renamed ant.prop ProjectProperties antProps = ProjectProperties.load(folderPath, PropertyType.ANT); ProjectPropertiesWorkingCopy antWorkingCopy; if (antProps == null) { antWorkingCopy = ProjectProperties.create(folderPath, PropertyType.ANT); } else { antWorkingCopy = antProps.makeWorkingCopy(); } // set or replace the path to the main project antWorkingCopy.setProperty(ProjectProperties.PROPERTY_TESTED_PROJECT, pathToMainProject); try { antWorkingCopy.save(); println("Updated %1$s", PropertyType.ANT.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.ANT.getFilename(), folderPath); return; } } /** * Checks whether the give <var>folderPath</var> is a valid project folder, and returns * a {@link FileWrapper} to the required file. * <p/>This checks that the folder exists and contains an AndroidManifest.xml file in it. * <p/>Any error are output using {@link #mLog}. * @param folderPath the folder to check * @param requiredFilename the file name of the file that's required. * @return a {@link FileWrapper} to the AndroidManifest.xml file, or null otherwise. */ private FileWrapper checkProjectFolder(String folderPath, String requiredFilename) { // project folder must exist and be a directory, since this is an update FolderWrapper projectFolder = new FolderWrapper(folderPath); if (!projectFolder.isDirectory()) { mLog.error(null, "Project folder '%1$s' is not a valid directory.", projectFolder); return null; } // Check AndroidManifest.xml is present FileWrapper requireFile = new FileWrapper(projectFolder, requiredFilename); if (!requireFile.isFile()) { mLog.error(null, "%1$s is not a valid project (%2$s not found).", folderPath, requiredFilename); return null; } return requireFile; } /** * Looks for a given regex in a file and returns the matcher if any line of the input file * contains the requested regexp. * * @param file the file to search. * @param regexp the regexp to search for. * * @return a Matcher or null if the regexp is not found. */ private Matcher checkFileContainsRegexp(File file, String regexp) { Pattern p = Pattern.compile(regexp); try { BufferedReader in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) != null) { Matcher m = p.matcher(line); if (m.find()) { return m; } } in.close(); } catch (Exception e) { // ignore } return null; } /** * Extracts a "full" package & activity name from an AndroidManifest.xml. * <p/> * The keywords dictionary is always filed the package name under the key {@link #PH_PACKAGE}. * If an activity name can be found, it is filed under the key {@link #PH_ACTIVITY_ENTRY_NAME}. * When no activity is found, this key is not created. * * @param manifestFile The AndroidManifest.xml file * @param outKeywords Place where to put the out parameters: package and activity names. * @return True if the package/activity was parsed and updated in the keyword dictionary. */ private boolean extractPackageFromManifest(File manifestFile, Map<String, String> outKeywords) { try { XPath xpath = AndroidXPathFactory.newXPath(); InputSource source = new InputSource(new FileReader(manifestFile)); String packageName = xpath.evaluate("/manifest/@package", source); source = new InputSource(new FileReader(manifestFile)); // Select the "android:name" attribute of all <activity> nodes but only if they // contain a sub-node <intent-filter><action> with an "android:name" attribute which // is 'android.intent.action.MAIN' and an <intent-filter><category> with an // "android:name" attribute which is 'android.intent.category.LAUNCHER' String expression = String.format("/manifest/application/activity" + "[intent-filter/action/@%1$s:name='android.intent.action.MAIN' and " + "intent-filter/category/@%1$s:name='android.intent.category.LAUNCHER']" + "/@%1$s:name", AndroidXPathFactory.DEFAULT_NS_PREFIX); NodeList activityNames = (NodeList) xpath.evaluate(expression, source, XPathConstants.NODESET); // If we get here, both XPath expressions were valid so we're most likely dealing // with an actual AndroidManifest.xml file. The nodes may not have the requested // attributes though, if which case we should warn. if (packageName == null || packageName.length() == 0) { mLog.error(null, "Missing <manifest package=\"...\"> in '%1$s'", manifestFile.getName()); return false; } // Get the first activity that matched earlier. If there is no activity, // activityName is set to an empty string and the generated "combined" name // will be in the form "package." (with a dot at the end). String activityName = ""; if (activityNames.getLength() > 0) { activityName = activityNames.item(0).getNodeValue(); } if (mLevel == OutputLevel.VERBOSE && activityNames.getLength() > 1) { println("WARNING: There is more than one activity defined in '%1$s'.\n" + "Only the first one will be used. If this is not appropriate, you need\n" + "to specify one of these values manually instead:", manifestFile.getName()); for (int i = 0; i < activityNames.getLength(); i++) { String name = activityNames.item(i).getNodeValue(); name = combinePackageActivityNames(packageName, name); println("- %1$s", name); } } if (activityName.length() == 0) { mLog.warning("Missing <activity %1$s:name=\"...\"> in '%2$s'.\n" + "No activity will be generated.", AndroidXPathFactory.DEFAULT_NS_PREFIX, manifestFile.getName()); } else { outKeywords.put(PH_ACTIVITY_ENTRY_NAME, activityName); } outKeywords.put(PH_PACKAGE, packageName); return true; } catch (IOException e) { mLog.error(e, "Failed to read %1$s", manifestFile.getName()); } catch (XPathExpressionException e) { Throwable t = e.getCause(); mLog.error(t == null ? e : t, "Failed to parse %1$s", manifestFile.getName()); } return false; } private String combinePackageActivityNames(String packageName, String activityName) { // Activity Name can have 3 forms: // - ".Name" means this is a class name in the given package name. // The full FQCN is thus packageName + ".Name" // - "Name" is an older variant of the former. Full FQCN is packageName + "." + "Name" // - "com.blah.Name" is a full FQCN. Ignore packageName and use activityName as-is. // To be valid, the package name should have at least two components. This is checked // later during the creation of the build.xml file, so we just need to detect there's // a dot but not at pos==0. int pos = activityName.indexOf('.'); if (pos == 0) { return packageName + activityName; } else if (pos > 0) { return activityName; } else { return packageName + "." + activityName; } } /** * Installs a new file that is based on a template file provided by a given target. * Each match of each key from the place-holder map in the template will be replaced with its * corresponding value in the created file. * * @param templateName the name of to the template file * @param destFile the path to the destination file, relative to the project * @param placeholderMap a map of (place-holder, value) to create the file from the template. * @param target the Target of the project that will be providing the template. * @throws ProjectCreateException */ private void installTargetTemplate(String templateName, File destFile, Map<String, String> placeholderMap, IAndroidTarget target) throws ProjectCreateException { // query the target for its template directory String templateFolder = target.getPath(IAndroidTarget.TEMPLATES); final String sourcePath = templateFolder + File.separator + templateName; installFullPathTemplate(sourcePath, destFile, placeholderMap); } /** * Installs a new file that is based on a template file provided by the tools folder. * Each match of each key from the place-holder map in the template will be replaced with its * corresponding value in the created file. * * @param templateName the name of to the template file * @param destFile the path to the destination file, relative to the project * @param placeholderMap a map of (place-holder, value) to create the file from the template. * @throws ProjectCreateException */ private void installTemplate(String templateName, File destFile, Map<String, String> placeholderMap) throws ProjectCreateException { // query the target for its template directory String templateFolder = mSdkFolder + File.separator + SdkConstants.OS_SDK_TOOLS_LIB_FOLDER; final String sourcePath = templateFolder + File.separator + templateName; installFullPathTemplate(sourcePath, destFile, placeholderMap); } /** * Installs a new file that is based on a template. * Each match of each key from the place-holder map in the template will be replaced with its * corresponding value in the created file. * * @param sourcePath the full path to the source template file * @param destFile the destination file * @param placeholderMap a map of (place-holder, value) to create the file from the template. * @throws ProjectCreateException */ private void installFullPathTemplate(String sourcePath, File destFile, Map<String, String> placeholderMap) throws ProjectCreateException { boolean existed = destFile.exists(); try { BufferedWriter out = new BufferedWriter(new FileWriter(destFile)); BufferedReader in = new BufferedReader(new FileReader(sourcePath)); String line; while ((line = in.readLine()) != null) { if (placeholderMap != null) { for (Map.Entry<String, String> entry : placeholderMap.entrySet()) { line = line.replace(entry.getKey(), entry.getValue()); } } out.write(line); out.newLine(); } out.close(); in.close(); } catch (Exception e) { throw new ProjectCreateException(e, "Could not access %1$s: %2$s", destFile, e.getMessage()); } println("%1$s file %2$s", existed ? "Updated" : "Added", destFile); } /** * Installs the project icons. * @param resourceFolder the resource folder * @param target the target of the project. * @return true if any icon was installed. */ private boolean installIcons(File resourceFolder, IAndroidTarget target) throws ProjectCreateException { // query the target for its template directory String templateFolder = target.getPath(IAndroidTarget.TEMPLATES); boolean installedIcon = false; installedIcon |= installIcon(templateFolder, "ic_launcher_hdpi.png", resourceFolder, "drawable-hdpi"); installedIcon |= installIcon(templateFolder, "ic_launcher_mdpi.png", resourceFolder, "drawable-mdpi"); installedIcon |= installIcon(templateFolder, "ic_launcher_ldpi.png", resourceFolder, "drawable-ldpi"); return installedIcon; } /** * Installs an Icon in the project. * @return true if the icon was installed. */ private boolean installIcon(String templateFolder, String iconName, File resourceFolder, String folderName) throws ProjectCreateException { File icon = new File(templateFolder, iconName); if (icon.exists()) { File drawable = createDirs(resourceFolder, folderName); installBinaryFile(icon, new File(drawable, "ic_launcher.png")); return true; } return false; } /** * Installs a binary file * @param source the source file to copy * @param destination the destination file to write * @throws ProjectCreateException */ private void installBinaryFile(File source, File destination) throws ProjectCreateException { byte[] buffer = new byte[8192]; FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); int read; while ((read = fis.read(buffer)) != -1) { fos.write(buffer, 0, read); } } catch (FileNotFoundException e) { // shouldn't happen since we check before. } catch (IOException e) { throw new ProjectCreateException(e, "Failed to read binary file: %1$s", source.getAbsolutePath()); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } if (fos != null) { try { fos.close(); } catch (IOException e) { // ignore } } } } /** * Prints a message unless silence is enabled. * <p/> * This is just a convenience wrapper around {@link ISdkLog#printf(String, Object...)} from * {@link #mLog} after testing if ouput level is {@link OutputLevel#VERBOSE}. * * @param format Format for String.format * @param args Arguments for String.format */ private void println(String format, Object... args) { if (mLevel != OutputLevel.SILENT) { if (!format.endsWith("\n")) { format += "\n"; } mLog.printf(format, args); } } /** * Creates a new folder, along with any parent folders that do not exists. * * @param parent the parent folder * @param name the name of the directory to create. * @throws ProjectCreateException */ private File createDirs(File parent, String name) throws ProjectCreateException { final File newFolder = new File(parent, name); boolean existedBefore = true; if (!newFolder.exists()) { if (!newFolder.mkdirs()) { throw new ProjectCreateException("Could not create directory: %1$s", newFolder); } existedBefore = false; } if (newFolder.isDirectory()) { if (!newFolder.canWrite()) { throw new ProjectCreateException("Path is not writable: %1$s", newFolder); } } else { throw new ProjectCreateException("Path is not a directory: %1$s", newFolder); } if (!existedBefore) { try { println("Created directory %1$s", newFolder.getCanonicalPath()); } catch (IOException e) { throw new ProjectCreateException( "Could not determine canonical path of created directory", e); } } return newFolder; } /** * Strips the string of beginning and trailing characters (multiple * characters will be stripped, example stripString("..test...", '.') * results in "test"; * * @param s the string to strip * @param strip the character to strip from beginning and end * @return the stripped string or the empty string if everything is stripped. */ private static String stripString(String s, char strip) { final int sLen = s.length(); int newStart = 0, newEnd = sLen - 1; while (newStart < sLen && s.charAt(newStart) == strip) { newStart++; } while (newEnd >= 0 && s.charAt(newEnd) == strip) { newEnd--; } /* * newEnd contains a char we want, and substring takes end as being * exclusive */ newEnd++; if (newStart >= sLen || newEnd < 0) { return ""; } return s.substring(newStart, newEnd); } }
true
true
public boolean updateProject(String folderPath, IAndroidTarget target, String projectName, String libraryPath) { // since this is an update, check the folder does point to a project FileWrapper androidManifest = checkProjectFolder(folderPath, SdkConstants.FN_ANDROID_MANIFEST_XML); if (androidManifest == null) { return false; } // get the parent folder. FolderWrapper projectFolder = (FolderWrapper) androidManifest.getParentFolder(); boolean hasProguard = false; // Check there's a project.properties with a target *or* --target was specified IAndroidTarget originalTarget = null; boolean writeProjectProp = false; ProjectProperties props = ProjectProperties.load(projectFolder, PropertyType.PROJECT); if (props == null) { // no project.properties, try to load default.properties props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_DEFAULT); writeProjectProp = true; } if (props != null) { String targetHash = props.getProperty(ProjectProperties.PROPERTY_TARGET); originalTarget = mSdkManager.getTargetFromHashString(targetHash); // if the project is already setup with proguard, we won't copy the proguard config. hasProguard = props.getProperty(ProjectProperties.PROPERTY_PROGUARD_CONFIG) != null; } if (originalTarget == null && target == null) { mLog.error(null, "The project either has no target set or the target is invalid.\n" + "Please provide a --target to the '%1$s update' command.", SdkConstants.androidCmdName()); return false; } boolean saveProjectProps = false; ProjectPropertiesWorkingCopy propsWC = null; // Update default.prop if --target was specified if (target != null || writeProjectProp) { // we already attempted to load the file earlier, if that failed, create it. if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.PROJECT); } else { propsWC = props.makeWorkingCopy(PropertyType.PROJECT); } // set or replace the target if (target != null) { propsWC.setProperty(ProjectProperties.PROPERTY_TARGET, target.hashString()); } saveProjectProps = true; } if (libraryPath != null) { // At this point, the default properties already exists, either because they were // already there or because they were created with a new target if (propsWC == null) { assert props != null; propsWC = props.makeWorkingCopy(); } // check the reference is valid File libProject = new File(libraryPath); String resolvedPath; if (libProject.isAbsolute() == false) { libProject = new File(projectFolder, libraryPath); try { resolvedPath = libProject.getCanonicalPath(); } catch (IOException e) { mLog.error(e, "Unable to resolve path to library project: %1$s", libraryPath); return false; } } else { resolvedPath = libProject.getAbsolutePath(); } println("Resolved location of library project to: %1$s", resolvedPath); // check the lib project exists if (checkProjectFolder(resolvedPath, SdkConstants.FN_ANDROID_MANIFEST_XML) == null) { mLog.error(null, "No Android Manifest at: %1$s", resolvedPath); return false; } // look for other references to figure out the index int index = 1; while (true) { String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); assert props != null; String ref = props.getProperty(propName); if (ref == null) { break; } else { index++; } } String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); propsWC.setProperty(propName, libraryPath); saveProjectProps = true; } // save the default props if needed. if (saveProjectProps) { try { assert propsWC != null; propsWC.save(); if (writeProjectProp) { println("Updated and renamed %1$s to %2$s", PropertyType.LEGACY_DEFAULT.getFilename(), PropertyType.PROJECT.getFilename()); } else { println("Updated %1$s", PropertyType.PROJECT.getFilename()); } } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.PROJECT.getFilename(), folderPath); return false; } if (writeProjectProp) { // need to delete the default prop file. ProjectProperties.delete(projectFolder, PropertyType.LEGACY_DEFAULT); } } // Refresh/create "sdk" in local.properties // because the file may already exists and contain other values (like apk config), // we first try to load it. props = ProjectProperties.load(projectFolder, PropertyType.LOCAL); if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.LOCAL); } else { propsWC = props.makeWorkingCopy(); } // set or replace the sdk location. propsWC.setProperty(ProjectProperties.PROPERTY_SDK, mSdkFolder); try { propsWC.save(); println("Updated %1$s", PropertyType.LOCAL.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.LOCAL.getFilename(), folderPath); return false; } // legacy: check if build.properties must be renamed to ant.properties. props = ProjectProperties.load(projectFolder, PropertyType.ANT); if (props == null) { props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_BUILD); if (props != null) { try { // get a working copy with the new property type propsWC = props.makeWorkingCopy(PropertyType.ANT); propsWC.save(); // delete the old file ProjectProperties.delete(projectFolder, PropertyType.LEGACY_BUILD); println("Renamed %1$s to %2$s", PropertyType.LEGACY_BUILD.getFilename(), PropertyType.ANT.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.ANT.getFilename(), folderPath); return false; } } } // Build.xml: create if not present or no <androidinit/> in it File buildXml = new File(projectFolder, SdkConstants.FN_BUILD_XML); boolean needsBuildXml = projectName != null || !buildXml.exists(); // if it seems there's no need for a new build.xml, look for inside the file // to try to detect old ones that may need updating. if (!needsBuildXml) { // we are looking for version-tag: followed by either an integer or "custom". if (checkFileContainsRegexp(buildXml, "version-tag:\\s*custom") != null) { //$NON-NLS-1$ println("%1$s: Found version-tag: custom. File will not be updated.", SdkConstants.FN_BUILD_XML); } else { Matcher m = checkFileContainsRegexp(buildXml, "version-tag:\\s*(\\d+)"); //$NON-NLS-1$ if (m == null) { println("----------\n" + "%1$s: Failed to find version-tag string. File must be updated.\n" + "In order to not erase potential customizations, the file will not be automatically regenerated.\n" + "If no changes have been made to the file, delete it manually and run the command again.\n" + "If you have made customizations to the build process, the file must be manually updated.\n" + "It is recommended to:\n" + "\t* Copy current file to a safe location.\n" + "\t* Delete original file.\n" + "\t* Run command again to generate a new file.\n" + "\t* Port customizations to the new file, by looking at the new rules file\n" + "\t located at <SDK>/tools/ant/build.xml\n" + "\t* Update file to contain\n" + "\t version-tag: custom\n" + "\t to prevent file from being rewritten automatically by the SDK tools.\n" + "----------\n", SdkConstants.FN_BUILD_XML); } else { String versionStr = m.group(1); if (versionStr != null) { // can't fail due to regexp above. int version = Integer.parseInt(versionStr); if (version < MIN_BUILD_VERSION_TAG) { println("%1$s: Found version-tag: %2$d. Expected version-tag: %3$d: file must be updated.", SdkConstants.FN_BUILD_XML, version, MIN_BUILD_VERSION_TAG); needsBuildXml = true; } } } } } if (needsBuildXml) { // create the map for place-holders of values to replace in the templates final HashMap<String, String> keywords = new HashMap<String, String>(); // put the current version-tag value keywords.put(PH_VERSION_TAG, Integer.toString(MIN_BUILD_VERSION_TAG)); // if there was no project name on the command line, figure one out. if (projectName == null) { // otherwise, take it from the existing build.xml if it exists already. if (buildXml.exists()) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); projectName = xpath.evaluate(XPATH_PROJECT_NAME, new InputSource(new FileInputStream(buildXml))); } catch (XPathExpressionException e) { // this is ok since we're going to recreate the file. mLog.error(e, "Unable to find existing project name from %1$s", SdkConstants.FN_BUILD_XML); } catch (FileNotFoundException e) { // can't happen since we check above. } } // if the project is still null, then we find another way. if (projectName == null) { extractPackageFromManifest(androidManifest, keywords); if (keywords.containsKey(PH_ACTIVITY_ENTRY_NAME)) { String activity = keywords.get(PH_ACTIVITY_ENTRY_NAME); // keep only the last segment if applicable int pos = activity.lastIndexOf('.'); if (pos != -1) { activity = activity.substring(pos + 1); } // Use the activity as project name projectName = activity; println("No project name specified, using Activity name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", activity, SdkConstants.FN_BUILD_XML); } else { // We need a project name. Just pick up the basename of the project // directory. File projectCanonicalFolder = projectFolder; try { projectCanonicalFolder = projectCanonicalFolder.getCanonicalFile(); } catch (IOException e) { // ignore, keep going } // Use the folder name as project name projectName = projectCanonicalFolder.getName(); println("No project name specified, using project folder name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", projectName, SdkConstants.FN_BUILD_XML); } } } // put the project name in the map for replacement during the template installation. keywords.put(PH_PROJECT_NAME, projectName); if (mLevel == OutputLevel.VERBOSE) { println("Regenerating %1$s with project name %2$s", SdkConstants.FN_BUILD_XML, keywords.get(PH_PROJECT_NAME)); } try { installTemplate("build.template", buildXml, keywords); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } if (hasProguard == false) { try { installTemplate(SdkConstants.FN_PROGUARD_CFG, new File(projectFolder, SdkConstants.FN_PROGUARD_CFG), null /*placeholderMap*/); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } return true; }
public boolean updateProject(String folderPath, IAndroidTarget target, String projectName, String libraryPath) { // since this is an update, check the folder does point to a project FileWrapper androidManifest = checkProjectFolder(folderPath, SdkConstants.FN_ANDROID_MANIFEST_XML); if (androidManifest == null) { return false; } // get the parent folder. FolderWrapper projectFolder = (FolderWrapper) androidManifest.getParentFolder(); boolean hasProguard = false; // Check there's a project.properties with a target *or* --target was specified IAndroidTarget originalTarget = null; boolean writeProjectProp = false; ProjectProperties props = ProjectProperties.load(projectFolder, PropertyType.PROJECT); if (props == null) { // no project.properties, try to load default.properties props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_DEFAULT); writeProjectProp = true; } if (props != null) { String targetHash = props.getProperty(ProjectProperties.PROPERTY_TARGET); originalTarget = mSdkManager.getTargetFromHashString(targetHash); // if the project is already setup with proguard, we won't copy the proguard config. hasProguard = props.getProperty(ProjectProperties.PROPERTY_PROGUARD_CONFIG) != null; } if (originalTarget == null && target == null) { mLog.error(null, "The project either has no target set or the target is invalid.\n" + "Please provide a --target to the '%1$s update' command.", SdkConstants.androidCmdName()); return false; } boolean saveProjectProps = false; ProjectPropertiesWorkingCopy propsWC = null; // Update default.prop if --target was specified if (target != null || writeProjectProp) { // we already attempted to load the file earlier, if that failed, create it. if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.PROJECT); } else { propsWC = props.makeWorkingCopy(PropertyType.PROJECT); } // set or replace the target if (target != null) { propsWC.setProperty(ProjectProperties.PROPERTY_TARGET, target.hashString()); } saveProjectProps = true; } if (libraryPath != null) { // At this point, the default properties already exists, either because they were // already there or because they were created with a new target if (propsWC == null) { assert props != null; propsWC = props.makeWorkingCopy(); } // check the reference is valid File libProject = new File(libraryPath); String resolvedPath; if (libProject.isAbsolute() == false) { libProject = new File(projectFolder, libraryPath); try { resolvedPath = libProject.getCanonicalPath(); } catch (IOException e) { mLog.error(e, "Unable to resolve path to library project: %1$s", libraryPath); return false; } } else { resolvedPath = libProject.getAbsolutePath(); } println("Resolved location of library project to: %1$s", resolvedPath); // check the lib project exists if (checkProjectFolder(resolvedPath, SdkConstants.FN_ANDROID_MANIFEST_XML) == null) { mLog.error(null, "No Android Manifest at: %1$s", resolvedPath); return false; } // look for other references to figure out the index int index = 1; while (true) { String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); assert props != null; if (props == null) { // This should not happen yet SDK bug 20535 says it can, not sure how. break; } String ref = props.getProperty(propName); if (ref == null) { break; } else { index++; } } String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index); propsWC.setProperty(propName, libraryPath); saveProjectProps = true; } // save the default props if needed. if (saveProjectProps) { try { assert propsWC != null; propsWC.save(); if (writeProjectProp) { println("Updated and renamed %1$s to %2$s", PropertyType.LEGACY_DEFAULT.getFilename(), PropertyType.PROJECT.getFilename()); } else { println("Updated %1$s", PropertyType.PROJECT.getFilename()); } } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.PROJECT.getFilename(), folderPath); return false; } if (writeProjectProp) { // need to delete the default prop file. ProjectProperties.delete(projectFolder, PropertyType.LEGACY_DEFAULT); } } // Refresh/create "sdk" in local.properties // because the file may already exists and contain other values (like apk config), // we first try to load it. props = ProjectProperties.load(projectFolder, PropertyType.LOCAL); if (props == null) { propsWC = ProjectProperties.create(projectFolder, PropertyType.LOCAL); } else { propsWC = props.makeWorkingCopy(); } // set or replace the sdk location. propsWC.setProperty(ProjectProperties.PROPERTY_SDK, mSdkFolder); try { propsWC.save(); println("Updated %1$s", PropertyType.LOCAL.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.LOCAL.getFilename(), folderPath); return false; } // legacy: check if build.properties must be renamed to ant.properties. props = ProjectProperties.load(projectFolder, PropertyType.ANT); if (props == null) { props = ProjectProperties.load(projectFolder, PropertyType.LEGACY_BUILD); if (props != null) { try { // get a working copy with the new property type propsWC = props.makeWorkingCopy(PropertyType.ANT); propsWC.save(); // delete the old file ProjectProperties.delete(projectFolder, PropertyType.LEGACY_BUILD); println("Renamed %1$s to %2$s", PropertyType.LEGACY_BUILD.getFilename(), PropertyType.ANT.getFilename()); } catch (Exception e) { mLog.error(e, "Failed to write %1$s file in '%2$s'", PropertyType.ANT.getFilename(), folderPath); return false; } } } // Build.xml: create if not present or no <androidinit/> in it File buildXml = new File(projectFolder, SdkConstants.FN_BUILD_XML); boolean needsBuildXml = projectName != null || !buildXml.exists(); // if it seems there's no need for a new build.xml, look for inside the file // to try to detect old ones that may need updating. if (!needsBuildXml) { // we are looking for version-tag: followed by either an integer or "custom". if (checkFileContainsRegexp(buildXml, "version-tag:\\s*custom") != null) { //$NON-NLS-1$ println("%1$s: Found version-tag: custom. File will not be updated.", SdkConstants.FN_BUILD_XML); } else { Matcher m = checkFileContainsRegexp(buildXml, "version-tag:\\s*(\\d+)"); //$NON-NLS-1$ if (m == null) { println("----------\n" + "%1$s: Failed to find version-tag string. File must be updated.\n" + "In order to not erase potential customizations, the file will not be automatically regenerated.\n" + "If no changes have been made to the file, delete it manually and run the command again.\n" + "If you have made customizations to the build process, the file must be manually updated.\n" + "It is recommended to:\n" + "\t* Copy current file to a safe location.\n" + "\t* Delete original file.\n" + "\t* Run command again to generate a new file.\n" + "\t* Port customizations to the new file, by looking at the new rules file\n" + "\t located at <SDK>/tools/ant/build.xml\n" + "\t* Update file to contain\n" + "\t version-tag: custom\n" + "\t to prevent file from being rewritten automatically by the SDK tools.\n" + "----------\n", SdkConstants.FN_BUILD_XML); } else { String versionStr = m.group(1); if (versionStr != null) { // can't fail due to regexp above. int version = Integer.parseInt(versionStr); if (version < MIN_BUILD_VERSION_TAG) { println("%1$s: Found version-tag: %2$d. Expected version-tag: %3$d: file must be updated.", SdkConstants.FN_BUILD_XML, version, MIN_BUILD_VERSION_TAG); needsBuildXml = true; } } } } } if (needsBuildXml) { // create the map for place-holders of values to replace in the templates final HashMap<String, String> keywords = new HashMap<String, String>(); // put the current version-tag value keywords.put(PH_VERSION_TAG, Integer.toString(MIN_BUILD_VERSION_TAG)); // if there was no project name on the command line, figure one out. if (projectName == null) { // otherwise, take it from the existing build.xml if it exists already. if (buildXml.exists()) { try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); projectName = xpath.evaluate(XPATH_PROJECT_NAME, new InputSource(new FileInputStream(buildXml))); } catch (XPathExpressionException e) { // this is ok since we're going to recreate the file. mLog.error(e, "Unable to find existing project name from %1$s", SdkConstants.FN_BUILD_XML); } catch (FileNotFoundException e) { // can't happen since we check above. } } // if the project is still null, then we find another way. if (projectName == null) { extractPackageFromManifest(androidManifest, keywords); if (keywords.containsKey(PH_ACTIVITY_ENTRY_NAME)) { String activity = keywords.get(PH_ACTIVITY_ENTRY_NAME); // keep only the last segment if applicable int pos = activity.lastIndexOf('.'); if (pos != -1) { activity = activity.substring(pos + 1); } // Use the activity as project name projectName = activity; println("No project name specified, using Activity name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", activity, SdkConstants.FN_BUILD_XML); } else { // We need a project name. Just pick up the basename of the project // directory. File projectCanonicalFolder = projectFolder; try { projectCanonicalFolder = projectCanonicalFolder.getCanonicalFile(); } catch (IOException e) { // ignore, keep going } // Use the folder name as project name projectName = projectCanonicalFolder.getName(); println("No project name specified, using project folder name '%1$s'.\n" + "If you wish to change it, edit the first line of %2$s.", projectName, SdkConstants.FN_BUILD_XML); } } } // put the project name in the map for replacement during the template installation. keywords.put(PH_PROJECT_NAME, projectName); if (mLevel == OutputLevel.VERBOSE) { println("Regenerating %1$s with project name %2$s", SdkConstants.FN_BUILD_XML, keywords.get(PH_PROJECT_NAME)); } try { installTemplate("build.template", buildXml, keywords); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } if (hasProguard == false) { try { installTemplate(SdkConstants.FN_PROGUARD_CFG, new File(projectFolder, SdkConstants.FN_PROGUARD_CFG), null /*placeholderMap*/); } catch (ProjectCreateException e) { mLog.error(e, null); return false; } } return true; }
diff --git a/core/Parser.java b/core/Parser.java index 08104f9..540b5c2 100755 --- a/core/Parser.java +++ b/core/Parser.java @@ -1,1557 +1,1557 @@ /* * Parser.java * * Parses a MIPS64 source code and fills the symbol table and the memory. * * (c) 2006 mancausoft, Vanni * * This file is part of the EduMIPS64 project, and is released under the GNU * General Public License. * * 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 */ /** Parses a MIPS64 source code and fills the symbol table and the memory. * @author mancausoft, Vanni */ package edumips64.core; import edumips64.Main; import edumips64.utils.*; import edumips64.core.is.*; import java.util.regex.*; import java.io.*; import java.util.*; import java.lang.reflect.Array; public class Parser { private enum AliasRegister {zero,at,v0,v1,a0,a1,a2,a3,t0,t1,t2,t3,t4,t5,t6,t7,s0,s1,s2,s3,s4,s5,s6,s7,t8,t9,k0,k1,gp,sp,fp,ra}; private static final String deprecateInstruction[] = {"BNEZ","BEQZ", "HALT", "DADDUI"}; private class VoidJump { public Instruction instr; public String label; int row; int column; int instrCount; String line; boolean isBranch = false; } ParserMultiWarningException warning; ParserMultiException error; boolean isFirstOutOfMemory; String path; int numError; int numWarning; /** Instance of Parser */ private static Parser instance = null; /** 0 null, 1 .data, 2 .text or .code */ private int status; /** File to be parsed */ private BufferedReader in; int memoryCount; String filename; private SymbolTable symTab; /** Singleton pattern constructor */ private Parser () { symTab = SymbolTable.getInstance(); } /** Singleton Pattern implementation * @return get the Singleton instance of the Parser */ public static Parser getInstance() { if(instance==null) instance = new Parser(); return instance; } private String fileToString(BufferedReader in) throws IOException { String ret = ""; int charRead =0; String line; while ((line = in.readLine())!=null) { String tmp = cleanFormat(line); if (tmp!=null) ret += tmp + "\n"; }while (charRead == 1024); return ret; } /** * */ private void checkLoop(String data, Stack<String> included ) throws IOException, ParserMultiException { int i = 0; do { i = data.indexOf("#include ",i); if (i != -1) { int end = data.indexOf("\n", i); if (end == -1) { end = data.length(); } int a = included.search(data.substring(i+9, end ).trim()); if ( a!= -1) { error = new ParserMultiException (); error.add("INCLUDE_LOOP",0,0,"#include "+ data.substring(i+9, end ).trim() ); throw error; } String filename = data.substring(i+9, end).split(";")[0].trim(); if (!(new File(filename)).isAbsolute()) filename = path + filename; String filetmp = fileToString(new BufferedReader(new InputStreamReader(new FileInputStream(filename),"ISO-8859-1"))); checkLoop(filetmp ,included); i ++; } }while(i!=-1); } /** Process the #include (Syntax #include file.ext ) */ private String preprocessor() throws IOException, ParserMultiException { String filetmp = ""; filetmp = fileToString(in); int i=0; //check loop Stack<String> included = new Stack<String>(); included.push(this.filename); checkLoop(filetmp, included); // include do { i = filetmp.indexOf("#include ",i); if (i != -1) { int end = filetmp.indexOf("\n", i); if (end == -1) { end = filetmp.length(); } edumips64.Main.logger.debug("Open by #include: " + filetmp.substring(i+9, end).trim()); String filename = filetmp.substring(i+9, end).split(";")[0].trim(); if (!(new File(filename)).isAbsolute()) filename = path + filename; filetmp = filetmp.substring(0,i) + fileToString (new BufferedReader(new InputStreamReader(new FileInputStream(filename) ,"ISO-8859-1"))) + filetmp.substring(end); } }while(i!=-1); return filetmp; } /** Loading from File * @param filename A String with the system-dependent file name * @throws FileNotFoundException if the file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading * @throws SecurityException if a security manager exists and its checkRead method denies read access to the file. */ public void parse(String filename) throws FileNotFoundException, SecurityException, IOException,ParserMultiException { in = new BufferedReader(new InputStreamReader(new FileInputStream(filename),"ISO-8859-1")); this.filename = filename; int oldindex = 0; int index = 0; filename = new File(filename).getAbsolutePath() ; while ((index = filename.indexOf(File.separator,index)) != -1 ) { oldindex = index; index ++; } path = filename.substring(0,oldindex+1); String code = preprocessor(); parse(code.toCharArray()); } /** Loading from buffer * @param buffer An Array of char with the MIPS code * */ public void parse(char[] buffer) throws IOException,ParserMultiException { in = new BufferedReader(new CharArrayReader(buffer)); doParsing(); } /** commit the parsing (public or private?) */ private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); - if (tmp<0 || tmp%8!=0 || tmp > edumips64.core.CPU.DATALIMIT) + if (tmp<0 || tmp%2!=0 || tmp > edumips64.core.CPU.DATALIMIT) { numError++; String er = "LABELADDRESSINVALID"; if (tmp > edumips64.core.CPU.DATALIMIT) er = "LABELTOOLARGE"; error.add(er,row,line.indexOf(param.substring(indPar,endPar))+1,line); error.add("LABELADDRESSINVALID",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } } /** Clean multiple tab or spaces in a bad format String //and converts this String to upper case * @param the bad format String * @return the cleaned String */ public String cleanFormat(String s){ if(s.length()>0 && s.charAt(0)!=';' && s.charAt(0)!='\n' ) { //String[] nocomment=s.split(";"); //s=nocomment[0];//.toUpperCase(); s=s.trim(); s=s.replace("\t"," "); while(s.contains(" ")) s=s.replace(" "," "); s=s.replace(", ",","); s=s.replace(" ,",","); if(s.length()>0) return s; } return null; } /** Check if is a valid string for a register * @param reg the string to validate * @return -1 if reg isn't a valid register, else a number of register */ private int isRegister(String reg) { try { int num; if(reg.charAt(0)=='r' || reg.charAt(0)=='R' || reg.charAt(0)=='$')//ci sono altri modi di scrivere un registro??? if(isNumber(reg.substring(1))) { num = Integer.parseInt(reg.substring(1)); if (num<32 && num>=0) return num; } if(reg.charAt(0)=='$' && (num=isAlias(reg.substring(1)))!=-1) return num; } catch(Exception e){} return -1; } /** Check if the parameter is a valid string for an alias-register * @param reg the string to validate * @return -1 if reg isn't a valid alias-register, else a number of register */ private int isAlias(String reg) { for(AliasRegister x : AliasRegister.values()) { if(reg.equalsIgnoreCase(x.name())) return x.ordinal(); } return -1; } /** Check if a string is a number * @param num the string to validate * @return true if num is a number, else false */ private boolean isNumber(String num) { if (num.charAt(0)=='+' || num.charAt(0)=='-') num = num.substring(1); for (int i=0; i<num.length(); i++) if(num.charAt(i)<'0'|| num.charAt(i)>'9') return false; return true; } /** Check if a string is a Hex number * @param num the string to validate * @return true if num is a number, else false */ private boolean isHexNumber(String num) { try { if (num.substring(0,2).compareToIgnoreCase("0X")!=0) return false; for (int i=2; i<num.length(); i++) if((num.charAt(i)<'0'|| num.charAt(i)>'9') && (num.charAt(i)<'A' || num.charAt(i)>'F')) return false; return true; } catch(Exception e) { return false; } } /** Check if a number is a valid .byte * @param num the value to validate * @return true if num is a valid .byte, else false */ private boolean isValidByte(long num) { if (num>255||num<-127) return false; return true; } /** Check if is a valid string for a register * @param imm the string to validate * @return false if imm isn't a valid immediate, else true */ private boolean isImmediate(String imm) { try { if(imm.charAt(0)=='#') imm = imm.substring(1); if(isNumber(imm)) { return true; } else if(isHexNumber(imm)) { if(imm.length()<=6) return true; } return false; } catch(Exception e) { return false; } } /** Replace all Tabulator with space * @param text the string to replace * @return a new String */ protected static String replaceTab (String text) { return text.replace("\t"," "); } /** Write a double in memory * @param row number of row * @param i * @param end * @param line the line of code * @param instr params */ private void writeDoubleInMemory (int row, int i, int end, String line, String instr ) throws MemoryElementNotFoundException { Memory mem = Memory.getInstance(); String value[] = instr.split(","); MemoryElement tmpMem = null; for(int j=0; j< Array.getLength(value);j++) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; Pattern p = Pattern.compile("-?[0-9]+.[0-9]+"); Matcher m = p.matcher(value[j]); boolean b = m.matches(); p = Pattern.compile("-?[0-9]+.[0-9]+E-?[0-9]+"); m = p.matcher(value[j]); b = b || m.matches(); /*if(isHexNumber(value[j])) { try { //insert here support for exadecimal } catch(NumberFormatException ex) { numError++; error.add("DOUBLE_TOO_LARGE",row,i+1,line); continue; } catch( Exception e)//modificare in un altro modo { e.printStackTrace(); } } else*/ if (b) { try { tmpMem.setBits (edumips64.core.fpu.FPInstructionUtils.doubleToBin(value[j] ,true),0); } catch(edumips64.core.fpu.FPExponentTooLargeException ex) { numError++; error.add("DOUBLE_EXT_TOO_LARGE",row,i+1,line); continue; } catch(edumips64.core.fpu.FPOverflowException ex) { numError++; //error.add("DOUBLE_TOO_LARGE",row,i+1,line); error.add("FP_OVERFLOW",row,i+1,line); continue; } catch(edumips64.core.fpu.FPUnderflowException ex) { numError++; //error.add("MINUS_DOUBLE_TOO_LARGE",row,i+1,line); error.add("FP_UNDERFLOW",row,i+1,line); continue; } catch(Exception e) { e.printStackTrace(); //non ci dovrebbe arrivare mai ma se per caso ci arriva che faccio? } } else { //manca riempimento errore numError++; error.add("INVALIDVALUE",row,i+1,line); i = line.length(); continue; } } } /** Write an integer in memory * @param row number of row * @param i * @param end * @param line the line of code * @param instr * @param numBit * @param name type of data */ private void writeIntegerInMemory (int row, int i, int end, String line, String instr, int numBit, String name ) throws MemoryElementNotFoundException { Memory mem = Memory.getInstance(); int posInWord=0; //position of byte to write into a doubleword String value[] = instr.split(","); MemoryElement tmpMem = null; for(int j=0; j< Array.getLength(value);j++) { if(j%(64/numBit)==0) { posInWord = 0; tmpMem = mem.getCell(memoryCount * 8); memoryCount++; } if(isNumber(value[j])) { try { long num = Long.parseLong(value[j]); if (numBit==8) tmpMem.writeByte((int)num,posInWord); else if (numBit==16) tmpMem.writeHalf((int)num,posInWord); else if (numBit==32) tmpMem.writeWord(num,posInWord); else if (numBit==64) tmpMem.writeDoubleWord(num); if( (num < -(Converter.powLong(2,numBit-1)) || num > (Converter.powLong( 2,numBit)-1)) && numBit != 64) throw new NumberFormatException(); } catch(NumberFormatException ex) { numError++; error.add(name.toUpperCase()+"_TOO_LARGE",row,i+1,line); continue; } catch(Exception e) { e.printStackTrace(); //non ci dovrebbe arrivare mai ma se per caso ci arriva che faccio? } } else if(isHexNumber(value[j])) { try { long num = Long.parseLong(Converter.hexToLong(value[j])); if (numBit==8) tmpMem.writeByte((int)num,posInWord); else if (numBit==16) tmpMem.writeHalf((int)num,posInWord); else if (numBit==32) tmpMem.writeWord(num,posInWord); else if (numBit==64) { String tmp = value[j].substring(2); while(tmp.charAt(0)=='0') tmp=tmp.substring(1); if(tmp.length()>numBit/4) throw new NumberFormatException(); tmpMem.writeDoubleWord(num); } if( (num < -(Converter.powLong(2,numBit-1)) || num > (Converter.powLong( 2,numBit)-1)) && numBit != 64) throw new NumberFormatException(); } catch(NumberFormatException ex) { numError++; error.add(name.toUpperCase() + "_TOO_LARGE",row,i+1,line); continue; } catch( Exception e)//modificare in un altro modo { e.printStackTrace(); } } else { //manca riempimento errore numError++; error.add("INVALIDVALUE",row,i+1,line); i = line.length(); continue; } posInWord += numBit/8; } } private List<String> splitStringParameters(String params, boolean auto_terminate) throws StringFormatException { List<String> pList = new LinkedList<String>(); StringBuffer temp = new StringBuffer(); edumips64.Main.logger.debug("Params: " + params); params = params.trim(); edumips64.Main.logger.debug("After trimming: " + params); int length = params.length(); boolean in_string = false; boolean escaping = false; boolean comma = false; for(int i = 0; i < length; ++i) { char c = params.charAt(i); if(!in_string) { switch(c) { case '"': if((!comma && pList.size() != 0) || i == length - 1) throw new StringFormatException(); in_string = true; comma = false; break; case ' ': case '\t': break; case ',': if(comma || i == 0 || i == length - 1) throw new StringFormatException(); comma = true; break; default: throw new StringFormatException(); } } else { if(!escaping && c == '\\') escaping = true; else if(!escaping && c == '"') { if(temp.length() > 0) { if(auto_terminate) { edumips64.Main.logger.debug("Behaving like .asciiz."); temp.append((char)0); } edumips64.Main.logger.debug("Added to pList string " + temp.toString()); pList.add(temp.toString()); temp.setLength(0); } in_string = false; } else { if(escaping) { escaping = false; temp.append('\\'); } temp.append(c); } } } if(pList.size() == 0 && in_string) // TODO: Unterminated string literal throw new StringFormatException(); return pList; } }
true
true
private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); if (tmp<0 || tmp%8!=0 || tmp > edumips64.core.CPU.DATALIMIT) { numError++; String er = "LABELADDRESSINVALID"; if (tmp > edumips64.core.CPU.DATALIMIT) er = "LABELTOOLARGE"; error.add(er,row,line.indexOf(param.substring(indPar,endPar))+1,line); error.add("LABELADDRESSINVALID",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } }
private void doParsing () throws IOException,ParserMultiException { boolean isFirstOutOfInstructionMemory = false; isFirstOutOfMemory = true; boolean halt = false; int row = 0; int nline=0; numError = 0; numWarning =0; int instrCount = -4; // Hack fituso by Andrea String line; error = new ParserMultiException(); warning = new ParserMultiWarningException(); LinkedList<VoidJump> voidJump = new LinkedList<VoidJump>(); Memory mem = Memory.getInstance(); memoryCount=0; String lastLabel =""; while ((line = in.readLine())!=null) //read all file { row++; for(int i=0; i<line.length(); i++) { if(line.charAt(i)==';') //comments break; if(line.charAt(i)==' ' || line.charAt(i)=='\t') continue; int tab = line.indexOf('\t',i); int space = line.indexOf(' ',i); if (tab == -1) tab=line.length(); if (space == -1) space=line.length(); int end = Math.min(tab,space)-1; String instr = line.substring(i,end+1); String parameters = null; try { if (line.charAt(i)=='.') { edumips64.Main.logger.debug("Processing " + instr); if(instr.compareToIgnoreCase(".DATA")==0) { status = 1; } else if (instr.compareToIgnoreCase(".TEXT")==0 || instr.compareToIgnoreCase(".CODE")==0 ) { status = 2; } else { String name = instr.substring(1); // The name, without the dot. if(status != 1) { numError++; error.add(name.toUpperCase() + "INCODE", row, i + 1, line); i = line.length(); continue; } try { if(!((instr.compareToIgnoreCase(".ASCII") == 0) || instr.compareToIgnoreCase(".ASCIIZ") == 0)) { // We don't want strings to be uppercase, do we? parameters = cleanFormat(line.substring(end+2)); parameters = parameters.toUpperCase(); parameters = parameters.split(";")[0]; Main.logger.debug("parameters: " + parameters); } else parameters = line.substring(end + 2); parameters = parameters.split(";")[0].trim(); Main.logger.debug("parameters: " + parameters); } catch (StringIndexOutOfBoundsException e) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } if (instr==null) { numWarning++; warning.add("VALUE_MISS", row, i+1, line); error.addWarning("VALUE_MISS", row, i+1, line); memoryCount++; i = line.length(); continue; } MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); Main.logger.debug("line: "+line); String[] comment = (line.substring(i)).split(";",2); if (Array.getLength(comment) == 2) { Main.logger.debug("found comments: "+comment[1]); tmpMem.setComment(comment[1]); } tmpMem.setCode(comment[0]); if(instr.compareToIgnoreCase(".ASCII") == 0 || instr.compareToIgnoreCase(".ASCIIZ") == 0) { edumips64.Main.logger.debug(".ascii(z): parameters = " + parameters); boolean auto_terminate = false; if(instr.compareToIgnoreCase(".ASCIIZ") == 0) auto_terminate = true; try { List<String> pList = splitStringParameters(parameters, auto_terminate); for(String current_string : pList) { edumips64.Main.logger.debug("Current string: [" + current_string + "]"); edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; int posInWord = 0; // TODO: Controllo sui parametri (es. virgolette?) int num = current_string.length(); boolean escape = false; boolean placeholder = false; int escaped = 0; // to avoid escape sequences to count as two bytes for(int tmpi = 0; tmpi < num; tmpi++) { if((tmpi - escaped) % 8 == 0 && (tmpi - escaped) != 0 && !escape) { edumips64.Main.logger.debug(".ascii(z): requested new memory cell (" + memoryCount + ")"); tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } char c = current_string.charAt(tmpi); int to_write = (int)c; edumips64.Main.logger.debug("Char: " + c + " (" + to_write + ") [" + Integer.toHexString(to_write) + "]"); if(escape) { switch(c) { case '0': to_write = 0; break; case 'n': to_write = 10; break; case 't': to_write = 9; break; case '\\': to_write = 92; break; case '"': to_write = 34; break; default: throw new StringFormatException(); } edumips64.Main.logger.debug("(escaped to [" + Integer.toHexString(to_write) + "])"); escape = false; c = 0; // to avoid re-entering the escape if branch. } if(placeholder) { if(c != '%' && c != 's' && c != 'd' && c != 'i') { edumips64.Main.logger.debug("Invalid placeholder: %" + c); // Invalid placeholder throw new StringFormatException(); } placeholder = false; } if(c == '%' && !placeholder) { edumips64.Main.logger.debug("Expecting on next step a valid placeholder..."); placeholder = true; } if(c == '\\') { escape = true; escaped++; continue; } tmpMem.writeByte(to_write, posInWord++); } } } catch(StringFormatException ex) { edumips64.Main.logger.debug("Badly formed string list"); numError++; // TODO: more descriptive error message error.add("INVALIDVALUE",row,0,line); } end = line.length(); } else if(instr.compareToIgnoreCase(".SPACE") == 0) { int posInWord=0; //position of byte to write into a doubleword memoryCount++; try { if(isHexNumber(parameters)) parameters = Converter.hexToLong(parameters); if(isNumber(parameters)) { int num = Integer.parseInt(parameters); for(int tmpi = 0; tmpi < num; tmpi++) { if(tmpi % 8 == 0 && tmpi != 0) { tmpMem = mem.getCell(memoryCount * 8); memoryCount++; posInWord = 0; } tmpMem.writeByte(0,posInWord++); } } else { throw new NumberFormatException(); } } catch(NumberFormatException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } catch(IrregularStringOfHexException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); continue; } posInWord ++; end = line.length(); } else if(instr.compareToIgnoreCase(".WORD")==0 || instr.compareToIgnoreCase(".WORD64")==0) { Main.logger.debug("pamword: "+parameters); writeIntegerInMemory(row, i, end, line, parameters, 64, "WORD"); end = line.length(); } else if (instr.compareToIgnoreCase(".WORD32")==0) { writeIntegerInMemory(row, i, end, line, parameters, 32, "WORD32"); end = line.length(); } else if(instr.compareToIgnoreCase(".BYTE")==0) { writeIntegerInMemory(row, i, end, line, parameters, 8, "BYTE"); end = line.length(); } else if(instr.compareToIgnoreCase(".WORD16")==0) { writeIntegerInMemory(row, i, end, line, parameters,16 , "WORD16"); end = line.length(); } else if(instr.compareToIgnoreCase(".DOUBLE")==0) { writeDoubleInMemory(row, i, end, line, parameters); end = line.length(); } else { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } } } else if(line.charAt(end)==':') { edumips64.Main.logger.debug("Processing a label.."); if(status==1) { edumips64.Main.logger.debug("in .data section"); MemoryElement tmpMem = null; tmpMem = mem.getCell(memoryCount * 8); try { symTab.setCellLabel(memoryCount * 8, line.substring(i, end)); } catch (SameLabelsException e) { // TODO: errore del parser edumips64.Main.logger.debug("Label " + line.substring(i, end) + " is already assigned"); } } else if(status==2) { edumips64.Main.logger.debug("in .text section"); lastLabel = line.substring(i,end); } edumips64.Main.logger.debug("done"); } else { if(status!=2) { numError++; error.add("INVALIDCODEFORDATA",row,i+1,line); i = line.length(); continue; } else if (status == 2) { boolean doPack = true; end++; Instruction tmpInst; // Check for halt-like instructions String temp = cleanFormat(line.substring(i)).toUpperCase(); if(temp.equals("HALT") || temp.equals("SYSCALL 0") || temp.equals("TRAP 0")) { halt = true; } //timmy for(int timmy = 0; timmy < Array.getLength(deprecateInstruction); timmy++) { if(deprecateInstruction[timmy].toUpperCase().equals(line.substring(i, end).toUpperCase())) { warning.add("WINMIPS64_NOT_MIPS64",row,i+1,line); error.addWarning("WINMIPS64_NOT_MIPS64",row,i+1,line); numWarning ++; } } tmpInst = Instruction.buildInstruction(line.substring(i,end).toUpperCase()); if (tmpInst == null) { numError++; error.add("INVALIDCODE",row,i+1,line); i = line.length(); continue; } String syntax = tmpInst.getSyntax(); instrCount += 4; if (syntax.compareTo("")!=0 && (line.length()<end+1)) { numError++; error.add("UNKNOWNSYNTAX",row,end,line); i = line.length(); continue; } if(syntax.compareTo("")!=0) { String param = cleanFormat(line.substring(end+1)); param = param.toUpperCase(); param = param.split(";")[0].trim(); Main.logger.debug("param: " + param); int indPar=0; for(int z=0; z < syntax.length(); z++) { if(syntax.charAt(z)=='%') { z++; if(syntax.charAt(z)=='R') //register { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int reg; if ((reg = isRegister(param.substring(indPar,endPar).trim()))>=0) { tmpInst.getParams().add(reg); indPar = endPar+1; } else { numError++; error.add("INVALIDREGISTER",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(0); i = line.length(); continue; } } else if(syntax.charAt(z)=='I') //immediate { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToShort(param.substring(indPar,endPar))); Main.logger.debug("imm = "+ imm); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { try { int offset=0,cc; MemoryElement tmpMem; cc = param.indexOf("+",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() + imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() + tmpMem1.getAddress()); } } else { cc = param.indexOf("-",indPar); if (cc!=-1) { tmpMem = symTab.getCell(param.substring(indPar,cc).trim()); if (isNumber(param.substring(cc+1,endPar))) { try { imm = Integer.parseInt(param.substring(indPar,endPar)); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } else if (isHexNumber(param.substring(cc+1,endPar))) { try { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if( imm < -32768 || imm > 32767) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(tmpMem.getAddress() - imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } else { MemoryElement tmpMem1 = symTab.getCell(param.substring(cc+1,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress() - tmpMem1.getAddress()); } } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } } } catch(MemoryElementNotFoundException ex) { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } else if(syntax.charAt(z)=='U') //Unsigned Immediate (5 bit) { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } int imm; if (isImmediate(param.substring(indPar,endPar))) { if (param.charAt(indPar)=='#') indPar++; if (isNumber(param.substring(indPar,endPar))) { try{ imm = Integer.parseInt(param.substring(indPar,endPar).trim()); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); } tmpInst.getParams().add(imm); indPar = endPar+1; } else if (isHexNumber(param.substring(indPar,endPar).trim())) { try { imm = (int) Long.parseLong(Converter.hexToLong(param.substring(indPar,endPar))); if (imm < 0) { numError++; error.add("VALUEISNOTUNSIGNED",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(imm); indPar = endPar+1; if( imm < 0 || imm > 31) throw new NumberFormatException(); } catch(NumberFormatException ex) { imm=0; numError++; error.add("5BIT_IMMEDIATE_TOO_LARGE",row,line.indexOf(param.substring(indPar,endPar))+1,line); tmpInst.getParams().add(imm); indPar = endPar+1; } catch(IrregularStringOfHexException ex) { //non ci dovrebbe mai arrivare } } } else { numError++; error.add("INVALIDIMMEDIATE",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='L') //Memory Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } try { MemoryElement tmpMem; if(param.substring(indPar,endPar).equals("")) tmpInst.getParams().add(0); else if(isNumber(param.substring(indPar,endPar).trim())) { int tmp = Integer.parseInt(param.substring(indPar,endPar).trim()); if (tmp<0 || tmp%2!=0 || tmp > edumips64.core.CPU.DATALIMIT) { numError++; String er = "LABELADDRESSINVALID"; if (tmp > edumips64.core.CPU.DATALIMIT) er = "LABELTOOLARGE"; error.add(er,row,line.indexOf(param.substring(indPar,endPar))+1,line); error.add("LABELADDRESSINVALID",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } tmpInst.getParams().add(tmp); } else { tmpMem = symTab.getCell(param.substring(indPar,endPar).trim()); tmpInst.getParams().add(tmpMem.getAddress()); } indPar = endPar+1; } catch (MemoryElementNotFoundException e) { numError++; error.add("LABELNOTFOUND",row,line.indexOf(param.substring(indPar,endPar))+1,line); i = line.length(); indPar = endPar+1; tmpInst.getParams().add(0); continue; } } else if(syntax.charAt(z)=='E') //Instruction Label { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); voidJump.add(tmpVoid); doPack = false; } } else if(syntax.charAt(z)=='B') //Instruction Label for branch { int endPar; if(z!=syntax.length()-1) endPar = param.indexOf(syntax.charAt(++z),indPar); else endPar = param.length(); if (endPar==-1) { numError++; error.add("SEPARATORMISS",row,indPar,line); i = line.length(); tmpInst.getParams().add(0); continue; } Integer labelAddr = symTab.getInstructionAddress(param.substring(indPar,endPar).trim()); if (labelAddr != null) { labelAddr -= instrCount + 4; tmpInst.getParams().add(labelAddr); } else { VoidJump tmpVoid = new VoidJump(); tmpVoid.instr = tmpInst; tmpVoid.row = row; tmpVoid.line = line; tmpVoid.column = indPar; tmpVoid.label = param.substring(indPar,endPar); tmpVoid.instrCount = instrCount; tmpVoid.isBranch = true; voidJump.add(tmpVoid); doPack = false; } } else { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } else { if(syntax.charAt(z)!=param.charAt(indPar++)) { numError++; error.add("UNKNOWNSYNTAX",row,1,line); i = line.length(); tmpInst.getParams().add(0); continue; } } } if( i == line.length()) continue; try { if (doPack) tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { try { tmpInst.pack(); } catch(IrregularStringOfBitsException e) { } } Main.logger.debug("line: "+line); String comment[] = line.split(";",2); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); tmpInst.setFullName(replaceTab(comment[0].substring(i))); if (Array.getLength(comment)==2) if (Array.getLength(comment)==2) tmpInst.setComment(comment[1]); try { mem.addInstruction(tmpInst,instrCount); symTab.setInstructionLabel(instrCount, lastLabel.toUpperCase()); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,i+1,line); i = line.length(); continue; } } catch(SameLabelsException ex) { numError++; error.add("SAMELABEL", row, 1, line); i = line.length(); } // Il finally e' totalmente inutile, ma è bello utilizzarlo per la // prima volta in un programma ;) finally { lastLabel = ""; } end = line.length(); } } i=end; } catch(MemoryElementNotFoundException ex) { if(isFirstOutOfMemory)//is first out of memory? { isFirstOutOfMemory = false; numError++; error.add("OUTOFMEMORY",row,i+1,line); i = line.length(); continue; } } catch(IrregularWriteOperationException ex) { numError++; error.add("INVALIDVALUE",row,i+1,line); break; } } } for (int i=0; i< voidJump.size();i++) { Integer labelAddr = symTab.getInstructionAddress(voidJump.get(i).label.trim()); if (labelAddr != null) { if (voidJump.get(i).isBranch) labelAddr -= voidJump.get(i).instrCount + 4; voidJump.get(i).instr.getParams().add(labelAddr); try { voidJump.get(i).instr.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } } else { numError++; error.add("LABELNOTFOUND",voidJump.get(i).row,voidJump.get(i).column ,voidJump.get(i).line); continue; } } in.close(); if(!halt) //if Halt is not present in code { numWarning++; warning.add("HALT_NOT_PRESENT",row,0,""); error.addWarning("HALT_NOT_PRESENT",row,0,""); try { Instruction tmpInst = Instruction.buildInstruction("SYSCALL"); tmpInst.getParams().add(0); tmpInst.setFullName("SYSCALL 0"); try { tmpInst.pack(); } catch(IrregularStringOfBitsException ex) { //ISGROUP HA SBAGLIATO QUALCOSA } mem.addInstruction(tmpInst,(instrCount+4)); symTab.setInstructionLabel((instrCount+4), ""); } catch(SymbolTableOverflowException ex) { if(isFirstOutOfInstructionMemory)//is first out of memory? { isFirstOutOfInstructionMemory = false; numError++; error.add("OUTOFINSTRUCTIONMEMORY",row,0,"Halt"); } } catch(SameLabelsException ex) {} // impossible } if (numError>0) { throw error; } else if (numWarning > 0) { throw warning; } }
diff --git a/src/de/hsanhalt/inf/studiappkoethen/activities/classes/MergedMarkers.java b/src/de/hsanhalt/inf/studiappkoethen/activities/classes/MergedMarkers.java index b071a87..a773b7c 100644 --- a/src/de/hsanhalt/inf/studiappkoethen/activities/classes/MergedMarkers.java +++ b/src/de/hsanhalt/inf/studiappkoethen/activities/classes/MergedMarkers.java @@ -1,80 +1,80 @@ package de.hsanhalt.inf.studiappkoethen.activities.classes; import java.util.List; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import de.hsanhalt.inf.studiappkoethen.R; public class MergedMarkers { //private static MergedMarkers INSTANCE; private Marker mergedMarker; private List<Marker> MarkerList; public MergedMarkers(Marker mergableMarker1, Marker mergableMarker2) { this.MarkerList.add(mergableMarker1); this.MarkerList.add(mergableMarker2); mergedMarker = mergableMarker1; mergeMarkers(); } /* public static MergedMarkers getInstance(Marker mergableMarker1, Marker mergableMarker2) { if (INSTANCE == null) { INSTANCE = new MergedMarkers(mergableMarker1, mergableMarker2); } return INSTANCE; }/**/ public Marker getMarker() { return this.mergedMarker; } public Marker addMarkerToMergedMarker(Marker addedMarker) { if(!MarkerInList(addedMarker)) { MarkerList.add(addedMarker); mergeMarkers(); } return mergedMarker; } private void mergeMarkers() { Marker merged = mergedMarker; merged.setTitle("Sammelmarker"); - merged.setSnippet("Bitte reinzoomen f�r detailierte Ansicht."); + merged.setSnippet("Bitte reinzoomen fuer detailierte Ansicht."); double addedLat = 0.0; double addedLng = 0.0; for(int i = 0; i < MarkerList.size(); i++) { addedLat += MarkerList.get(i).getPosition().latitude; addedLng += MarkerList.get(i).getPosition().longitude; } addedLat = addedLat / MarkerList.size(); addedLng = addedLng / MarkerList.size(); LatLng mergedLatLng = new LatLng(addedLat, addedLng); merged.setPosition(mergedLatLng); mergedMarker = merged; } public boolean MarkerInList(Marker marker) { return MarkerList.contains(marker); } public MarkerOptions getMarkerOptions() { MarkerOptions options = new MarkerOptions() .position(mergedMarker.getPosition()) .title(mergedMarker.getTitle()) .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)) .snippet(mergedMarker.getSnippet()); return options; } }
true
true
private void mergeMarkers() { Marker merged = mergedMarker; merged.setTitle("Sammelmarker"); merged.setSnippet("Bitte reinzoomen f�r detailierte Ansicht."); double addedLat = 0.0; double addedLng = 0.0; for(int i = 0; i < MarkerList.size(); i++) { addedLat += MarkerList.get(i).getPosition().latitude; addedLng += MarkerList.get(i).getPosition().longitude; } addedLat = addedLat / MarkerList.size(); addedLng = addedLng / MarkerList.size(); LatLng mergedLatLng = new LatLng(addedLat, addedLng); merged.setPosition(mergedLatLng); mergedMarker = merged; }
private void mergeMarkers() { Marker merged = mergedMarker; merged.setTitle("Sammelmarker"); merged.setSnippet("Bitte reinzoomen fuer detailierte Ansicht."); double addedLat = 0.0; double addedLng = 0.0; for(int i = 0; i < MarkerList.size(); i++) { addedLat += MarkerList.get(i).getPosition().latitude; addedLng += MarkerList.get(i).getPosition().longitude; } addedLat = addedLat / MarkerList.size(); addedLng = addedLng / MarkerList.size(); LatLng mergedLatLng = new LatLng(addedLat, addedLng); merged.setPosition(mergedLatLng); mergedMarker = merged; }
diff --git a/ini/trakem2/display/Polyline.java b/ini/trakem2/display/Polyline.java index 0de4a3c7..51af9f62 100644 --- a/ini/trakem2/display/Polyline.java +++ b/ini/trakem2/display/Polyline.java @@ -1,1427 +1,1428 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2008-2009 Albert Cardona and Rodney Douglas. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (http://www.gnu.org/licenses/gpl.txt ) This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.display; import ij.gui.Plot; import ij.ImagePlus; import ij.measure.Calibration; import ij.measure.ResultsTable; import ini.trakem2.imaging.LayerStack; import ini.trakem2.Project; import ini.trakem2.utils.Bureaucrat; import ini.trakem2.utils.IJError; import ini.trakem2.utils.M; import ini.trakem2.utils.ProjectToolbar; import ini.trakem2.utils.Utils; import ini.trakem2.utils.Worker; import ini.trakem2.vector.VectorString3D; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Composite; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Shape; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import features.ComputeCurvatures; import tracing.Path; import tracing.SearchThread; import tracing.TracerThread; import tracing.SearchProgressCallback; import javax.vecmath.Vector3d; import javax.vecmath.Point3f; /** A sequence of points that make multiple chained line segments. */ public class Polyline extends ZDisplayable implements Line3D { /**The number of points.*/ protected int n_points; /**The array of clicked x,y points as [2][n].*/ protected double[][] p = new double[2][0]; /**The array of Layers over which the points of this pipe live */ protected long[] p_layer = new long[0]; /** New empty Polyline. */ public Polyline(Project project, String title) { super(project, title, 0, 0); addToDatabase(); n_points = 0; } public Polyline(Project project, long id, String title, double width, double height, float alpha, boolean visible, Color color, boolean locked, AffineTransform at) { super(project, id, title, locked, at, width, height); this.visible = visible; this.alpha = alpha; this.visible = visible; this.color = color; this.n_points = -1; //used as a flag to signal "I have points, but unloaded" } /** Reconstruct from XML. */ public Polyline(final Project project, final long id, final HashMap ht_attr, final HashMap ht_links) { super(project, id, ht_attr, ht_links); // parse specific data for (Iterator it = ht_attr.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); String key = (String)entry.getKey(); String data = (String)entry.getValue(); if (key.equals("d")) { // parse the points // parse the SVG points data ArrayList al_p = new ArrayList(); // M: Move To // L: Line To // sequence is: M p[0][0],p[1][0] L p[0][1],p[1][1] L p[0][2],p[1][2] ... // first point: int i_start = data.indexOf('M'); int i_L = data.indexOf('L', i_start+1); int next = 0; while (-1 != i_L) { if (p[0].length == next) enlargeArrays(); // parse the point // 'X' int i_comma = data.indexOf(',', i_start+1); p[0][next] = Double.parseDouble(data.substring(i_start+1, i_comma)); // 'Y' i_L = data.indexOf('L', i_comma); int i_end = i_L; if (-1 == i_L) i_end = data.length(); p[1][next] = Double.parseDouble(data.substring(i_comma+1, i_end)); // prepare next point i_start = i_L; next++; } n_points = next; // scale arrays back, so minimal size and also same size as p_layer p = new double[][]{Utils.copy(p[0], n_points), Utils.copy(p[1], n_points)}; } else if (key.equals("layer_ids")) { // parse comma-separated list of layer ids. Creates empty Layer instances with the proper id, that will be replaced later. final String[] layer_ids = data.replaceAll(" ", "").trim().split(","); this.p_layer = new long[layer_ids.length]; for (int i=0; i<layer_ids.length; i++) { if (i == p_layer.length) enlargeArrays(); this.p_layer[i] = Long.parseLong(layer_ids[i]); } } } } /**Increase the size of the arrays by 5.*/ synchronized protected void enlargeArrays() { enlargeArrays(5); } synchronized protected void enlargeArrays(int n_more) { //catch length int length = p[0].length; //make copies double[][] p_copy = new double[2][length + n_more]; long[] p_layer_copy = new long[length + n_more]; //copy values System.arraycopy(p[0], 0, p_copy[0], 0, length); System.arraycopy(p[1], 0, p_copy[1], 0, length); System.arraycopy(p_layer, 0, p_layer_copy, 0, length); //assign them this.p = p_copy; this.p_layer = p_layer_copy; } /** Returns the index of the first point in the segment made of any two consecutive points. */ synchronized protected int findClosestSegment(final int x_p, final int y_p, final long layer_id, final double mag) { if (1 == n_points) return -1; if (0 == n_points) return -1; int index = -1; double d = (10.0D / mag); if (d < 2) d = 2; double sq_d = d*d; double min_sq_dist = Double.MAX_VALUE; final Calibration cal = layer_set.getCalibration(); final double z = layer_set.getLayer(layer_id).getZ() * cal.pixelWidth; double x2 = p[0][0] * cal.pixelWidth; double y2 = p[1][0] * cal.pixelHeight; double z2 = layer_set.getLayer(p_layer[0]).getZ() * cal.pixelWidth; double x1, y1, z1; for (int i=1; i<n_points; i++) { x1 = x2; y1 = y2; z1 = z2; x2 = p[0][i] * cal.pixelWidth; y2 = p[1][i] * cal.pixelHeight; z2 = layer_set.getLayer(p_layer[i]).getZ() * cal.pixelWidth; double sq_dist = M.distancePointToSegmentSq(x_p * cal.pixelWidth, y_p * cal.pixelHeight, z, x1, y1, z1, x2, y2, z2); if (sq_dist < sq_d && sq_dist < min_sq_dist) { min_sq_dist = sq_dist; index = i-1; // previous } } return index; } /**Find a point in an array, with a precision dependent on the magnification. Only points in the given layer are considered, the rest are ignored. Returns -1 if none found. */ synchronized protected int findPoint(final int x_p, final int y_p, final long layer_id, final double mag) { int index = -1; double d = (10.0D / mag); if (d < 2) d = 2; double min_dist = Double.MAX_VALUE; for (int i=0; i<n_points; i++) { double dist = Math.abs(x_p - p[0][i]) + Math.abs(y_p - p[1][i]); if (layer_id == p_layer[i] && dist <= d && dist <= min_dist) { min_dist = dist; index = i; } } return index; } /** Find closest point within the current layer. */ synchronized protected int findNearestPoint(final int x_p, final int y_p, final long layer_id) { int index = -1; double min_dist = Double.MAX_VALUE; for (int i=0; i<n_points; i++) { if (layer_id != p_layer[i]) continue; double sq_dist = Math.pow(p[0][i] - x_p, 2) + Math.pow(p[1][i] - y_p, 2); if (sq_dist < min_dist) { index = i; min_dist = sq_dist; } } return index; } /**Remove a point from the bezier backbone and its two associated control points.*/ synchronized protected void removePoint(final int index) { // check preconditions: if (index < 0) { return; } else if (n_points - 1 == index) { //last point out n_points--; } else { //one point out (but not the last) --n_points; // shift all points after 'index' one position to the left: for (int i=index; i<n_points; i++) { p[0][i] = p[0][i+1]; //the +1 doesn't fail ever because the n_points has been adjusted above, but the arrays are still the same size. The case of deleting the last point is taken care above. p[1][i] = p[1][i+1]; p_layer[i] = p_layer[i+1]; } } // Reset or fix autotracing records if (index < last_autotrace_start && n_points > 0) { last_autotrace_start--; } else last_autotrace_start = -1; //update in database updateInDatabase("points"); } /**Move backbone point by the given deltas.*/ public void dragPoint(final int index, final int dx, final int dy) { if (index < 0 || index >= n_points) return; p[0][index] += dx; p[1][index] += dy; // Reset autotracing records if (-1 != last_autotrace_start && index >= last_autotrace_start) { last_autotrace_start = -1; } } /** @param x_p,y_p in local coords. */ protected double[] sqDistanceToEndPoints(final double x_p, final double y_p, final long layer_id) { final Calibration cal = layer_set.getCalibration(); final double lz = layer_set.getLayer(layer_id).getZ(); final double p0z =layer_set.getLayer(p_layer[0]).getZ(); final double pNz =layer_set.getLayer(p_layer[n_points -1]).getZ(); double sqdist0 = (p[0][0] - x_p) * (p[0][0] - x_p) * cal.pixelWidth * cal.pixelWidth + (p[1][0] - y_p) * (p[1][0] - y_p) * cal.pixelHeight * cal.pixelHeight + (lz - p0z) * (lz - p0z) * cal.pixelWidth * cal.pixelWidth; // double multiplication by pixelWidth, ok, since it's what it's used to compute the pixel position in Z double sqdistN = (p[0][n_points-1] - x_p) * (p[0][n_points-1] - x_p) * cal.pixelWidth * cal.pixelWidth + (p[1][n_points-1] - y_p) * (p[1][n_points-1] - y_p) * cal.pixelHeight * cal.pixelHeight + (lz - pNz) * (lz - pNz) * cal.pixelWidth * cal.pixelWidth; return new double[]{sqdist0, sqdistN}; } synchronized public void insertPoint(int i, int x_p, int y_p, long layer_id) { if (-1 == n_points) setupForDisplay(); //reload if (p[0].length == n_points) enlargeArrays(); double[][] p2 = new double[2][p[0].length]; long[] p_layer2 = new long[p_layer.length]; if (0 != i) { System.arraycopy(p[0], 0, p2[0], 0, i); System.arraycopy(p[1], 0, p2[1], 0, i); System.arraycopy(p_layer, 0, p_layer2, 0, i); } p2[0][i] = x_p; p2[1][i] = y_p; p_layer2[i] = layer_id; if (n_points != i) { System.arraycopy(p[0], i, p2[0], i+1, n_points -i); System.arraycopy(p[1], i, p2[1], i+1, n_points -i); System.arraycopy(p_layer, i, p_layer2, i+1, n_points -i); } p = p2; p_layer = p_layer2; n_points++; } /** Append a point at the end. Returns the index of the new point. */ synchronized protected int appendPoint(int x_p, int y_p, long layer_id) { if (-1 == n_points) setupForDisplay(); //reload //check array size if (p[0].length == n_points) { enlargeArrays(); } p[0][n_points] = x_p; p[1][n_points] = y_p; p_layer[n_points] = layer_id; n_points++; return n_points-1; } /**Add a point either at the end or between two existing points, with accuracy depending on magnification. The width of the new point is that of the closest point after which it is inserted.*/ synchronized protected int addPoint(int x_p, int y_p, long layer_id, double magnification) { if (-1 == n_points) setupForDisplay(); //reload //lookup closest point and then get the closest clicked point to it int index = 0; if (n_points > 1) index = findClosestSegment(x_p, y_p, layer_id, magnification); //check array size if (p[0].length == n_points) { enlargeArrays(); } //decide: if (0 == n_points || 1 == n_points || index + 1 == n_points) { //append at the end p[0][n_points] = x_p; p[1][n_points] = y_p; p_layer[n_points] = layer_id; index = n_points; last_autotrace_start = -1; } else if (-1 == index) { // decide whether to append at the end or prepend at the beginning // compute distance in the 3D space to the first and last points final double[] sqd0N = sqDistanceToEndPoints(x_p, y_p, layer_id); //final double sqdist0 = sqd0N[0]; //final double sqdistN = sqd0N[1]; //if (sqdistN < sqdist0) if (sqd0N[1] < sqd0N[0]) { //append at the end p[0][n_points] = x_p; p[1][n_points] = y_p; p_layer[n_points] = layer_id; index = n_points; last_autotrace_start = -1; } else { // prepend at the beginning for (int i=n_points-1; i>-1; i--) { p[0][i+1] = p[0][i]; p[1][i+1] = p[1][i]; p_layer[i+1] = p_layer[i]; } p[0][0] = x_p; p[1][0] = y_p; p_layer[0] = layer_id; index = 0; if (-1 != last_autotrace_start) last_autotrace_start++; } } else { //insert at index: index++; //so it is added after the closest point; // 1 - copy second half of array int sh_length = n_points -index; double[][] p_copy = new double[2][sh_length]; long[] p_layer_copy = new long[sh_length]; System.arraycopy(p[0], index, p_copy[0], 0, sh_length); System.arraycopy(p[1], index, p_copy[1], 0, sh_length); System.arraycopy(p_layer, index, p_layer_copy, 0, sh_length); // 2 - insert value into 'p' (the two control arrays get the same value) p[0][index] = x_p; p[1][index] = y_p; p_layer[index] = layer_id; // 3 - copy second half into the array System.arraycopy(p_copy[0], 0, p[0], index+1, sh_length); System.arraycopy(p_copy[1], 0, p[1], index+1, sh_length); System.arraycopy(p_layer_copy, 0, p_layer, index+1, sh_length); // Reset autotracing records if (index < last_autotrace_start) { last_autotrace_start++; } } //add one up this.n_points++; return index; } synchronized protected void appendPoints(final double[] px, final double[] py, final long[] p_layer_ids, int len) { for (int i=0, next=n_points; i<len; i++, next++) { if (next == p[0].length) enlargeArrays(); p[0][next] = px[i]; p[1][next] = py[i]; p_layer[next] = p_layer_ids[i]; } n_points += len; updateInDatabase("points"); } public void paint(final Graphics2D g, final double magnification, final boolean active, final int channels, final Layer active_layer) { if (0 == n_points) return; if (-1 == n_points) { // load points from the database setupForDisplay(); } //arrange transparency Composite original_composite = null; if (alpha != 1.0f) { original_composite = g.getComposite(); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; } final boolean no_color_cues = "true".equals(project.getProperty("no_color_cues")); final long layer_id = active_layer.getId(); final double z_current = active_layer.getZ(); // Different approach: a point paints itself and towards the next, except the last point. // First point: double z = layer_set.getLayer(p_layer[0]).getZ(); boolean paint = true; if (z < z_current) { if (no_color_cues) paint = false; else g.setColor(Color.red); } else if (z == z_current) g.setColor(this.color); else if (no_color_cues) paint = false; else g.setColor(Color.blue); // Paint half line: if (paint && n_points > 1) { g.drawLine((int)p[0][0], (int)p[1][0], (int)((p[0][0] + p[0][1])/2), (int)((p[1][0] + p[1][1])/2)); } final Rectangle srcRect = Display.getFront().getCanvas().getSrcRect(); // Paint handle if active and in the current layer if (active && layer_id == p_layer[0]) { g.setColor(this.color); DisplayCanvas.drawHandle(g, p[0][0], p[1][0], srcRect, magnification); // Label the first point distinctively Composite comp = g.getComposite(); AffineTransform aff = g.getTransform(); g.setTransform(new AffineTransform()); g.setColor(Color.white); g.setXORMode(Color.green); g.drawString("1", (int)( (p[0][0] - srcRect.x)*magnification + (4.0 / magnification)), (int)( (p[1][0] - srcRect.y)*magnification)); // displaced 4 screen pixels to the right g.setComposite(comp); g.setTransform(aff); } for (int i=1; i<n_points; i++) { // Determine color z = layer_set.getLayer(p_layer[i]).getZ(); paint = true; if (z < z_current) { if (no_color_cues) paint = false; else g.setColor(Color.red); } else if (z == z_current) g.setColor(this.color); else if (no_color_cues) paint = false; else g.setColor(Color.blue); if (!paint) continue; // paint half line towards previous point: g.drawLine((int)p[0][i], (int)p[1][i], (int)((p[0][i] + p[0][i-1])/2), (int)((p[1][i] + p[1][i-1])/2)); // paint half line towards next point: if (i < n_points -1) { g.drawLine((int)p[0][i], (int)p[1][i], (int)((p[0][i] + p[0][i+1])/2), (int)((p[1][i] + p[1][i+1])/2)); } // Paint handle if active and in the current layer if (active && layer_id == p_layer[i]) { g.setColor(this.color); DisplayCanvas.drawHandle(g, p[0][i], p[1][i], srcRect, magnification); } } //Transparency: fix alpha composite back to original. if (null != original_composite) { g.setComposite(original_composite); } } public void keyPressed(KeyEvent ke) { int keyCode = ke.getKeyCode(); switch (keyCode) { case KeyEvent.VK_D: if (-1 == last_autotrace_start) { if (0 > n_points) Utils.log("Cannot remove last set of autotraced points:\n Manual editions exist, or never autotraced."); return; } // Else, remove: final int len = n_points - last_autotrace_start; n_points = last_autotrace_start; last_autotrace_start = -1; repaint(true); Utils.log("Removed " + len + " autotraced points."); return; case KeyEvent.VK_R: // reset tracing tr_map.remove(layer_set); ke.consume(); Utils.log("Reset tracing data for Polyline " + this); return; } } /**Helper vars for mouse events. It's safe to have them static since only one Pipe will be edited at a time.*/ static protected int index; static private boolean is_new_point = false; final static private HashMap<LayerSet,TraceParameters> tr_map = new HashMap<LayerSet,TraceParameters>(); private int last_autotrace_start = -1; static public void flushTraceCache(final Project project) { synchronized (tr_map) { for (Iterator<LayerSet> it = tr_map.keySet().iterator(); it.hasNext(); ) { if (it.next().getProject() == project) it.remove(); } } } /** Shared between all Polyline of the same LayerSet. The issue of locking doesn't arise because there is only one source of mouse input. If you try to run it programatically with synthetic MouseEvent, that's your problem. */ static private class TraceParameters { boolean update = true; ImagePlus virtual = null; double scale = 1; ComputeCurvatures hessian = null; TracerThread tracer = null; // catched thread for KeyEvent to attempt to stop it } public void mousePressed(MouseEvent me, int x_p, int y_p, double mag) { // transform the x_p, y_p to the local coordinates int x_pd = x_p; int y_pd = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_p = (int)po.x; y_p = (int)po.y; } final int tool = ProjectToolbar.getToolId(); final Display display = ((DisplayCanvas)me.getSource()).getDisplay(); final long layer_id = display.getLayer().getId(); index = findPoint(x_p, y_p, layer_id, mag); if (ProjectToolbar.PENCIL == tool && n_points > 0 && -1 == index && !me.isShiftDown() && !Utils.isControlDown(me)) { // Use Mark Longair's tracing: from the clicked point to the last one final double scale = layer_set.getVirtualizationScale(); // Ok now with all found images, create a virtual stack that provides access to them all, with caching. final Worker[] worker = new Worker[2]; TraceParameters tr_ = tr_map.get(layer_set); final TraceParameters tr = null == tr_ ? new TraceParameters() : tr_; if (null == tr_) { synchronized (tr_map) { tr_map.put(layer_set, tr); } } if (tr.update) { worker[0] = new Worker("Preparing Hessian...") { public void run() { startedWorking(); try { Utils.log("Push ESCAPE key to cancel autotrace anytime."); ImagePlus virtual = new LayerStack(layer_set, scale, ImagePlus.GRAY8, Patch.class, display.getDisplayChannelAlphas()).getImagePlus(); //virtual.show(); Calibration cal = virtual.getCalibration(); double minimumSeparation = 1; if (cal != null) minimumSeparation = Math.min(cal.pixelWidth, Math.min(cal.pixelHeight, cal.pixelDepth)); ComputeCurvatures hessian = new ComputeCurvatures(virtual, minimumSeparation, null, cal != null); hessian.run(); tr.virtual = virtual; tr.scale = scale; tr.hessian = hessian; tr.update = false; } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[0], project); } Point2D.Double po = transformPoint(p[0][n_points-1], p[1][n_points-1]); final int start_x = (int)po.x; final int start_y = (int)po.y; final int start_z = layer_set.indexOf(layer_set.getLayer(p_layer[n_points-1])); // 0-based final int goal_x = (int)(x_pd * scale); // must transform into virtual space final int goal_y = (int)(y_pd * scale); final int goal_z = layer_set.indexOf(display.getLayer()); /* Utils.log2("x_pd, y_pd : " + x_pd + ", " + y_pd); Utils.log2("scale: " + scale); Utils.log2("start: " + start_x + "," + start_y + ", " + start_z); Utils.log2("goal: " + goal_x + "," + goal_y + ", " + goal_z); Utils.log2("virtual: " + tr.virtual); */ final boolean simplify = me.isAltDown(); worker[1] = new Worker("Tracer - waiting on hessian") { public void run() { startedWorking(); try { if (null != worker[0]) { // Wait until hessian is ready worker[0].join(); } setTaskName("Tracing path"); final int reportEveryMilliseconds = 2000; tr.tracer = new TracerThread(tr.virtual, 0, 255, 120, // timeout seconds reportEveryMilliseconds, start_x, start_y, start_z, goal_x, goal_y, goal_z, true, // reciproal pix values at start and goal tr.virtual.getStackSize() == 1, tr.hessian, null == tr.hessian ? 1 : 4, null, null != tr.hessian); tr.tracer.addProgressListener(new SearchProgressCallback() { public void pointsInSearch(SearchThread source, int inOpen, int inClosed) { worker[1].setTaskName("Tracing path: open=" + inOpen + " closed=" + inClosed); } public void finished(SearchThread source, boolean success) { if (!success) { Utils.logAll("Could NOT trace a path"); } } public void threadStatus(SearchThread source, int currentStatus) { // This method gets called every reportEveryMilliseconds if (worker[1].hasQuitted()) { source.requestStop(); } } }); tr.tracer.run(); final Path result = tr.tracer.getResult(); tr.tracer = null; if (null == result) { Utils.log("Finding a path failed"); //: "+ // not public //SearchThread.exitReasonStrings[tracer.getExitReason()]); return; } // TODO: precise_x_positions etc are likely to be broken (calibrated or something) // Remove bogus points: those at the end with 0,0 coords int len = result.points; final double[][] pos = result.getXYZUnscaled(); for (int i=len-1; i>-1; i--) { if (0 == pos[0][i] && 0 == pos[1][i]) { len--; } else break; } // Transform points: undo scale, and bring to this Polyline AffineTransform: final AffineTransform aff = new AffineTransform(); /* Inverse order: */ /* 2 */ aff.concatenate(Polyline.this.at.createInverse()); /* 1 */ aff.scale(1/scale, 1/scale); final double[] po = new double[len * 2]; for (int i=0, j=0; i<len; i++, j+=2) { po[j] = pos[0][i]; po[j+1] = pos[1][i]; } final double[] po2 = new double[len * 2]; aff.transform(po, 0, po2, 0, len); // what a stupid format: consecutive x,y pairs long[] p_layer_ids = new long[len]; double[] pox = new double[len]; double[] poy = new double[len]; for (int i=0, j=0; i<len; i++, j+=2) { - p_layer_ids[i] = layer_set.getNearestLayer(pos[2][i]).getId(); // z_positions in 0-(N-1), not in 0-N like slices! + p_layer_ids[i] = layer_set.getLayer((int)pos[2][i]).getId(); // z_positions in 0-(N-1), not in 1-N like slices! pox[i] = po2[j]; poy[i] = po2[j+1]; } // Simplify path: to steps of 5 calibration units, or 5 pixels when not calibrated. if (simplify) { + setTaskName("Simplifying path"); Object[] ob = Polyline.simplify(pox, poy, p_layer_ids, 10000, layer_set); pox = (double[])ob[0]; poy = (double[])ob[1]; p_layer_ids = (long[])ob[2]; len = pox.length; } // Record the first newly-added autotraced point index: last_autotrace_start = Polyline.this.n_points; Polyline.this.appendPoints(pox, poy, p_layer_ids, len); Polyline.this.repaint(true); Utils.logAll("Added " + len + " new points."); } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[1], project); index = -1; return; } if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { if (Utils.isControlDown(me) && me.isShiftDown()) { final long lid = Display.getFrontLayer(this.project).getId(); if (-1 == index || lid != p_layer[index]) { index = findNearestPoint(x_p, y_p, layer_id); } if (-1 != index) { //delete point removePoint(index); index = -1; repaint(false); } // In any case, terminate return; } if (-1 != index && layer_id != p_layer[index]) index = -1; // disable! //if no conditions are met, attempt to add point else if (-1 == index && !me.isShiftDown() && !me.isAltDown()) { //add a new point index = addPoint(x_p, y_p, layer_id, mag); is_new_point = true; repaint(false); return; } } } public void mouseDragged(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_d_old, int y_d_old) { // transform to the local coordinates if (!this.at.isIdentity()) { //final Point2D.Double p = inverseTransformPoint(x_p, y_p); //x_p = (int)p.x; //y_p = (int)p.y; final Point2D.Double pd = inverseTransformPoint(x_d, y_d); x_d = (int)pd.x; y_d = (int)pd.y; final Point2D.Double pdo = inverseTransformPoint(x_d_old, y_d_old); x_d_old = (int)pdo.x; y_d_old = (int)pdo.y; } final int tool = ProjectToolbar.getToolId(); if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { //if a point in the backbone is found, then: if (-1 != index && !me.isAltDown() && !me.isShiftDown()) { dragPoint(index, x_d - x_d_old, y_d - y_d_old); repaint(false); return; } } } public void mouseReleased(MouseEvent me, int x_p, int y_p, int x_d, int y_d, int x_r, int y_r) { final int tool = ProjectToolbar.getToolId(); if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { repaint(); //needed at least for the removePoint } //update points in database if there was any change if (-1 != index) { if (is_new_point) { // update all points, since the index may have changed updateInDatabase("points"); } else if (-1 != index && index != n_points) { //second condition happens when the last point has been removed // not implemented // updateInDatabase(getUpdatePointForSQL(index)); // Instead: updateInDatabase("points"); } else if (index != n_points) { // don't do it when the last point is removed // update all updateInDatabase("points"); } updateInDatabase("dimensions"); } else if (x_r != x_p || y_r != y_p) { updateInDatabase("dimensions"); } repaint(true); // reset is_new_point = false; index = -1; } synchronized protected void calculateBoundingBox(final boolean adjust_position) { if (0 == n_points) { this.width = this.height = 0; layer_set.updateBucket(this); return; } final double[] m = calculateDataBoundingBox(); this.width = m[2] - m[0]; // max_x - min_x; this.height = m[3] - m[1]; // max_y - min_y; if (adjust_position) { // now readjust points to make min_x,min_y be the x,y for (int i=0; i<n_points; i++) { p[0][i] -= m[0]; // min_x; p[1][i] -= m[1]; // min_y; } this.at.translate(m[0], m[1]) ; // (min_x, min_y); // not using super.translate(...) because a preConcatenation is not needed; here we deal with the data. updateInDatabase("transform"); } updateInDatabase("dimensions"); layer_set.updateBucket(this); } /** Returns min_x, min_y, max_x, max_y. */ protected double[] calculateDataBoundingBox() { double min_x = Double.MAX_VALUE; double min_y = Double.MAX_VALUE; double max_x = 0.0D; double max_y = 0.0D; // check the points for (int i=0; i<n_points; i++) { if (p[0][i] < min_x) min_x = p[0][i]; if (p[1][i] < min_y) min_y = p[1][i]; if (p[0][i] > max_x) max_x = p[0][i]; if (p[1][i] > max_y) max_y = p[1][i]; } return new double[]{min_x, min_y, max_x, max_y}; } /**Release all memory resources taken by this object.*/ synchronized public void destroy() { super.destroy(); p = null; p_layer = null; } /**Release memory resources used by this object: namely the arrays of points, which can be reloaded with a call to setupForDisplay()*/ synchronized public void flush() { p = null; p_layer = null; n_points = -1; // flag that points exist but are not loaded } public void repaint() { repaint(true); } /**Repaints in the given ImageCanvas only the area corresponding to the bounding box of this Pipe. */ public void repaint(boolean repaint_navigator) { //TODO: this could be further optimized to repaint the bounding box of the last modified segments, i.e. the previous and next set of interpolated points of any given backbone point. This would be trivial if each segment of the Bezier curve was an object. Rectangle box = getBoundingBox(null); calculateBoundingBox(true); box.add(getBoundingBox(null)); Display.repaint(layer_set, this, box, 5, repaint_navigator); } /**Make this object ready to be painted.*/ synchronized private void setupForDisplay() { if (-1 == n_points) n_points = 0; // load points /* Database storage not implemented yet if (null == p) { ArrayList al = project.getLoader().fetchPolylinePoints(id); n_points = al.size(); p = new double[2][n_points]; p_layer = new long[n_points]; Iterator it = al.iterator(); int i = 0; while (it.hasNext()) { Object[] ob = (Object[])it.next(); p[0][i] = ((Double)ob[0]).doubleValue(); p[1][i] = ((Double)ob[1]).doubleValue(); p_layer[i] = ((Long)ob[7]).longValue(); i++; } } */ } /** The exact perimeter of this pipe, in integer precision. */ synchronized public Polygon getPerimeter() { if (null == p || p[0].length < 2) return new Polygon(); // local pointers, since they may be transformed int n_points = this.n_points; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; } int[] x = new int[n_points]; int[] y = new int[n_points]; for (int i=0; i<n_points; i++) { x[i] = (int)p[0][i]; y[i] = (int)p[1][i]; } return new Polygon(x, y, n_points); } public boolean isDeletable() { return 0 == n_points; } /** The number of points in this pipe. */ public int length() { if (-1 == n_points) setupForDisplay(); return n_points; } synchronized public boolean contains(final Layer layer, int x, int y) { Display front = Display.getFront(); double radius = 10; if (null != front) { double mag = front.getCanvas().getMagnification(); radius = (10.0D / mag); if (radius < 2) radius = 2; } // else assume fixed radius of 10 around the line final long lid = layer.getId(); final double z = layer.getZ(); for (int i=0; i<n_points; i++) { if (lid == p_layer[i]) { // check both lines: if (i > 0 && M.distancePointToLine(x, y, p[0][i-1], p[1][i-1], p[0][i], p[1][i]) < radius) { return true; } if (i < (n_points -1) && M.distancePointToLine(x, y, p[0][i], p[1][i], p[0][i+1], p[1][i+1]) < radius) { return true; } } else if (i > 0) { double z1 = layer_set.getLayer(p_layer[i-1]).getZ(); double z2 = layer_set.getLayer(p_layer[i]).getZ(); if ( (z1 < z && z < z2) || (z2 < z && z < z1) ) { // line between j and j-1 crosses the given layer if (M.distancePointToLine(x, y, p[0][i-1], p[1][i-1], p[0][i], p[1][i]) < radius) { return true; } } } } return false; } /* Scan the Display and link Patch objects that lay under this Pipe's bounding box. */ public boolean linkPatches() { // TODO needs to check all layers!! unlinkAll(Patch.class); // sort points by layer id final HashMap<Long,ArrayList<Integer>> m = new HashMap<Long,ArrayList<Integer>>(); for (int i=0; i<n_points; i++) { ArrayList<Integer> a = m.get(p_layer[i]); if (null == a) { a = new ArrayList<Integer>(); m.put(p_layer[i], a); } a.add(i); } boolean must_lock = false; // For each layer id, search patches whose perimeter includes // one of the backbone points in this path: for (Map.Entry<Long,ArrayList<Integer>> e : m.entrySet()) { final Layer layer = layer_set.getLayer(e.getKey().longValue()); for (Displayable patch : layer.getDisplayables(Patch.class)) { final Polygon perimeter = patch.getPerimeter(); for (Integer in : e.getValue()) { final int i = in.intValue(); if (perimeter.contains(p[0][i], p[1][i])) { this.link(patch); if (patch.locked) must_lock = true; break; } } } } // set the locked flag to this and all linked ones if (must_lock && !locked) { setLocked(true); return true; } return false; } /** Returns the layer of lowest Z coordinate where this ZDisplayable has a point in, or the creation layer if no points yet. */ public Layer getFirstLayer() { if (0 == n_points) return this.layer; if (-1 == n_points) setupForDisplay(); //reload Layer la = this.layer; double z = Double.MAX_VALUE; for (int i=0; i<n_points; i++) { Layer layer = layer_set.getLayer(p_layer[i]); if (layer.getZ() < z) la = layer; } return la; } /** Exports data. */ synchronized public void exportXML(StringBuffer sb_body, String indent, Object any) { sb_body.append(indent).append("<t2_polyline\n"); String in = indent + "\t"; super.exportXML(sb_body, in, any); if (-1 == n_points) setupForDisplay(); // reload //if (0 == n_points) return; String[] RGB = Utils.getHexRGBColor(color); sb_body.append(in).append("style=\"fill:none;stroke-opacity:").append(alpha).append(";stroke:#").append(RGB[0]).append(RGB[1]).append(RGB[2]).append(";stroke-width:1.0px;stroke-opacity:1.0\"\n"); if (n_points > 0) { sb_body.append(in).append("d=\"M"); for (int i=0; i<n_points-1; i++) { sb_body.append(" ").append(p[0][i]).append(",").append(p[1][i]).append(" L"); } sb_body.append(" ").append(p[0][n_points-1]).append(',').append(p[1][n_points-1]).append("\"\n"); sb_body.append(in).append("layer_ids=\""); // different from 'layer_id' in superclass for (int i=0; i<n_points; i++) { sb_body.append(p_layer[i]); if (n_points -1 != i) sb_body.append(","); } sb_body.append("\"\n"); } sb_body.append(indent).append(">\n"); super.restXML(sb_body, in, any); sb_body.append(indent).append("</t2_polyline>\n"); } /** Exports to type t2_polyline. */ static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) { String type = "t2_polyline"; if (hs.contains(type)) return; hs.add(type); sb_header.append(indent).append("<!ELEMENT t2_polyline (").append(Displayable.commonDTDChildren()).append(")>\n"); Displayable.exportDTD(type, sb_header, hs, indent); sb_header.append(indent).append(TAG_ATTR1).append(type).append(" d").append(TAG_ATTR2) ; } /** Performs a deep copy of this object, without the links. */ synchronized public Displayable clone(final Project pr, final boolean copy_id) { final long nid = copy_id ? this.id : pr.getLoader().getNextId(); final Polyline copy = new Polyline(pr, nid, null != title ? title.toString() : null, width, height, alpha, this.visible, new Color(color.getRed(), color.getGreen(), color.getBlue()), this.locked, (AffineTransform)this.at.clone()); // The data: if (-1 == n_points) setupForDisplay(); // load data copy.n_points = n_points; copy.p = new double[][]{(double[])this.p[0].clone(), (double[])this.p[1].clone()}; copy.p_layer = (long[])this.p_layer.clone(); copy.addToDatabase(); return copy; } /** Calibrated. */ synchronized public List generateTriangles(double scale, int parallels, int resample) { return generateTriangles(scale, parallels, resample, layer_set.getCalibrationCopy()); } /** Returns a list of Point3f that define a polyline in 3D, for usage with an ij3d CustomLineMesh CONTINUOUS. @param parallels is ignored. */ synchronized public List generateTriangles(final double scale, final int parallels, final int resample, final Calibration cal) { if (-1 == n_points) setupForDisplay(); if (0 == n_points) return null; // local pointers, since they may be transformed final int n_points; final double[][] p; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; } else { n_points = this.n_points; p = this.p; } final ArrayList list = new ArrayList(); final double KW = scale * cal.pixelWidth * resample; final double KH = scale * cal.pixelHeight * resample; for (int i=0; i<n_points; i++) { list.add(new Point3f((float) (p[0][i] * KW), (float) (p[1][i] * KH), (float) (layer_set.getLayer(p_layer[i]).getZ() * KW))); } if (n_points < 2) { // Duplicate first point list.add(list.get(0)); } return list; } synchronized private Object[] getTransformedData() { final int n_points = this.n_points; final double[][] p = transformPoints(this.p, n_points); return new Object[]{p}; } public boolean intersects(final Area area, final double z_first, final double z_last) { if (-1 == n_points) setupForDisplay(); for (int i=0; i<n_points; i++) { final double z = layer_set.getLayer(p_layer[i]).getZ(); if (z < z_first || z > z_last) continue; if (area.contains(p[0][i], p[1][i])) return true; } return false; } /** Returns a non-calibrated VectorString3D. */ synchronized public VectorString3D asVectorString3D() { // local pointers, since they may be transformed int n_points = this.n_points; double[][] p = this.p; if (!this.at.isIdentity()) { final Object[] ob = getTransformedData(); p = (double[][])ob[0]; n_points = p[0].length; } double[] z_values = new double[n_points]; for (int i=0; i<n_points; i++) { z_values[i] = layer_set.getLayer(p_layer[i]).getZ(); } final double[] px = p[0]; final double[] py = p[1]; final double[] pz = z_values; VectorString3D vs = null; try { vs = new VectorString3D(px, py, pz, false); } catch (Exception e) { IJError.print(e); } return vs; } public String getInfo() { if (-1 == n_points) setupForDisplay(); //reload // measure length double len = 0; if (n_points > 1) { VectorString3D vs = asVectorString3D(); vs.calibrate(this.layer_set.getCalibration()); len = vs.computeLength(); // no resampling } return new StringBuffer("Length: ").append(Utils.cutNumber(len, 2, true)).append(' ').append(this.layer_set.getCalibration().getUnits()).append('\n').toString(); } public ResultsTable measure(ResultsTable rt) { if (-1 == n_points) setupForDisplay(); //reload if (0 == n_points) return rt; if (null == rt) rt = Utils.createResultsTable("Polyline results", new String[]{"id", "length", "name-id"}); // measure length double len = 0; Calibration cal = layer_set.getCalibration(); if (n_points > 1) { VectorString3D vs = asVectorString3D(); vs.calibrate(cal); len = vs.computeLength(); // no resampling } rt.incrementCounter(); rt.addLabel("units", cal.getUnit()); rt.addValue(0, this.id); rt.addValue(1, len); rt.addValue(2, getNameId()); return rt; } /** Resample the curve to, first, a number of points as resulting from resampling to a point interdistance of delta, and second, as adjustment by random walk of those points towards the original points. */ static public Object[] simplify(final double[] px, final double[] py, final long[] p_layer_ids, /*final double delta, final double allowed_error_per_point,*/ final int max_iterations, final LayerSet layer_set) throws Exception { if (px.length != py.length || py.length != p_layer_ids.length) return null; final double[] pz = new double[px.length]; for (int i=0; i<pz.length; i++) { pz[i] = layer_set.getLayer(p_layer_ids[i]).getZ(); } /* // Resample: VectorString3D vs = new VectorString3D(px, py, pz, false); Calibration cal = layer_set.getCalibrationCopy(); vs.calibrate(cal); vs.resample(delta); cal.pixelWidth = 1 / cal.pixelWidth; cal.pixelHeight = 1 / cal.pixelHeight; vs.calibrate(cal); // undo it, since source points are in pixels Pth path = new Pth(vs.getPoints(0), vs.getPoints(1), vs.getPoints(2)); vs = null; // The above fails with strangely jagged lines. */ // Instead, just a line: Calibration cal = layer_set.getCalibrationCopy(); double one_unit = 1 / cal.pixelWidth; // in pixels double traced_length = M.distance(px[0], py[0], pz[0], px[px.length-1], py[py.length-1], pz[pz.length-1]); double segment_length = (one_unit * 5); int n_new_points = (int)(traced_length / segment_length) + 1; double[] rx = new double[n_new_points]; double[] ry = new double[n_new_points]; double[] rz = new double[n_new_points]; rx[0] = px[0]; rx[rx.length-1] = px[px.length-1]; ry[0] = py[0]; ry[ry.length-1] = py[py.length-1]; rz[0] = pz[0]; rz[rz.length-1] = pz[pz.length-1]; Vector3d v = new Vector3d(rx[n_new_points-1] - rx[0], ry[n_new_points-1] - ry[0], rz[n_new_points-1] - rz[0]); v.normalize(); v.scale(segment_length); for (int i=1; i<n_new_points-1; i++) { rx[i] = rx[0] + v.x * i; ry[i] = ry[0] + v.y * i; rz[i] = rz[0] + v.z * i; } Pth path = new Pth(rx, ry, rz); rx = ry = rz = null; //final double lowest_error = px.length * allowed_error_per_point; final double d = 1; final Random rand = new Random(System.currentTimeMillis()); double current_error = Double.MAX_VALUE; int i = 0; //double[] er = new double[max_iterations]; //double[] index = new double[max_iterations]; int missed_in_a_row = 0; for (; i<max_iterations; i++) { final Pth copy = path.copy().shakeUpOne(d, rand); double error = copy.measureErrorSq(px, py, pz); // If less error, keep the copy if (error < current_error) { current_error = error; path = copy; //er[i] = error; //index[i] = i; missed_in_a_row = 0; } else { //er[i] = current_error; //index[i] = i; missed_in_a_row++; if (missed_in_a_row > 10 * path.px.length) { Utils.log2("Stopped random walk at iteration " + i); break; } continue; } /* // If below lowest_error, quit searching if (current_error < lowest_error) { Utils.log2("Stopped at iteration " + i); break; } */ } /* Plot plot = new Plot("error", "iteration", "error", index, er); plot.setLineWidth(2); plot.show(); */ if (max_iterations == i) { Utils.log2("Reached max iterations -- current error: " + current_error); } // Approximate new Z to a layer id: long[] plids = new long[path.px.length]; plids[0] = p_layer_ids[0]; // first point untouched for (int k=1; k<path.pz.length; k++) { plids[k] = layer_set.getNearestLayer(path.pz[k]).getId(); } return new Object[]{path.px, path.py, plids}; } /** A path of points in 3D. */ static private class Pth { final double[] px, py, pz; Pth(double[] px, double[] py, double[] pz) { this.px = px; this.py = py; this.pz = pz; } /** Excludes first and last points. */ final Pth shakeUpOne(final double d, final Random rand) { final int i = rand.nextInt(px.length-1) + 1; px[i] += d * (rand.nextBoolean() ? 1 : -1); py[i] += d * (rand.nextBoolean() ? 1 : -1); pz[i] += d * (rand.nextBoolean() ? 1 : -1); return this; } final Pth copy() { return new Pth( Utils.copy(px, px.length), Utils.copy(py, py.length), Utils.copy(pz, pz.length) ); } /** Excludes first and last points. */ final double measureErrorSq(final double[] ox, final double[] oy, final double[] oz) { double error = 0; for (int i=1; i<ox.length -1; i++) { double min_dist = Double.MAX_VALUE; for (int j=1; j<px.length; j++) { // distance from a original point to a line defined by two consecutive new points double dist = M.distancePointToSegmentSq(ox[i], oy[i], oz[i], px[j-1], py[j-1], pz[j-1], px[j], py[j], pz[j]); if (dist < min_dist) min_dist = dist; } error += min_dist; } return error; } } public void setPosition(FallLine fl) { // Where are we now? } @Override final Class getInternalDataPackageClass() { return DPPolyline.class; } @Override synchronized Object getDataPackage() { return new DPPolyline(this); } static private final class DPPolyline extends Displayable.DataPackage { final double[][] p; final long[] p_layer; DPPolyline(final Polyline polyline) { super(polyline); // store copies of all arrays this.p = new double[][]{Utils.copy(polyline.p[0], polyline.n_points), Utils.copy(polyline.p[1], polyline.n_points)}; this.p_layer = new long[polyline.n_points]; System.arraycopy(polyline.p_layer, 0, this.p_layer, 0, polyline.n_points); } @Override final boolean to2(final Displayable d) { super.to1(d); final Polyline polyline = (Polyline)d; final int len = p[0].length; // == n_points, since it was cropped on copy polyline.p = new double[][]{Utils.copy(p[0], len), Utils.copy(p[1], len)}; polyline.n_points = p[0].length; polyline.p_layer = new long[len]; System.arraycopy(p_layer, 0, polyline.p_layer, 0, len); return true; } } /** Retain the data within the layer range, and through out all the rest. */ synchronized public boolean crop(List<Layer> range) { HashSet<Long> lids = new HashSet<Long>(); for (Layer l : range) { lids.add(l.getId()); } for (int i=0; i<n_points; i++) { if (!lids.contains(p_layer[i])) { removePoint(i); i--; } } calculateBoundingBox(true); return true; } /** Create a shorter Polyline, from start to end (inclusive); not added to the LayerSet. */ synchronized public Polyline sub(int start, int end) { Polyline sub = new Polyline(project, title); sub.n_points = end - start + 1; sub.p[0] = Utils.copy(this.p[0], start, sub.n_points); sub.p[1] = Utils.copy(this.p[1], start, sub.n_points); sub.p_layer = new long[sub.n_points]; System.arraycopy(this.p_layer, start, sub.p_layer, 0, sub.n_points); return sub; } synchronized public void reverse() { Utils.reverse(p[0]); Utils.reverse(p[1]); Utils.reverse(p_layer); } }
false
true
public void mousePressed(MouseEvent me, int x_p, int y_p, double mag) { // transform the x_p, y_p to the local coordinates int x_pd = x_p; int y_pd = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_p = (int)po.x; y_p = (int)po.y; } final int tool = ProjectToolbar.getToolId(); final Display display = ((DisplayCanvas)me.getSource()).getDisplay(); final long layer_id = display.getLayer().getId(); index = findPoint(x_p, y_p, layer_id, mag); if (ProjectToolbar.PENCIL == tool && n_points > 0 && -1 == index && !me.isShiftDown() && !Utils.isControlDown(me)) { // Use Mark Longair's tracing: from the clicked point to the last one final double scale = layer_set.getVirtualizationScale(); // Ok now with all found images, create a virtual stack that provides access to them all, with caching. final Worker[] worker = new Worker[2]; TraceParameters tr_ = tr_map.get(layer_set); final TraceParameters tr = null == tr_ ? new TraceParameters() : tr_; if (null == tr_) { synchronized (tr_map) { tr_map.put(layer_set, tr); } } if (tr.update) { worker[0] = new Worker("Preparing Hessian...") { public void run() { startedWorking(); try { Utils.log("Push ESCAPE key to cancel autotrace anytime."); ImagePlus virtual = new LayerStack(layer_set, scale, ImagePlus.GRAY8, Patch.class, display.getDisplayChannelAlphas()).getImagePlus(); //virtual.show(); Calibration cal = virtual.getCalibration(); double minimumSeparation = 1; if (cal != null) minimumSeparation = Math.min(cal.pixelWidth, Math.min(cal.pixelHeight, cal.pixelDepth)); ComputeCurvatures hessian = new ComputeCurvatures(virtual, minimumSeparation, null, cal != null); hessian.run(); tr.virtual = virtual; tr.scale = scale; tr.hessian = hessian; tr.update = false; } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[0], project); } Point2D.Double po = transformPoint(p[0][n_points-1], p[1][n_points-1]); final int start_x = (int)po.x; final int start_y = (int)po.y; final int start_z = layer_set.indexOf(layer_set.getLayer(p_layer[n_points-1])); // 0-based final int goal_x = (int)(x_pd * scale); // must transform into virtual space final int goal_y = (int)(y_pd * scale); final int goal_z = layer_set.indexOf(display.getLayer()); /* Utils.log2("x_pd, y_pd : " + x_pd + ", " + y_pd); Utils.log2("scale: " + scale); Utils.log2("start: " + start_x + "," + start_y + ", " + start_z); Utils.log2("goal: " + goal_x + "," + goal_y + ", " + goal_z); Utils.log2("virtual: " + tr.virtual); */ final boolean simplify = me.isAltDown(); worker[1] = new Worker("Tracer - waiting on hessian") { public void run() { startedWorking(); try { if (null != worker[0]) { // Wait until hessian is ready worker[0].join(); } setTaskName("Tracing path"); final int reportEveryMilliseconds = 2000; tr.tracer = new TracerThread(tr.virtual, 0, 255, 120, // timeout seconds reportEveryMilliseconds, start_x, start_y, start_z, goal_x, goal_y, goal_z, true, // reciproal pix values at start and goal tr.virtual.getStackSize() == 1, tr.hessian, null == tr.hessian ? 1 : 4, null, null != tr.hessian); tr.tracer.addProgressListener(new SearchProgressCallback() { public void pointsInSearch(SearchThread source, int inOpen, int inClosed) { worker[1].setTaskName("Tracing path: open=" + inOpen + " closed=" + inClosed); } public void finished(SearchThread source, boolean success) { if (!success) { Utils.logAll("Could NOT trace a path"); } } public void threadStatus(SearchThread source, int currentStatus) { // This method gets called every reportEveryMilliseconds if (worker[1].hasQuitted()) { source.requestStop(); } } }); tr.tracer.run(); final Path result = tr.tracer.getResult(); tr.tracer = null; if (null == result) { Utils.log("Finding a path failed"); //: "+ // not public //SearchThread.exitReasonStrings[tracer.getExitReason()]); return; } // TODO: precise_x_positions etc are likely to be broken (calibrated or something) // Remove bogus points: those at the end with 0,0 coords int len = result.points; final double[][] pos = result.getXYZUnscaled(); for (int i=len-1; i>-1; i--) { if (0 == pos[0][i] && 0 == pos[1][i]) { len--; } else break; } // Transform points: undo scale, and bring to this Polyline AffineTransform: final AffineTransform aff = new AffineTransform(); /* Inverse order: */ /* 2 */ aff.concatenate(Polyline.this.at.createInverse()); /* 1 */ aff.scale(1/scale, 1/scale); final double[] po = new double[len * 2]; for (int i=0, j=0; i<len; i++, j+=2) { po[j] = pos[0][i]; po[j+1] = pos[1][i]; } final double[] po2 = new double[len * 2]; aff.transform(po, 0, po2, 0, len); // what a stupid format: consecutive x,y pairs long[] p_layer_ids = new long[len]; double[] pox = new double[len]; double[] poy = new double[len]; for (int i=0, j=0; i<len; i++, j+=2) { p_layer_ids[i] = layer_set.getNearestLayer(pos[2][i]).getId(); // z_positions in 0-(N-1), not in 0-N like slices! pox[i] = po2[j]; poy[i] = po2[j+1]; } // Simplify path: to steps of 5 calibration units, or 5 pixels when not calibrated. if (simplify) { Object[] ob = Polyline.simplify(pox, poy, p_layer_ids, 10000, layer_set); pox = (double[])ob[0]; poy = (double[])ob[1]; p_layer_ids = (long[])ob[2]; len = pox.length; } // Record the first newly-added autotraced point index: last_autotrace_start = Polyline.this.n_points; Polyline.this.appendPoints(pox, poy, p_layer_ids, len); Polyline.this.repaint(true); Utils.logAll("Added " + len + " new points."); } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[1], project); index = -1; return; } if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { if (Utils.isControlDown(me) && me.isShiftDown()) { final long lid = Display.getFrontLayer(this.project).getId(); if (-1 == index || lid != p_layer[index]) { index = findNearestPoint(x_p, y_p, layer_id); } if (-1 != index) { //delete point removePoint(index); index = -1; repaint(false); } // In any case, terminate return; } if (-1 != index && layer_id != p_layer[index]) index = -1; // disable! //if no conditions are met, attempt to add point else if (-1 == index && !me.isShiftDown() && !me.isAltDown()) { //add a new point index = addPoint(x_p, y_p, layer_id, mag); is_new_point = true; repaint(false); return; } } }
public void mousePressed(MouseEvent me, int x_p, int y_p, double mag) { // transform the x_p, y_p to the local coordinates int x_pd = x_p; int y_pd = y_p; if (!this.at.isIdentity()) { final Point2D.Double po = inverseTransformPoint(x_p, y_p); x_p = (int)po.x; y_p = (int)po.y; } final int tool = ProjectToolbar.getToolId(); final Display display = ((DisplayCanvas)me.getSource()).getDisplay(); final long layer_id = display.getLayer().getId(); index = findPoint(x_p, y_p, layer_id, mag); if (ProjectToolbar.PENCIL == tool && n_points > 0 && -1 == index && !me.isShiftDown() && !Utils.isControlDown(me)) { // Use Mark Longair's tracing: from the clicked point to the last one final double scale = layer_set.getVirtualizationScale(); // Ok now with all found images, create a virtual stack that provides access to them all, with caching. final Worker[] worker = new Worker[2]; TraceParameters tr_ = tr_map.get(layer_set); final TraceParameters tr = null == tr_ ? new TraceParameters() : tr_; if (null == tr_) { synchronized (tr_map) { tr_map.put(layer_set, tr); } } if (tr.update) { worker[0] = new Worker("Preparing Hessian...") { public void run() { startedWorking(); try { Utils.log("Push ESCAPE key to cancel autotrace anytime."); ImagePlus virtual = new LayerStack(layer_set, scale, ImagePlus.GRAY8, Patch.class, display.getDisplayChannelAlphas()).getImagePlus(); //virtual.show(); Calibration cal = virtual.getCalibration(); double minimumSeparation = 1; if (cal != null) minimumSeparation = Math.min(cal.pixelWidth, Math.min(cal.pixelHeight, cal.pixelDepth)); ComputeCurvatures hessian = new ComputeCurvatures(virtual, minimumSeparation, null, cal != null); hessian.run(); tr.virtual = virtual; tr.scale = scale; tr.hessian = hessian; tr.update = false; } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[0], project); } Point2D.Double po = transformPoint(p[0][n_points-1], p[1][n_points-1]); final int start_x = (int)po.x; final int start_y = (int)po.y; final int start_z = layer_set.indexOf(layer_set.getLayer(p_layer[n_points-1])); // 0-based final int goal_x = (int)(x_pd * scale); // must transform into virtual space final int goal_y = (int)(y_pd * scale); final int goal_z = layer_set.indexOf(display.getLayer()); /* Utils.log2("x_pd, y_pd : " + x_pd + ", " + y_pd); Utils.log2("scale: " + scale); Utils.log2("start: " + start_x + "," + start_y + ", " + start_z); Utils.log2("goal: " + goal_x + "," + goal_y + ", " + goal_z); Utils.log2("virtual: " + tr.virtual); */ final boolean simplify = me.isAltDown(); worker[1] = new Worker("Tracer - waiting on hessian") { public void run() { startedWorking(); try { if (null != worker[0]) { // Wait until hessian is ready worker[0].join(); } setTaskName("Tracing path"); final int reportEveryMilliseconds = 2000; tr.tracer = new TracerThread(tr.virtual, 0, 255, 120, // timeout seconds reportEveryMilliseconds, start_x, start_y, start_z, goal_x, goal_y, goal_z, true, // reciproal pix values at start and goal tr.virtual.getStackSize() == 1, tr.hessian, null == tr.hessian ? 1 : 4, null, null != tr.hessian); tr.tracer.addProgressListener(new SearchProgressCallback() { public void pointsInSearch(SearchThread source, int inOpen, int inClosed) { worker[1].setTaskName("Tracing path: open=" + inOpen + " closed=" + inClosed); } public void finished(SearchThread source, boolean success) { if (!success) { Utils.logAll("Could NOT trace a path"); } } public void threadStatus(SearchThread source, int currentStatus) { // This method gets called every reportEveryMilliseconds if (worker[1].hasQuitted()) { source.requestStop(); } } }); tr.tracer.run(); final Path result = tr.tracer.getResult(); tr.tracer = null; if (null == result) { Utils.log("Finding a path failed"); //: "+ // not public //SearchThread.exitReasonStrings[tracer.getExitReason()]); return; } // TODO: precise_x_positions etc are likely to be broken (calibrated or something) // Remove bogus points: those at the end with 0,0 coords int len = result.points; final double[][] pos = result.getXYZUnscaled(); for (int i=len-1; i>-1; i--) { if (0 == pos[0][i] && 0 == pos[1][i]) { len--; } else break; } // Transform points: undo scale, and bring to this Polyline AffineTransform: final AffineTransform aff = new AffineTransform(); /* Inverse order: */ /* 2 */ aff.concatenate(Polyline.this.at.createInverse()); /* 1 */ aff.scale(1/scale, 1/scale); final double[] po = new double[len * 2]; for (int i=0, j=0; i<len; i++, j+=2) { po[j] = pos[0][i]; po[j+1] = pos[1][i]; } final double[] po2 = new double[len * 2]; aff.transform(po, 0, po2, 0, len); // what a stupid format: consecutive x,y pairs long[] p_layer_ids = new long[len]; double[] pox = new double[len]; double[] poy = new double[len]; for (int i=0, j=0; i<len; i++, j+=2) { p_layer_ids[i] = layer_set.getLayer((int)pos[2][i]).getId(); // z_positions in 0-(N-1), not in 1-N like slices! pox[i] = po2[j]; poy[i] = po2[j+1]; } // Simplify path: to steps of 5 calibration units, or 5 pixels when not calibrated. if (simplify) { setTaskName("Simplifying path"); Object[] ob = Polyline.simplify(pox, poy, p_layer_ids, 10000, layer_set); pox = (double[])ob[0]; poy = (double[])ob[1]; p_layer_ids = (long[])ob[2]; len = pox.length; } // Record the first newly-added autotraced point index: last_autotrace_start = Polyline.this.n_points; Polyline.this.appendPoints(pox, poy, p_layer_ids, len); Polyline.this.repaint(true); Utils.logAll("Added " + len + " new points."); } catch (Exception e) { IJError.print(e); } finishedWorking(); }}; Bureaucrat.createAndStart(worker[1], project); index = -1; return; } if (ProjectToolbar.PEN == tool || ProjectToolbar.PENCIL == tool) { if (Utils.isControlDown(me) && me.isShiftDown()) { final long lid = Display.getFrontLayer(this.project).getId(); if (-1 == index || lid != p_layer[index]) { index = findNearestPoint(x_p, y_p, layer_id); } if (-1 != index) { //delete point removePoint(index); index = -1; repaint(false); } // In any case, terminate return; } if (-1 != index && layer_id != p_layer[index]) index = -1; // disable! //if no conditions are met, attempt to add point else if (-1 == index && !me.isShiftDown() && !me.isAltDown()) { //add a new point index = addPoint(x_p, y_p, layer_id, mag); is_new_point = true; repaint(false); return; } } }
diff --git a/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiAuthenticationProcessingFilterEntryPoint.java b/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiAuthenticationProcessingFilterEntryPoint.java index bf77ba12..dc5730ab 100644 --- a/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiAuthenticationProcessingFilterEntryPoint.java +++ b/jamwiki-web/src/main/java/org/jamwiki/authentication/JAMWikiAuthenticationProcessingFilterEntryPoint.java @@ -1,54 +1,47 @@ /** * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999. * * This program is free software; you can redistribute it and/or modify * it under the terms of the latest version 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 program (LICENSE.txt); if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.jamwiki.authentication; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.AuthenticationException; import org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint; import org.jamwiki.utils.WikiLogger; import org.jamwiki.utils.WikiUtil; /** * This class is a hack implemented to work around the fact that the default * Spring Security classes can only redirect to a single, hard-coded URL. Due to the * fact that JAMWiki may have multiple virtual wikis this class overrides some * of the default Spring Security behavior to allow additional flexibility. Hopefully * future versions of Spring Security will add additional flexibility and this class * can be removed. */ public class JAMWikiAuthenticationProcessingFilterEntryPoint extends AuthenticationProcessingFilterEntryPoint { /** Standard logger. */ private static final WikiLogger logger = WikiLogger.getLogger(JAMWikiAuthenticationProcessingFilterEntryPoint.class.getName()); /** * Return the URL to redirect to in case of a login being required. This method * uses the configured login URL and prepends the virtual wiki. */ protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { - String uri = request.getRequestURI(); - // FIXME - move the "strip after semicolon" code to WikiUtil - int pathParamIndex = uri.indexOf(';'); - if (pathParamIndex > 0) { - // strip everything after the first semi-colon - uri = uri.substring(0, pathParamIndex); - } String virtualWiki = WikiUtil.getVirtualWikiFromURI(request); return "/" + virtualWiki + this.getLoginFormUrl(); } }
true
true
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String uri = request.getRequestURI(); // FIXME - move the "strip after semicolon" code to WikiUtil int pathParamIndex = uri.indexOf(';'); if (pathParamIndex > 0) { // strip everything after the first semi-colon uri = uri.substring(0, pathParamIndex); } String virtualWiki = WikiUtil.getVirtualWikiFromURI(request); return "/" + virtualWiki + this.getLoginFormUrl(); }
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) { String virtualWiki = WikiUtil.getVirtualWikiFromURI(request); return "/" + virtualWiki + this.getLoginFormUrl(); }
diff --git a/src-tools/org/seasr/meandre/components/tools/webservice/GetResponseContentType.java b/src-tools/org/seasr/meandre/components/tools/webservice/GetResponseContentType.java index da08b91c..2aee8b65 100644 --- a/src-tools/org/seasr/meandre/components/tools/webservice/GetResponseContentType.java +++ b/src-tools/org/seasr/meandre/components/tools/webservice/GetResponseContentType.java @@ -1,158 +1,159 @@ /** * University of Illinois/NCSA * Open Source License * * Copyright (c) 2008, Board of Trustees-University of Illinois. * All rights reserved. * * Developed by: * * Automated Learning Group * National Center for Supercomputing Applications * http://www.seasr.org * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal with 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: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimers. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * * * Neither the names of Automated Learning Group, The National Center for * Supercomputing Applications, or University of Illinois, nor the names of * its contributors may be used to endorse or promote products derived from * this Software without specific prior written permission. * * 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 * CONTRIBUTORS 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 * WITH THE SOFTWARE. */ package org.seasr.meandre.components.tools.webservice; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.meandre.annotations.Component; import org.meandre.annotations.Component.Licenses; import org.meandre.annotations.ComponentInput; import org.meandre.annotations.ComponentOutput; import org.meandre.annotations.ComponentProperty; import org.meandre.core.ComponentContext; import org.meandre.core.ComponentContextProperties; import org.seasr.datatypes.core.BasicDataTypesTools; import org.seasr.meandre.components.abstracts.AbstractExecutableComponent; import com.google.gdata.util.ContentType; /** * @author Boris Capitanu */ @Component( creator = "Boris Capitanu", description = "Returns the best content type, as specified in the 'Accept' header, based on the specified supported content types. " + "If the request does not supply an Accept header value, then the first content type specified in the 'supported_types' " + "property will be returned.", name = "Get Response Content Type", tags = "webservice, header, content type, accept", rights = Licenses.UofINCSA, baseURL = "meandre://seasr.org/components/foundry/", dependency = {"protobuf-java-2.2.0.jar"} ) public class GetResponseContentType extends AbstractExecutableComponent { //------------------------------ INPUTS ------------------------------------------------------ @ComponentInput( name = "request_handler", description = "The request object." + "<br>TYPE: javax.servlet.http.HttpServletRequest" ) protected static final String IN_REQUEST = "request_handler"; //------------------------------ OUTPUTS ----------------------------------------------------- @ComponentOutput( name = "content_type", description = "The best content type" + "<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings" ) protected static final String OUT_CONTENT_TYPE = "content_type"; @ComponentOutput( name = "request_handler", description = "Same as input." ) protected static final String OUT_REQUEST = "request_handler"; //------------------------------ PROPERTIES --------------------------------------------------- @ComponentProperty ( description = "The comma-separated list of supported content types in descending order of preference " + "(non-empty, and each entry is of the form type/subtype without the wildcard char '*')", name = "supported_types", defaultValue = "" ) protected static final String PROP_SUPPORTED_TYPES = "supported_types"; @ComponentProperty ( description = "Should the charset from request be included?", name = "include_request_charset", defaultValue = "true" ) protected static final String PROP_INCLUDE_REQUEST_CHARSET = "include_request_charset"; //-------------------------------------------------------------------------------------------- protected List<ContentType> _supportedTypes; protected boolean _appendCharset; //-------------------------------------------------------------------------------------------- @Override public void initializeCallBack(ComponentContextProperties ccp) throws Exception { String supportedTypes[] = getPropertyOrDieTrying(PROP_SUPPORTED_TYPES, ccp).split(","); _supportedTypes = new ArrayList<ContentType>(supportedTypes.length); for (String type : supportedTypes) _supportedTypes.add(new ContentType(type.trim())); _appendCharset = Boolean.parseBoolean(getPropertyOrDieTrying(PROP_INCLUDE_REQUEST_CHARSET, ccp)); } @Override public void executeCallBack(ComponentContext cc) throws Exception { HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST); String accept = request.getHeader("Accept"); ContentType bestType = accept.length() > 0 ? ContentType.getBestContentType(accept, _supportedTypes) : _supportedTypes.get(0); String encoding = request.getCharacterEncoding(); - String contentType = _appendCharset ? String.format("%s; charset=%s", bestType.toString(), encoding) : bestType.toString(); + String contentType = (_appendCharset && encoding != null) ? + String.format("%s; charset=%s", bestType.toString(), encoding) : bestType.toString(); console.fine("Best content type: " + contentType); cc.pushDataComponentToOutput(OUT_CONTENT_TYPE, BasicDataTypesTools.stringToStrings(contentType)); cc.pushDataComponentToOutput(OUT_REQUEST, request); } @Override public void disposeCallBack(ComponentContextProperties ccp) throws Exception { _supportedTypes.clear(); _supportedTypes = null; } }
true
true
public void executeCallBack(ComponentContext cc) throws Exception { HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST); String accept = request.getHeader("Accept"); ContentType bestType = accept.length() > 0 ? ContentType.getBestContentType(accept, _supportedTypes) : _supportedTypes.get(0); String encoding = request.getCharacterEncoding(); String contentType = _appendCharset ? String.format("%s; charset=%s", bestType.toString(), encoding) : bestType.toString(); console.fine("Best content type: " + contentType); cc.pushDataComponentToOutput(OUT_CONTENT_TYPE, BasicDataTypesTools.stringToStrings(contentType)); cc.pushDataComponentToOutput(OUT_REQUEST, request); }
public void executeCallBack(ComponentContext cc) throws Exception { HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST); String accept = request.getHeader("Accept"); ContentType bestType = accept.length() > 0 ? ContentType.getBestContentType(accept, _supportedTypes) : _supportedTypes.get(0); String encoding = request.getCharacterEncoding(); String contentType = (_appendCharset && encoding != null) ? String.format("%s; charset=%s", bestType.toString(), encoding) : bestType.toString(); console.fine("Best content type: " + contentType); cc.pushDataComponentToOutput(OUT_CONTENT_TYPE, BasicDataTypesTools.stringToStrings(contentType)); cc.pushDataComponentToOutput(OUT_REQUEST, request); }
diff --git a/trunk/src/om/devservlet/DevServlet.java b/trunk/src/om/devservlet/DevServlet.java index df23281..384a270 100644 --- a/trunk/src/om/devservlet/DevServlet.java +++ b/trunk/src/om/devservlet/DevServlet.java @@ -1,759 +1,759 @@ /* OpenMark online assessment system Copyright (C) 2007 The Open University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package om.devservlet; import java.awt.GraphicsEnvironment; import java.io.*; import java.net.URLEncoder; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.*; import om.OmException; import om.OmVersion; import om.question.*; import om.stdquestion.StandardQuestion; import org.w3c.dom.Document; import org.w3c.dom.Element; import util.misc.*; import util.xml.XHTML; import util.xml.XML; /** * Servlet used to build and test questions on a developer machine. Not suitable * for any production or public demonstration use. Only supports one instance * of one question at a time. */ public class DevServlet extends HttpServlet { /** Constant for specifying the number of text boxes for typing package names in the interface. */ private final static int NUM_EXTRA_PACKAGE_SLOTS = 3; /** Number of times the question is started, to check that it is using the random seed correctly. */ private final static int NUM_REPEAT_INITS = 2; /** In-progress question (null if none) */ private Question qInProgress=null; /** Classloader for in-progress question */ private ClosableClassLoader cclInProgress=null; /** ID of in-progress question */ private String sInProgressID=null; /** Whether the in-progress question has sent back results. */ private boolean questionHasSentResults; /** Map of String (filename) -> Resource */ private Map<String,Resource> mResources=new HashMap<String,Resource>(); /** CSS */ private String sCSS=null; /** List of question definitions */ private QuestionDefinitions qdQuestions; /** Clear/reset question data */ private void resetQuestion() { // Get rid of question and (hopefully) clear its classloader if(qInProgress!=null) { try { qInProgress.close(); } catch(Throwable t) { // Ignore errors on close } mResources.clear(); // Not all questions are laoded using ClosableClassLoaders; some are. // This needs more examination to figure it out. cclInProgress.close(); cclInProgress=null; qInProgress=null; sInProgressID=null; sCSS=null; } questionHasSentResults = false; } @Override public void init() throws ServletException { try { System.setProperty("java.awt.headless", "true"); } catch(Throwable t) { } if(!GraphicsEnvironment.isHeadless()) { throw new ServletException("Your application server must be set to run in " + "headless mode. Add the following option to the Java command line that " + "launches it: -Djava.awt.headless=true"); } try { qdQuestions=new QuestionDefinitions(getServletContext()); } catch(OmException oe) { throw new ServletException(oe); } } @Override protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { handle(false,request,response); } @Override protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { handle(true,request,response); } private void sendError(HttpServletRequest request,HttpServletResponse response, int iCode, String sTitle, String sMessage, Throwable tException) { try { response.setStatus(iCode); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); pw.println( "<html>" + "<head><title>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</title></head>"+ "<body>" + "<h1>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</h1>" + "<p>"+XHTML.escape(sMessage,XHTML.ESCAPE_TEXT)+"</p>" + "<p>" + ( (sInProgressID!=null && request.getPathInfo().equals("/run/"+sInProgressID+"/")) ? "<a href='./'>[Restart]</a> <a href='../../build/"+sInProgressID+"/'>[Rebuild]</a> " : "")+ "<a href='../../'>[List]</a> "+ "</p>"+ (tException!=null ? "<pre>"+XHTML.escape(Exceptions.getString( tException,new String[]{"om"}),XHTML.ESCAPE_TEXT)+"</pre>": "")+ "</body>" + "</html>"); pw.close(); } catch(IOException ioe) { // Ignore exception, they must have closed browser or something } } private void handleFront(boolean bPost,HttpServletRequest request,HttpServletResponse response) throws Exception { if(bPost) { String extraPackages = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { String extraPackage = request.getParameter("extra" + i).trim(); if (extraPackage.length()>0) { extraPackages += " <includepackage>"+extraPackage+"</includepackage>\n"; } } File fNew=new File( qdQuestions.getQuestionsFolder(),request.getParameter("package")+".xml"); Writer w=new OutputStreamWriter(new FileOutputStream(fNew),"UTF-8"); w.write( "<questiondefinition>\n" + " <sourcetree>"+request.getParameter("source")+"</sourcetree>\n" + " <package>"+request.getParameter("package")+"</package>\n" + extraPackages + "</questiondefinition>\n"); w.close(); response.sendRedirect("."); } QuestionDefinition[] aqd=qdQuestions.getQuestionDefinitions(); String extraPackagesHtml = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { extraPackagesHtml += "<input type='text' name='extra" + i + "' size='65' value='" + ((aqd.length>0 && aqd[aqd.length-1].getAdditionalPackageRoots().length>i) ? aqd[aqd.length-1].getAdditionalPackageRoots()[i] : "") + "'/><br />"; } // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>OpenMark-S (Om) question development</title>"+ "<style type='text/css'>\n"+ "body { font: 12px Verdana, sans-serif; }\n" + "h1 { font: bold 14px Verdana, sans-serif; }\n" + "a { color: black; }\n" + "h2 { font: 14px Verdana, sans-serif; }\n" + "#create,#questionbox { margin-bottom:20px; border:1px solid #888; padding:10px; }\n"+ "#create span { float:left; width:20em; margin-top: 5px }\n" + "#create span.fields { width:auto; }\n" + "#create div { clear:left; }\n"+ "</style>"+ "</head>"+ "<body>"+ "<h1>" + " OpenMark-S (Om) question development ("+OmVersion.getVersion()+")" + "</h1>" + "<div id='questionbox'>" + "<h2>Defined questions</h2>"+ "<ul id='questions'>"+ "</ul>"+ "</div>" + "<form id='create' method='post' action='.'>" + "<h2>Create new question</h2>" + "<div><span>Package</span><span class='fields'><input type='text' name='package' size='65' value='"+ ((aqd.length>0) ? aqd[aqd.length-1].getPackage().replaceAll("\\.[^.]$",".") : "")+ "'/></span></div>"+ "<div><span>Source tree</span><span class='fields'><input type='text' name='source' size='65' value='" + ((aqd.length>0) ? aqd[aqd.length-1].getSourceFolder().getAbsolutePath() : "")+ "'/></span></div>"+ "<div><span>Extra package (optional)</span><span class='fields'>" + extraPackagesHtml + "</span></div>"+ "<div><input type='submit' name='action' id='submit' value='Create'/></div>"+ "<p>This creates a new question definition file (.xml) in the questions " + "folder of your Om webapp.</p>"+ "</form>"+ "</body>"+ "</xhtml>"); // Find the root element and chuck in a line for each question Element eParent=XML.find(d,"id","questions"); for(int iQuestion=0;iQuestion<aqd.length;iQuestion++) { String encodedName = URLEncoder.encode(aqd[iQuestion].getID(), "UTF-8"); Element eQ=XML.createChild(eParent,"li"); XML.createText(eQ," "+aqd[iQuestion].getID()+" "); if(aqd[iQuestion].hasJar()) { Element eRun=XML.createChild(eQ,"a"); eRun.setAttribute("href","run/"+encodedName+"/"); XML.createText(eRun,"(Run)"); XML.createText(eQ," "); } Element eBuild=XML.createChild(eQ,"a"); eBuild.setAttribute("href","build/"+encodedName+"/"); XML.createText(eBuild,"(Build)"); XML.createText(eQ," "); Element eRemove=XML.createChild(eQ,"a"); eRemove.setAttribute("href","remove/"+encodedName+"/"); XML.createText(eRemove,"(Remove)"); } XHTML.output(d,request,response,"en"); } private void handleBuild(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { resetQuestion(); String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); boolean bSuccess=qdQuestions.getQuestionDefinition(sQuestion).build(pw); if(bSuccess) { pw.println( "<script type='text/javascript'>\n" + "var re=/^(.*)\\/build\\/(.*)$/;\n"+ "location.href=location.href.replace(re,'$1/run/$2');\n" + "</script>"); } else { pw.println( "<p><a href='javascript:location.reload()'>Rebuild</a></p>"); } pw.println("</body></html>"); pw.close(); } private void handleRemove(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } PrintWriter pw = response.getWriter(); File toRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".xml"); if (toRemove.exists()) { if (!toRemove.delete()) { pw.println("Could not remove the XML file."); } File jarToRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".jar"); if (jarToRemove.exists()) { if (!jarToRemove.delete()) { pw.println("Could not remove the jar file."); } } } else { pw.println("Unknown question."); } response.sendRedirect(".."); } private InitParams ipInProgress; private void handleRun(boolean bPost,String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); // Must access page with / at end if("".equals(sAfter) && !request.getRequestURI().endsWith("/")) { response.sendRedirect(request.getRequestURI()+"/"); return; } if("save".equals(request.getQueryString())) { // Delete existing saved files File fSave=new File(getServletContext().getRealPath("save")); if(!fSave.exists()) fSave.mkdir(); File[] afExisting=IO.listFiles(fSave); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } File fResources=new File(fSave,"resources"); if(!fResources.exists()) fResources.mkdir(); afExisting=IO.listFiles(fResources); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } // Save last xhtml FileOutputStream fos=new FileOutputStream(new File(fSave,"question.html")); fos.write(sLastXHTML.getBytes("UTF-8")); fos.close(); // Save CSS if(sCSS!=null) { fos=new FileOutputStream(new File(fSave,"style.css")); fos.write(sCSS.getBytes("UTF-8")); fos.close(); } // Save resources for(Map.Entry<String,Resource> me : mResources.entrySet()) { fos=new FileOutputStream(new File(fResources, me.getKey())); fos.write(me.getValue().getContent()); fos.close(); } response.setContentType("text/plain"); PrintWriter pw=response.getWriter(); pw.println( "OK, saved a local copy in 'save' folder within webapp.\n\n" + "Existing contents are cleared when you do that, so don't keep anything there!"); pw.close(); return; } // Different question if(!bPost) { int iVariant=-1; long randomSeed = System.currentTimeMillis(); if(sAfter.startsWith("v")) { iVariant=Integer.parseInt(sAfter.substring(1)); sAfter=""; } if(sAfter.startsWith("rs")) { randomSeed = Long.parseLong(sAfter.substring(2)); sAfter=""; } if(sAfter.equals("")) { resetQuestion(); QuestionDefinition qd=qdQuestions.getQuestionDefinition(sQuestion); QuestionDefinition.RunReturn rr=qd.run(); qInProgress=rr.q; cclInProgress=rr.ccl; sInProgressID=sQuestion; String sAccess=request.getParameter("access"); boolean bPlain="plain".equals(sAccess); double dZoom="big".equals(sAccess) ? 2.0 : 1.0; String sFG="bw".equals(sAccess) ? "#00ff00" : null; String sBG="bw".equals(sAccess) ? "#000000" : null; ipInProgress=new InitParams(randomSeed, sFG,sBG,dZoom,bPlain,cclInProgress,iVariant); Rendering r=qInProgress.init(rr.dMeta,ipInProgress); // Try starting the question a few times, and ensure we get the same result each time. String xHTML = XML.saveString(r.getXHTML()); for (int i = 0; i < NUM_REPEAT_INITS; i++) { Question qCopy = qInProgress.getClass().newInstance(); String newXHTML = XML.saveString(qCopy.init(rr.dMeta,ipInProgress).getXHTML()); if (!xHTML.equals(newXHTML)) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = new PrintWriter(response.getWriter()); pw.println("<html><head><title>Error starting question</title></head><body>"); pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: " + "Starting the question twice with the same random seed produced " + "different results. This means there is a bug in your question.</div>"); pw.println("<p><a href='../../build/" + sQuestion + "/'>Rebuild</a></p>"); - pw.println("<h2>First verions of the question HTML</h2><pre>"); + pw.println("<h2>First version of the question HTML</h2><pre>"); pw.println(XHTML.escape(xHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre><h2>Repeat version of the question HTML</h2><pre>"); pw.println(XHTML.escape(newXHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre>"); pw.println("</body></html>"); pw.close(); return; } } // Add resources Resource[] arResources=r.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style sCSS=r.getCSS(); // Serve XHTML serveXHTML(sQuestion,r,request,response,qInProgress); } else if(sCSS!=null && sAfter.equals("style.css")) { response.setContentType("text/css"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(sCSS); response.getWriter().close(); } else if(sAfter.startsWith("resources/")) { Resource r=mResources.get(sAfter.substring("resources/".length())); if(r==null) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Requested resource not found: "+sRemainingPath, null); } response.setContentType(r.getMimeType()); response.setContentLength(r.getContent().length); if(r.getEncoding()!=null) response.setCharacterEncoding(r.getEncoding()); response.getOutputStream().write(r.getContent()); response.getOutputStream().close(); } else { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } } else { if(!sQuestion.equals(sInProgressID)) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot change to a different question mid-question (the " + "developer servlet supports only a single session at a time, " + "so don't open multiple browser windows).", null); return; } if(sAfter.length()>0) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot POST to any URL other than the question.", null); return; } ActionParams ap=new ActionParams(); for(Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) { String sName = (String)e.nextElement(); ap.setParameter(sName,request.getParameter(sName)); } if(ipInProgress.isPlainMode()) ap.setParameter("plain","yes"); ActionRendering ar=qInProgress.action(ap); if(ar.isSessionEnd()) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=new PrintWriter(response.getWriter()); pw.println("<html><head><title>Question ended</title></head><body>"); if (!questionHasSentResults) { pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: The question ended without sending back any results.</div>"); pw.println("<p><a href='./'>Restart</a></p>"); } else { pw.println("<p>Question ended. <a href='./'>Restart</a></p>"); } pw.println("</body></html>"); pw.close(); } else { // Add resources Resource[] arResources=ar.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style if(ar.getCSS()!=null) sCSS=ar.getCSS(); // Serve XHTML serveXHTML(sQuestion,ar,request,response,qInProgress); } } } byte[] abTempCSS=null; private void handle(boolean bPost, HttpServletRequest request,HttpServletResponse response) { try { // Vitally important, otherwise any input with unicode gets screwed up request.setCharacterEncoding("UTF-8"); String sPath=request.getPathInfo(); if(sPath==null || sPath.equals("") || sPath.equals("/")) { // Must access page with / at end if(request.getRequestURI().endsWith("/")) { handleFront(bPost,request,response); } else { response.sendRedirect(request.getRequestURI()+"/"); return; } } else if(sPath.startsWith("/build/")) handleBuild(sPath.substring("/build/".length()),request,response); else if(sPath.startsWith("/run/")) handleRun(bPost,sPath.substring("/run/".length()),request,response); else if(sPath.startsWith("/remove/")) handleRemove(sPath.substring("/remove/".length()),request,response); else { sendError(request,response,HttpServletResponse.SC_NOT_FOUND, "Not found","The URL you requested is not provided by this server.", null); } } catch(Throwable t) { sendError(request,response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Error handling request","An exception occurred.", t); } } /** Remember last xhtml sent so we can save it */ private String sLastXHTML; private void serveXHTML(String sQuestion,Rendering r, HttpServletRequest request,HttpServletResponse response,Question q) throws IOException { // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>Question: "+sQuestion+"</title>"+ "<link rel='stylesheet' href='style.css' type='text/css'/>"+ ((new File("c:/hack.css")).exists() ? "<link rel='stylesheet' href='file:///c:/hack.css' type='text/css'/>" : "")+ "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>"+ "<meta http-equiv='imagetoolbar' content='no'/>"+ "<script type='text/javascript'>window.isDevServlet=true;</script>"+ "</head>"+ "<body>"+ "<h1 style='font: bold 14px Verdana'>Question: "+sQuestion+" " + "[<a href='./'>Restart</a> <small>" + "<a href='./v0'>0</a> <a href='./v1'>1</a> <a href='./v2'>2</a> " + "<a href='./v3'>3</a> <a href='./v4'>4</a> " + "<a href='./?access=plain'>Plain</a> <a href='./?access=bw'>Colour</a> " + "<a href='./?access=big'>Big</a>" + "</small>] " + "[<a href='../../build/"+sQuestion+"/'>Rebuild</a>] " + "[<a href='../../'>List</a>] <small>[<a href='./?save'>Save</a>]</small>" + "</h1>"+ "<form method='post' action='./' id='question' autocomplete='off' class='om'/>"+ "<pre id='results' style='clear:both'/>"+ "<pre id='log'/>"+ ((new File("c:/hack.js")).exists() ? "<script type='text/javascript' src='file:///c:/hack.js'/>" : "")+ "</body>"+ "</xhtml>"); // Get question top-level element and clone it into new document Element eQuestion=(Element)d.importNode(r.getXHTML(),true); Element eDiv=XML.find(d,"id","question"); if(q instanceof StandardQuestion) { double dZoom=((StandardQuestion)q).getZoom(); eDiv.setAttribute("style","width:"+Math.round(dZoom * 600)+"px;"); } eDiv.appendChild(eQuestion); StringBuffer sbResults=new StringBuffer(); if(r instanceof ActionRendering) { Results rResults=((ActionRendering)r).getResults(); if(rResults!=null) { questionHasSentResults = true; sbResults.append("Results\n=======\n\nScores\n------\n\n"); Score[] as=rResults.getScores(); for(int i=0;i<as.length;i++) { if(as[i].getAxis()==null) sbResults.append("(default axis) "); else sbResults.append("["+as[i].getAxis()+"] "); sbResults.append(as[i].getMarks()+"\n"); } sbResults.append( "\nSummaries\n---------\n\n"+ "Question: "+XHTML.escape(rResults.getQuestionLine()==null ? "" : rResults.getQuestionLine(),XHTML.ESCAPE_TEXT)+"\n"+ "Answer: "+XHTML.escape(rResults.getAnswerLine()==null ? "" : rResults.getAnswerLine(),XHTML.ESCAPE_TEXT)+"\n"); sbResults.append( "\nActions\n-------\n\n"+XHTML.escape(rResults.getActionSummary()==null?"":rResults.getActionSummary(),XHTML.ESCAPE_TEXT)); XML.createText(XML.find(d,"id","results"),sbResults.toString()); } } if(q instanceof StandardQuestion) { StandardQuestion sq=(StandardQuestion)q; XML.createText(XML.find(d,"id","log"),sq.eatLog()); } // Fix up the replacement variables Map<String,String> mReplace=new HashMap<String,String>(getLabelReplaceMap()); mReplace.put("RESOURCES","resources"); mReplace.put("IDPREFIX",""); XML.replaceTokens(eQuestion,mReplace); // Update document root d.getDocumentElement().setAttribute("class",UserAgent.getBrowserString(request)); // Remember StringWriter sw=new StringWriter(); XHTML.saveFullDocument(d,sw,false,"en"); sLastXHTML=sw.toString(); // Whew! Now send to user XHTML.output(d,request,response,"en"); } /** Cache label replacement (Map of String (labelset id) -> Map ) */ private Map<String,Map<String,String> > mLabelReplace=new HashMap<String,Map<String, String> >(); /** * Returns the map of label replacements appropriate for the current session. * @param us Session * @return Map of replacements (don't change this) * @throws IOException Any problems loading it */ private Map<String, String> getLabelReplaceMap() throws IOException { String sKey="!default"; // Get from cache Map<String, String> mLabels=mLabelReplace.get(sKey); if(mLabels!=null) return mLabels; // Load from file Map<String, String> m=new HashMap<String, String>(); File f=new File(getServletContext().getRealPath("WEB-INF/labels/"+sKey+".xml")); if(!f.exists()) throw new IOException("Unable to find requested label set: "+sKey); Document d=XML.parse(f); Element[] aeLabels=XML.getChildren(d.getDocumentElement()); for(int i=0;i<aeLabels.length;i++) { m.put( XML.getRequiredAttribute(aeLabels[i],"id"), XML.getText(aeLabels[i])); } // Cache and return mLabelReplace.put(sKey,m); return m; } }
true
true
private void sendError(HttpServletRequest request,HttpServletResponse response, int iCode, String sTitle, String sMessage, Throwable tException) { try { response.setStatus(iCode); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); pw.println( "<html>" + "<head><title>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</title></head>"+ "<body>" + "<h1>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</h1>" + "<p>"+XHTML.escape(sMessage,XHTML.ESCAPE_TEXT)+"</p>" + "<p>" + ( (sInProgressID!=null && request.getPathInfo().equals("/run/"+sInProgressID+"/")) ? "<a href='./'>[Restart]</a> <a href='../../build/"+sInProgressID+"/'>[Rebuild]</a> " : "")+ "<a href='../../'>[List]</a> "+ "</p>"+ (tException!=null ? "<pre>"+XHTML.escape(Exceptions.getString( tException,new String[]{"om"}),XHTML.ESCAPE_TEXT)+"</pre>": "")+ "</body>" + "</html>"); pw.close(); } catch(IOException ioe) { // Ignore exception, they must have closed browser or something } } private void handleFront(boolean bPost,HttpServletRequest request,HttpServletResponse response) throws Exception { if(bPost) { String extraPackages = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { String extraPackage = request.getParameter("extra" + i).trim(); if (extraPackage.length()>0) { extraPackages += " <includepackage>"+extraPackage+"</includepackage>\n"; } } File fNew=new File( qdQuestions.getQuestionsFolder(),request.getParameter("package")+".xml"); Writer w=new OutputStreamWriter(new FileOutputStream(fNew),"UTF-8"); w.write( "<questiondefinition>\n" + " <sourcetree>"+request.getParameter("source")+"</sourcetree>\n" + " <package>"+request.getParameter("package")+"</package>\n" + extraPackages + "</questiondefinition>\n"); w.close(); response.sendRedirect("."); } QuestionDefinition[] aqd=qdQuestions.getQuestionDefinitions(); String extraPackagesHtml = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { extraPackagesHtml += "<input type='text' name='extra" + i + "' size='65' value='" + ((aqd.length>0 && aqd[aqd.length-1].getAdditionalPackageRoots().length>i) ? aqd[aqd.length-1].getAdditionalPackageRoots()[i] : "") + "'/><br />"; } // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>OpenMark-S (Om) question development</title>"+ "<style type='text/css'>\n"+ "body { font: 12px Verdana, sans-serif; }\n" + "h1 { font: bold 14px Verdana, sans-serif; }\n" + "a { color: black; }\n" + "h2 { font: 14px Verdana, sans-serif; }\n" + "#create,#questionbox { margin-bottom:20px; border:1px solid #888; padding:10px; }\n"+ "#create span { float:left; width:20em; margin-top: 5px }\n" + "#create span.fields { width:auto; }\n" + "#create div { clear:left; }\n"+ "</style>"+ "</head>"+ "<body>"+ "<h1>" + " OpenMark-S (Om) question development ("+OmVersion.getVersion()+")" + "</h1>" + "<div id='questionbox'>" + "<h2>Defined questions</h2>"+ "<ul id='questions'>"+ "</ul>"+ "</div>" + "<form id='create' method='post' action='.'>" + "<h2>Create new question</h2>" + "<div><span>Package</span><span class='fields'><input type='text' name='package' size='65' value='"+ ((aqd.length>0) ? aqd[aqd.length-1].getPackage().replaceAll("\\.[^.]$",".") : "")+ "'/></span></div>"+ "<div><span>Source tree</span><span class='fields'><input type='text' name='source' size='65' value='" + ((aqd.length>0) ? aqd[aqd.length-1].getSourceFolder().getAbsolutePath() : "")+ "'/></span></div>"+ "<div><span>Extra package (optional)</span><span class='fields'>" + extraPackagesHtml + "</span></div>"+ "<div><input type='submit' name='action' id='submit' value='Create'/></div>"+ "<p>This creates a new question definition file (.xml) in the questions " + "folder of your Om webapp.</p>"+ "</form>"+ "</body>"+ "</xhtml>"); // Find the root element and chuck in a line for each question Element eParent=XML.find(d,"id","questions"); for(int iQuestion=0;iQuestion<aqd.length;iQuestion++) { String encodedName = URLEncoder.encode(aqd[iQuestion].getID(), "UTF-8"); Element eQ=XML.createChild(eParent,"li"); XML.createText(eQ," "+aqd[iQuestion].getID()+" "); if(aqd[iQuestion].hasJar()) { Element eRun=XML.createChild(eQ,"a"); eRun.setAttribute("href","run/"+encodedName+"/"); XML.createText(eRun,"(Run)"); XML.createText(eQ," "); } Element eBuild=XML.createChild(eQ,"a"); eBuild.setAttribute("href","build/"+encodedName+"/"); XML.createText(eBuild,"(Build)"); XML.createText(eQ," "); Element eRemove=XML.createChild(eQ,"a"); eRemove.setAttribute("href","remove/"+encodedName+"/"); XML.createText(eRemove,"(Remove)"); } XHTML.output(d,request,response,"en"); } private void handleBuild(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { resetQuestion(); String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); boolean bSuccess=qdQuestions.getQuestionDefinition(sQuestion).build(pw); if(bSuccess) { pw.println( "<script type='text/javascript'>\n" + "var re=/^(.*)\\/build\\/(.*)$/;\n"+ "location.href=location.href.replace(re,'$1/run/$2');\n" + "</script>"); } else { pw.println( "<p><a href='javascript:location.reload()'>Rebuild</a></p>"); } pw.println("</body></html>"); pw.close(); } private void handleRemove(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } PrintWriter pw = response.getWriter(); File toRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".xml"); if (toRemove.exists()) { if (!toRemove.delete()) { pw.println("Could not remove the XML file."); } File jarToRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".jar"); if (jarToRemove.exists()) { if (!jarToRemove.delete()) { pw.println("Could not remove the jar file."); } } } else { pw.println("Unknown question."); } response.sendRedirect(".."); } private InitParams ipInProgress; private void handleRun(boolean bPost,String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); // Must access page with / at end if("".equals(sAfter) && !request.getRequestURI().endsWith("/")) { response.sendRedirect(request.getRequestURI()+"/"); return; } if("save".equals(request.getQueryString())) { // Delete existing saved files File fSave=new File(getServletContext().getRealPath("save")); if(!fSave.exists()) fSave.mkdir(); File[] afExisting=IO.listFiles(fSave); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } File fResources=new File(fSave,"resources"); if(!fResources.exists()) fResources.mkdir(); afExisting=IO.listFiles(fResources); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } // Save last xhtml FileOutputStream fos=new FileOutputStream(new File(fSave,"question.html")); fos.write(sLastXHTML.getBytes("UTF-8")); fos.close(); // Save CSS if(sCSS!=null) { fos=new FileOutputStream(new File(fSave,"style.css")); fos.write(sCSS.getBytes("UTF-8")); fos.close(); } // Save resources for(Map.Entry<String,Resource> me : mResources.entrySet()) { fos=new FileOutputStream(new File(fResources, me.getKey())); fos.write(me.getValue().getContent()); fos.close(); } response.setContentType("text/plain"); PrintWriter pw=response.getWriter(); pw.println( "OK, saved a local copy in 'save' folder within webapp.\n\n" + "Existing contents are cleared when you do that, so don't keep anything there!"); pw.close(); return; } // Different question if(!bPost) { int iVariant=-1; long randomSeed = System.currentTimeMillis(); if(sAfter.startsWith("v")) { iVariant=Integer.parseInt(sAfter.substring(1)); sAfter=""; } if(sAfter.startsWith("rs")) { randomSeed = Long.parseLong(sAfter.substring(2)); sAfter=""; } if(sAfter.equals("")) { resetQuestion(); QuestionDefinition qd=qdQuestions.getQuestionDefinition(sQuestion); QuestionDefinition.RunReturn rr=qd.run(); qInProgress=rr.q; cclInProgress=rr.ccl; sInProgressID=sQuestion; String sAccess=request.getParameter("access"); boolean bPlain="plain".equals(sAccess); double dZoom="big".equals(sAccess) ? 2.0 : 1.0; String sFG="bw".equals(sAccess) ? "#00ff00" : null; String sBG="bw".equals(sAccess) ? "#000000" : null; ipInProgress=new InitParams(randomSeed, sFG,sBG,dZoom,bPlain,cclInProgress,iVariant); Rendering r=qInProgress.init(rr.dMeta,ipInProgress); // Try starting the question a few times, and ensure we get the same result each time. String xHTML = XML.saveString(r.getXHTML()); for (int i = 0; i < NUM_REPEAT_INITS; i++) { Question qCopy = qInProgress.getClass().newInstance(); String newXHTML = XML.saveString(qCopy.init(rr.dMeta,ipInProgress).getXHTML()); if (!xHTML.equals(newXHTML)) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = new PrintWriter(response.getWriter()); pw.println("<html><head><title>Error starting question</title></head><body>"); pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: " + "Starting the question twice with the same random seed produced " + "different results. This means there is a bug in your question.</div>"); pw.println("<p><a href='../../build/" + sQuestion + "/'>Rebuild</a></p>"); pw.println("<h2>First verions of the question HTML</h2><pre>"); pw.println(XHTML.escape(xHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre><h2>Repeat version of the question HTML</h2><pre>"); pw.println(XHTML.escape(newXHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre>"); pw.println("</body></html>"); pw.close(); return; } } // Add resources Resource[] arResources=r.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style sCSS=r.getCSS(); // Serve XHTML serveXHTML(sQuestion,r,request,response,qInProgress); } else if(sCSS!=null && sAfter.equals("style.css")) { response.setContentType("text/css"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(sCSS); response.getWriter().close(); } else if(sAfter.startsWith("resources/")) { Resource r=mResources.get(sAfter.substring("resources/".length())); if(r==null) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Requested resource not found: "+sRemainingPath, null); } response.setContentType(r.getMimeType()); response.setContentLength(r.getContent().length); if(r.getEncoding()!=null) response.setCharacterEncoding(r.getEncoding()); response.getOutputStream().write(r.getContent()); response.getOutputStream().close(); } else { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } } else { if(!sQuestion.equals(sInProgressID)) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot change to a different question mid-question (the " + "developer servlet supports only a single session at a time, " + "so don't open multiple browser windows).", null); return; } if(sAfter.length()>0) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot POST to any URL other than the question.", null); return; } ActionParams ap=new ActionParams(); for(Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) { String sName = (String)e.nextElement(); ap.setParameter(sName,request.getParameter(sName)); } if(ipInProgress.isPlainMode()) ap.setParameter("plain","yes"); ActionRendering ar=qInProgress.action(ap); if(ar.isSessionEnd()) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=new PrintWriter(response.getWriter()); pw.println("<html><head><title>Question ended</title></head><body>"); if (!questionHasSentResults) { pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: The question ended without sending back any results.</div>"); pw.println("<p><a href='./'>Restart</a></p>"); } else { pw.println("<p>Question ended. <a href='./'>Restart</a></p>"); } pw.println("</body></html>"); pw.close(); } else { // Add resources Resource[] arResources=ar.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style if(ar.getCSS()!=null) sCSS=ar.getCSS(); // Serve XHTML serveXHTML(sQuestion,ar,request,response,qInProgress); } } } byte[] abTempCSS=null; private void handle(boolean bPost, HttpServletRequest request,HttpServletResponse response) { try { // Vitally important, otherwise any input with unicode gets screwed up request.setCharacterEncoding("UTF-8"); String sPath=request.getPathInfo(); if(sPath==null || sPath.equals("") || sPath.equals("/")) { // Must access page with / at end if(request.getRequestURI().endsWith("/")) { handleFront(bPost,request,response); } else { response.sendRedirect(request.getRequestURI()+"/"); return; } } else if(sPath.startsWith("/build/")) handleBuild(sPath.substring("/build/".length()),request,response); else if(sPath.startsWith("/run/")) handleRun(bPost,sPath.substring("/run/".length()),request,response); else if(sPath.startsWith("/remove/")) handleRemove(sPath.substring("/remove/".length()),request,response); else { sendError(request,response,HttpServletResponse.SC_NOT_FOUND, "Not found","The URL you requested is not provided by this server.", null); } } catch(Throwable t) { sendError(request,response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Error handling request","An exception occurred.", t); } } /** Remember last xhtml sent so we can save it */ private String sLastXHTML; private void serveXHTML(String sQuestion,Rendering r, HttpServletRequest request,HttpServletResponse response,Question q) throws IOException { // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>Question: "+sQuestion+"</title>"+ "<link rel='stylesheet' href='style.css' type='text/css'/>"+ ((new File("c:/hack.css")).exists() ? "<link rel='stylesheet' href='file:///c:/hack.css' type='text/css'/>" : "")+ "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>"+ "<meta http-equiv='imagetoolbar' content='no'/>"+ "<script type='text/javascript'>window.isDevServlet=true;</script>"+ "</head>"+ "<body>"+ "<h1 style='font: bold 14px Verdana'>Question: "+sQuestion+" " + "[<a href='./'>Restart</a> <small>" + "<a href='./v0'>0</a> <a href='./v1'>1</a> <a href='./v2'>2</a> " + "<a href='./v3'>3</a> <a href='./v4'>4</a> " + "<a href='./?access=plain'>Plain</a> <a href='./?access=bw'>Colour</a> " + "<a href='./?access=big'>Big</a>" + "</small>] " + "[<a href='../../build/"+sQuestion+"/'>Rebuild</a>] " + "[<a href='../../'>List</a>] <small>[<a href='./?save'>Save</a>]</small>" + "</h1>"+ "<form method='post' action='./' id='question' autocomplete='off' class='om'/>"+ "<pre id='results' style='clear:both'/>"+ "<pre id='log'/>"+ ((new File("c:/hack.js")).exists() ? "<script type='text/javascript' src='file:///c:/hack.js'/>" : "")+ "</body>"+ "</xhtml>"); // Get question top-level element and clone it into new document Element eQuestion=(Element)d.importNode(r.getXHTML(),true); Element eDiv=XML.find(d,"id","question"); if(q instanceof StandardQuestion) { double dZoom=((StandardQuestion)q).getZoom(); eDiv.setAttribute("style","width:"+Math.round(dZoom * 600)+"px;"); } eDiv.appendChild(eQuestion); StringBuffer sbResults=new StringBuffer(); if(r instanceof ActionRendering) { Results rResults=((ActionRendering)r).getResults(); if(rResults!=null) { questionHasSentResults = true; sbResults.append("Results\n=======\n\nScores\n------\n\n"); Score[] as=rResults.getScores(); for(int i=0;i<as.length;i++) { if(as[i].getAxis()==null) sbResults.append("(default axis) "); else sbResults.append("["+as[i].getAxis()+"] "); sbResults.append(as[i].getMarks()+"\n"); } sbResults.append( "\nSummaries\n---------\n\n"+ "Question: "+XHTML.escape(rResults.getQuestionLine()==null ? "" : rResults.getQuestionLine(),XHTML.ESCAPE_TEXT)+"\n"+ "Answer: "+XHTML.escape(rResults.getAnswerLine()==null ? "" : rResults.getAnswerLine(),XHTML.ESCAPE_TEXT)+"\n"); sbResults.append( "\nActions\n-------\n\n"+XHTML.escape(rResults.getActionSummary()==null?"":rResults.getActionSummary(),XHTML.ESCAPE_TEXT)); XML.createText(XML.find(d,"id","results"),sbResults.toString()); } } if(q instanceof StandardQuestion) { StandardQuestion sq=(StandardQuestion)q; XML.createText(XML.find(d,"id","log"),sq.eatLog()); } // Fix up the replacement variables Map<String,String> mReplace=new HashMap<String,String>(getLabelReplaceMap()); mReplace.put("RESOURCES","resources"); mReplace.put("IDPREFIX",""); XML.replaceTokens(eQuestion,mReplace); // Update document root d.getDocumentElement().setAttribute("class",UserAgent.getBrowserString(request)); // Remember StringWriter sw=new StringWriter(); XHTML.saveFullDocument(d,sw,false,"en"); sLastXHTML=sw.toString(); // Whew! Now send to user XHTML.output(d,request,response,"en"); } /** Cache label replacement (Map of String (labelset id) -> Map ) */ private Map<String,Map<String,String> > mLabelReplace=new HashMap<String,Map<String, String> >(); /** * Returns the map of label replacements appropriate for the current session. * @param us Session * @return Map of replacements (don't change this) * @throws IOException Any problems loading it */ private Map<String, String> getLabelReplaceMap() throws IOException { String sKey="!default"; // Get from cache Map<String, String> mLabels=mLabelReplace.get(sKey); if(mLabels!=null) return mLabels; // Load from file Map<String, String> m=new HashMap<String, String>(); File f=new File(getServletContext().getRealPath("WEB-INF/labels/"+sKey+".xml")); if(!f.exists()) throw new IOException("Unable to find requested label set: "+sKey); Document d=XML.parse(f); Element[] aeLabels=XML.getChildren(d.getDocumentElement()); for(int i=0;i<aeLabels.length;i++) { m.put( XML.getRequiredAttribute(aeLabels[i],"id"), XML.getText(aeLabels[i])); } // Cache and return mLabelReplace.put(sKey,m); return m; } }
private void sendError(HttpServletRequest request,HttpServletResponse response, int iCode, String sTitle, String sMessage, Throwable tException) { try { response.setStatus(iCode); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); pw.println( "<html>" + "<head><title>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</title></head>"+ "<body>" + "<h1>"+XHTML.escape(sTitle,XHTML.ESCAPE_TEXT)+"</h1>" + "<p>"+XHTML.escape(sMessage,XHTML.ESCAPE_TEXT)+"</p>" + "<p>" + ( (sInProgressID!=null && request.getPathInfo().equals("/run/"+sInProgressID+"/")) ? "<a href='./'>[Restart]</a> <a href='../../build/"+sInProgressID+"/'>[Rebuild]</a> " : "")+ "<a href='../../'>[List]</a> "+ "</p>"+ (tException!=null ? "<pre>"+XHTML.escape(Exceptions.getString( tException,new String[]{"om"}),XHTML.ESCAPE_TEXT)+"</pre>": "")+ "</body>" + "</html>"); pw.close(); } catch(IOException ioe) { // Ignore exception, they must have closed browser or something } } private void handleFront(boolean bPost,HttpServletRequest request,HttpServletResponse response) throws Exception { if(bPost) { String extraPackages = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { String extraPackage = request.getParameter("extra" + i).trim(); if (extraPackage.length()>0) { extraPackages += " <includepackage>"+extraPackage+"</includepackage>\n"; } } File fNew=new File( qdQuestions.getQuestionsFolder(),request.getParameter("package")+".xml"); Writer w=new OutputStreamWriter(new FileOutputStream(fNew),"UTF-8"); w.write( "<questiondefinition>\n" + " <sourcetree>"+request.getParameter("source")+"</sourcetree>\n" + " <package>"+request.getParameter("package")+"</package>\n" + extraPackages + "</questiondefinition>\n"); w.close(); response.sendRedirect("."); } QuestionDefinition[] aqd=qdQuestions.getQuestionDefinitions(); String extraPackagesHtml = ""; for (int i = 0; i<NUM_EXTRA_PACKAGE_SLOTS; ++i) { extraPackagesHtml += "<input type='text' name='extra" + i + "' size='65' value='" + ((aqd.length>0 && aqd[aqd.length-1].getAdditionalPackageRoots().length>i) ? aqd[aqd.length-1].getAdditionalPackageRoots()[i] : "") + "'/><br />"; } // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>OpenMark-S (Om) question development</title>"+ "<style type='text/css'>\n"+ "body { font: 12px Verdana, sans-serif; }\n" + "h1 { font: bold 14px Verdana, sans-serif; }\n" + "a { color: black; }\n" + "h2 { font: 14px Verdana, sans-serif; }\n" + "#create,#questionbox { margin-bottom:20px; border:1px solid #888; padding:10px; }\n"+ "#create span { float:left; width:20em; margin-top: 5px }\n" + "#create span.fields { width:auto; }\n" + "#create div { clear:left; }\n"+ "</style>"+ "</head>"+ "<body>"+ "<h1>" + " OpenMark-S (Om) question development ("+OmVersion.getVersion()+")" + "</h1>" + "<div id='questionbox'>" + "<h2>Defined questions</h2>"+ "<ul id='questions'>"+ "</ul>"+ "</div>" + "<form id='create' method='post' action='.'>" + "<h2>Create new question</h2>" + "<div><span>Package</span><span class='fields'><input type='text' name='package' size='65' value='"+ ((aqd.length>0) ? aqd[aqd.length-1].getPackage().replaceAll("\\.[^.]$",".") : "")+ "'/></span></div>"+ "<div><span>Source tree</span><span class='fields'><input type='text' name='source' size='65' value='" + ((aqd.length>0) ? aqd[aqd.length-1].getSourceFolder().getAbsolutePath() : "")+ "'/></span></div>"+ "<div><span>Extra package (optional)</span><span class='fields'>" + extraPackagesHtml + "</span></div>"+ "<div><input type='submit' name='action' id='submit' value='Create'/></div>"+ "<p>This creates a new question definition file (.xml) in the questions " + "folder of your Om webapp.</p>"+ "</form>"+ "</body>"+ "</xhtml>"); // Find the root element and chuck in a line for each question Element eParent=XML.find(d,"id","questions"); for(int iQuestion=0;iQuestion<aqd.length;iQuestion++) { String encodedName = URLEncoder.encode(aqd[iQuestion].getID(), "UTF-8"); Element eQ=XML.createChild(eParent,"li"); XML.createText(eQ," "+aqd[iQuestion].getID()+" "); if(aqd[iQuestion].hasJar()) { Element eRun=XML.createChild(eQ,"a"); eRun.setAttribute("href","run/"+encodedName+"/"); XML.createText(eRun,"(Run)"); XML.createText(eQ," "); } Element eBuild=XML.createChild(eQ,"a"); eBuild.setAttribute("href","build/"+encodedName+"/"); XML.createText(eBuild,"(Build)"); XML.createText(eQ," "); Element eRemove=XML.createChild(eQ,"a"); eRemove.setAttribute("href","remove/"+encodedName+"/"); XML.createText(eRemove,"(Remove)"); } XHTML.output(d,request,response,"en"); } private void handleBuild(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { resetQuestion(); String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); boolean bSuccess=qdQuestions.getQuestionDefinition(sQuestion).build(pw); if(bSuccess) { pw.println( "<script type='text/javascript'>\n" + "var re=/^(.*)\\/build\\/(.*)$/;\n"+ "location.href=location.href.replace(re,'$1/run/$2');\n" + "</script>"); } else { pw.println( "<p><a href='javascript:location.reload()'>Rebuild</a></p>"); } pw.println("</body></html>"); pw.close(); } private void handleRemove(String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); if(!sAfter.equals("")) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } PrintWriter pw = response.getWriter(); File toRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".xml"); if (toRemove.exists()) { if (!toRemove.delete()) { pw.println("Could not remove the XML file."); } File jarToRemove=new File( qdQuestions.getQuestionsFolder(),sQuestion+".jar"); if (jarToRemove.exists()) { if (!jarToRemove.delete()) { pw.println("Could not remove the jar file."); } } } else { pw.println("Unknown question."); } response.sendRedirect(".."); } private InitParams ipInProgress; private void handleRun(boolean bPost,String sRemainingPath, HttpServletRequest request,HttpServletResponse response) throws Exception { String sQuestion=sRemainingPath.replaceAll("^([^/]*)/?.*$","$1"); String sAfter=sRemainingPath.replaceAll("^[^/]*/?(.*)$","$1"); // Must access page with / at end if("".equals(sAfter) && !request.getRequestURI().endsWith("/")) { response.sendRedirect(request.getRequestURI()+"/"); return; } if("save".equals(request.getQueryString())) { // Delete existing saved files File fSave=new File(getServletContext().getRealPath("save")); if(!fSave.exists()) fSave.mkdir(); File[] afExisting=IO.listFiles(fSave); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } File fResources=new File(fSave,"resources"); if(!fResources.exists()) fResources.mkdir(); afExisting=IO.listFiles(fResources); for(int i=0;i<afExisting.length;i++) { if(afExisting[i].isFile()) afExisting[i].delete(); } // Save last xhtml FileOutputStream fos=new FileOutputStream(new File(fSave,"question.html")); fos.write(sLastXHTML.getBytes("UTF-8")); fos.close(); // Save CSS if(sCSS!=null) { fos=new FileOutputStream(new File(fSave,"style.css")); fos.write(sCSS.getBytes("UTF-8")); fos.close(); } // Save resources for(Map.Entry<String,Resource> me : mResources.entrySet()) { fos=new FileOutputStream(new File(fResources, me.getKey())); fos.write(me.getValue().getContent()); fos.close(); } response.setContentType("text/plain"); PrintWriter pw=response.getWriter(); pw.println( "OK, saved a local copy in 'save' folder within webapp.\n\n" + "Existing contents are cleared when you do that, so don't keep anything there!"); pw.close(); return; } // Different question if(!bPost) { int iVariant=-1; long randomSeed = System.currentTimeMillis(); if(sAfter.startsWith("v")) { iVariant=Integer.parseInt(sAfter.substring(1)); sAfter=""; } if(sAfter.startsWith("rs")) { randomSeed = Long.parseLong(sAfter.substring(2)); sAfter=""; } if(sAfter.equals("")) { resetQuestion(); QuestionDefinition qd=qdQuestions.getQuestionDefinition(sQuestion); QuestionDefinition.RunReturn rr=qd.run(); qInProgress=rr.q; cclInProgress=rr.ccl; sInProgressID=sQuestion; String sAccess=request.getParameter("access"); boolean bPlain="plain".equals(sAccess); double dZoom="big".equals(sAccess) ? 2.0 : 1.0; String sFG="bw".equals(sAccess) ? "#00ff00" : null; String sBG="bw".equals(sAccess) ? "#000000" : null; ipInProgress=new InitParams(randomSeed, sFG,sBG,dZoom,bPlain,cclInProgress,iVariant); Rendering r=qInProgress.init(rr.dMeta,ipInProgress); // Try starting the question a few times, and ensure we get the same result each time. String xHTML = XML.saveString(r.getXHTML()); for (int i = 0; i < NUM_REPEAT_INITS; i++) { Question qCopy = qInProgress.getClass().newInstance(); String newXHTML = XML.saveString(qCopy.init(rr.dMeta,ipInProgress).getXHTML()); if (!xHTML.equals(newXHTML)) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = new PrintWriter(response.getWriter()); pw.println("<html><head><title>Error starting question</title></head><body>"); pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: " + "Starting the question twice with the same random seed produced " + "different results. This means there is a bug in your question.</div>"); pw.println("<p><a href='../../build/" + sQuestion + "/'>Rebuild</a></p>"); pw.println("<h2>First version of the question HTML</h2><pre>"); pw.println(XHTML.escape(xHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre><h2>Repeat version of the question HTML</h2><pre>"); pw.println(XHTML.escape(newXHTML, XHTML.ESCAPE_TEXT)); pw.println("</pre>"); pw.println("</body></html>"); pw.close(); return; } } // Add resources Resource[] arResources=r.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style sCSS=r.getCSS(); // Serve XHTML serveXHTML(sQuestion,r,request,response,qInProgress); } else if(sCSS!=null && sAfter.equals("style.css")) { response.setContentType("text/css"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(sCSS); response.getWriter().close(); } else if(sAfter.startsWith("resources/")) { Resource r=mResources.get(sAfter.substring("resources/".length())); if(r==null) { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Requested resource not found: "+sRemainingPath, null); } response.setContentType(r.getMimeType()); response.setContentLength(r.getContent().length); if(r.getEncoding()!=null) response.setCharacterEncoding(r.getEncoding()); response.getOutputStream().write(r.getContent()); response.getOutputStream().close(); } else { sendError(request,response, HttpServletResponse.SC_NOT_FOUND,"Not found","Don't know how to handle request: "+sRemainingPath, null); return; } } else { if(!sQuestion.equals(sInProgressID)) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot change to a different question mid-question (the " + "developer servlet supports only a single session at a time, " + "so don't open multiple browser windows).", null); return; } if(sAfter.length()>0) { sendError(request,response, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "POST not allowed","You cannot POST to any URL other than the question.", null); return; } ActionParams ap=new ActionParams(); for(Enumeration<?> e = request.getParameterNames(); e.hasMoreElements();) { String sName = (String)e.nextElement(); ap.setParameter(sName,request.getParameter(sName)); } if(ipInProgress.isPlainMode()) ap.setParameter("plain","yes"); ActionRendering ar=qInProgress.action(ap); if(ar.isSessionEnd()) { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=new PrintWriter(response.getWriter()); pw.println("<html><head><title>Question ended</title></head><body>"); if (!questionHasSentResults) { pw.println("<div style='border: 1px solid #888; padding: 1em; background: #fdc; font-weight: bold'>Error: The question ended without sending back any results.</div>"); pw.println("<p><a href='./'>Restart</a></p>"); } else { pw.println("<p>Question ended. <a href='./'>Restart</a></p>"); } pw.println("</body></html>"); pw.close(); } else { // Add resources Resource[] arResources=ar.getResources(); for(int i=0;i<arResources.length;i++) { mResources.put(arResources[i].getFilename(),arResources[i]); } // Set style if(ar.getCSS()!=null) sCSS=ar.getCSS(); // Serve XHTML serveXHTML(sQuestion,ar,request,response,qInProgress); } } } byte[] abTempCSS=null; private void handle(boolean bPost, HttpServletRequest request,HttpServletResponse response) { try { // Vitally important, otherwise any input with unicode gets screwed up request.setCharacterEncoding("UTF-8"); String sPath=request.getPathInfo(); if(sPath==null || sPath.equals("") || sPath.equals("/")) { // Must access page with / at end if(request.getRequestURI().endsWith("/")) { handleFront(bPost,request,response); } else { response.sendRedirect(request.getRequestURI()+"/"); return; } } else if(sPath.startsWith("/build/")) handleBuild(sPath.substring("/build/".length()),request,response); else if(sPath.startsWith("/run/")) handleRun(bPost,sPath.substring("/run/".length()),request,response); else if(sPath.startsWith("/remove/")) handleRemove(sPath.substring("/remove/".length()),request,response); else { sendError(request,response,HttpServletResponse.SC_NOT_FOUND, "Not found","The URL you requested is not provided by this server.", null); } } catch(Throwable t) { sendError(request,response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Error handling request","An exception occurred.", t); } } /** Remember last xhtml sent so we can save it */ private String sLastXHTML; private void serveXHTML(String sQuestion,Rendering r, HttpServletRequest request,HttpServletResponse response,Question q) throws IOException { // Create basic template Document d=XML.parse( "<xhtml>" + "<head>" + "<title>Question: "+sQuestion+"</title>"+ "<link rel='stylesheet' href='style.css' type='text/css'/>"+ ((new File("c:/hack.css")).exists() ? "<link rel='stylesheet' href='file:///c:/hack.css' type='text/css'/>" : "")+ "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>"+ "<meta http-equiv='imagetoolbar' content='no'/>"+ "<script type='text/javascript'>window.isDevServlet=true;</script>"+ "</head>"+ "<body>"+ "<h1 style='font: bold 14px Verdana'>Question: "+sQuestion+" " + "[<a href='./'>Restart</a> <small>" + "<a href='./v0'>0</a> <a href='./v1'>1</a> <a href='./v2'>2</a> " + "<a href='./v3'>3</a> <a href='./v4'>4</a> " + "<a href='./?access=plain'>Plain</a> <a href='./?access=bw'>Colour</a> " + "<a href='./?access=big'>Big</a>" + "</small>] " + "[<a href='../../build/"+sQuestion+"/'>Rebuild</a>] " + "[<a href='../../'>List</a>] <small>[<a href='./?save'>Save</a>]</small>" + "</h1>"+ "<form method='post' action='./' id='question' autocomplete='off' class='om'/>"+ "<pre id='results' style='clear:both'/>"+ "<pre id='log'/>"+ ((new File("c:/hack.js")).exists() ? "<script type='text/javascript' src='file:///c:/hack.js'/>" : "")+ "</body>"+ "</xhtml>"); // Get question top-level element and clone it into new document Element eQuestion=(Element)d.importNode(r.getXHTML(),true); Element eDiv=XML.find(d,"id","question"); if(q instanceof StandardQuestion) { double dZoom=((StandardQuestion)q).getZoom(); eDiv.setAttribute("style","width:"+Math.round(dZoom * 600)+"px;"); } eDiv.appendChild(eQuestion); StringBuffer sbResults=new StringBuffer(); if(r instanceof ActionRendering) { Results rResults=((ActionRendering)r).getResults(); if(rResults!=null) { questionHasSentResults = true; sbResults.append("Results\n=======\n\nScores\n------\n\n"); Score[] as=rResults.getScores(); for(int i=0;i<as.length;i++) { if(as[i].getAxis()==null) sbResults.append("(default axis) "); else sbResults.append("["+as[i].getAxis()+"] "); sbResults.append(as[i].getMarks()+"\n"); } sbResults.append( "\nSummaries\n---------\n\n"+ "Question: "+XHTML.escape(rResults.getQuestionLine()==null ? "" : rResults.getQuestionLine(),XHTML.ESCAPE_TEXT)+"\n"+ "Answer: "+XHTML.escape(rResults.getAnswerLine()==null ? "" : rResults.getAnswerLine(),XHTML.ESCAPE_TEXT)+"\n"); sbResults.append( "\nActions\n-------\n\n"+XHTML.escape(rResults.getActionSummary()==null?"":rResults.getActionSummary(),XHTML.ESCAPE_TEXT)); XML.createText(XML.find(d,"id","results"),sbResults.toString()); } } if(q instanceof StandardQuestion) { StandardQuestion sq=(StandardQuestion)q; XML.createText(XML.find(d,"id","log"),sq.eatLog()); } // Fix up the replacement variables Map<String,String> mReplace=new HashMap<String,String>(getLabelReplaceMap()); mReplace.put("RESOURCES","resources"); mReplace.put("IDPREFIX",""); XML.replaceTokens(eQuestion,mReplace); // Update document root d.getDocumentElement().setAttribute("class",UserAgent.getBrowserString(request)); // Remember StringWriter sw=new StringWriter(); XHTML.saveFullDocument(d,sw,false,"en"); sLastXHTML=sw.toString(); // Whew! Now send to user XHTML.output(d,request,response,"en"); } /** Cache label replacement (Map of String (labelset id) -> Map ) */ private Map<String,Map<String,String> > mLabelReplace=new HashMap<String,Map<String, String> >(); /** * Returns the map of label replacements appropriate for the current session. * @param us Session * @return Map of replacements (don't change this) * @throws IOException Any problems loading it */ private Map<String, String> getLabelReplaceMap() throws IOException { String sKey="!default"; // Get from cache Map<String, String> mLabels=mLabelReplace.get(sKey); if(mLabels!=null) return mLabels; // Load from file Map<String, String> m=new HashMap<String, String>(); File f=new File(getServletContext().getRealPath("WEB-INF/labels/"+sKey+".xml")); if(!f.exists()) throw new IOException("Unable to find requested label set: "+sKey); Document d=XML.parse(f); Element[] aeLabels=XML.getChildren(d.getDocumentElement()); for(int i=0;i<aeLabels.length;i++) { m.put( XML.getRequiredAttribute(aeLabels[i],"id"), XML.getText(aeLabels[i])); } // Cache and return mLabelReplace.put(sKey,m); return m; } }
diff --git a/webapp/WEB-INF/classes/org/makumba/parade/controller/FileAction.java b/webapp/WEB-INF/classes/org/makumba/parade/controller/FileAction.java index fb33db7..1b4b043 100644 --- a/webapp/WEB-INF/classes/org/makumba/parade/controller/FileAction.java +++ b/webapp/WEB-INF/classes/org/makumba/parade/controller/FileAction.java @@ -1,91 +1,91 @@ package org.makumba.parade.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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.apache.struts.upload.FormFile; import org.makumba.parade.model.Parade; import org.makumba.parade.model.managers.CVSManager; import org.makumba.parade.model.managers.FileManager; import org.makumba.parade.tools.ParadeJNotifyListener; public class FileAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String context = request.getParameter("context"); String path = request.getParameter("path"); String file = request.getParameter("file"); String op = request.getParameter("op"); String[] source = request.getParameterValues("source"); // we reconstruct the absolute path if (op != null && op.startsWith("deleteFile")) { String[] params = { request.getParameter("params"), path }; Object result[] = CommandController.onDeleteFile(context, params); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); } if (op != null && op.startsWith("editFile")) { return (mapping.findForward("edit")); } if (op != null && op.startsWith("saveFile")) { String absoluteFilePath = Parade.constructAbsolutePath(context, path) + java.io.File.separator + file; ParadeJNotifyListener.createFileLock(absoluteFilePath); FileController.saveFile(absoluteFilePath, source); - FileManager.updateSimpleFileCache(context, path, file); + FileManager.updateSimpleFileCache(context, Parade.constructAbsolutePath(context, path), file); CVSManager.updateSimpleCvsCache(context, absoluteFilePath); ParadeJNotifyListener.updateRelations(Parade.constructAbsolutePath(context, ""), path + (path.endsWith("/") || file.startsWith("/") ? "" : java.io.File.separator) + file); ParadeJNotifyListener.removeFileLock(absoluteFilePath); return (mapping.findForward("edit")); } if (op != null && op.startsWith("upload")) { request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("display", "command"); request.setAttribute("view", "commandOutput"); request.setAttribute("file", file); UploadForm uploadForm = (UploadForm) form; // Process the FormFile FormFile theFile = uploadForm.getTheFile(); String contentType = theFile.getContentType(); String fileName = theFile.getFileName(); int fileSize = theFile.getFileSize(); byte[] fileData = theFile.getFileData(); // upload the file Object result[] = CommandController.uploadFile(context, path, fileName, contentType, fileSize, fileData); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); return mapping.findForward("browse"); } request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("file", file); request.setAttribute("display", "file"); return (mapping.findForward("browse")); } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String context = request.getParameter("context"); String path = request.getParameter("path"); String file = request.getParameter("file"); String op = request.getParameter("op"); String[] source = request.getParameterValues("source"); // we reconstruct the absolute path if (op != null && op.startsWith("deleteFile")) { String[] params = { request.getParameter("params"), path }; Object result[] = CommandController.onDeleteFile(context, params); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); } if (op != null && op.startsWith("editFile")) { return (mapping.findForward("edit")); } if (op != null && op.startsWith("saveFile")) { String absoluteFilePath = Parade.constructAbsolutePath(context, path) + java.io.File.separator + file; ParadeJNotifyListener.createFileLock(absoluteFilePath); FileController.saveFile(absoluteFilePath, source); FileManager.updateSimpleFileCache(context, path, file); CVSManager.updateSimpleCvsCache(context, absoluteFilePath); ParadeJNotifyListener.updateRelations(Parade.constructAbsolutePath(context, ""), path + (path.endsWith("/") || file.startsWith("/") ? "" : java.io.File.separator) + file); ParadeJNotifyListener.removeFileLock(absoluteFilePath); return (mapping.findForward("edit")); } if (op != null && op.startsWith("upload")) { request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("display", "command"); request.setAttribute("view", "commandOutput"); request.setAttribute("file", file); UploadForm uploadForm = (UploadForm) form; // Process the FormFile FormFile theFile = uploadForm.getTheFile(); String contentType = theFile.getContentType(); String fileName = theFile.getFileName(); int fileSize = theFile.getFileSize(); byte[] fileData = theFile.getFileData(); // upload the file Object result[] = CommandController.uploadFile(context, path, fileName, contentType, fileSize, fileData); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); return mapping.findForward("browse"); } request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("file", file); request.setAttribute("display", "file"); return (mapping.findForward("browse")); }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String context = request.getParameter("context"); String path = request.getParameter("path"); String file = request.getParameter("file"); String op = request.getParameter("op"); String[] source = request.getParameterValues("source"); // we reconstruct the absolute path if (op != null && op.startsWith("deleteFile")) { String[] params = { request.getParameter("params"), path }; Object result[] = CommandController.onDeleteFile(context, params); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); } if (op != null && op.startsWith("editFile")) { return (mapping.findForward("edit")); } if (op != null && op.startsWith("saveFile")) { String absoluteFilePath = Parade.constructAbsolutePath(context, path) + java.io.File.separator + file; ParadeJNotifyListener.createFileLock(absoluteFilePath); FileController.saveFile(absoluteFilePath, source); FileManager.updateSimpleFileCache(context, Parade.constructAbsolutePath(context, path), file); CVSManager.updateSimpleCvsCache(context, absoluteFilePath); ParadeJNotifyListener.updateRelations(Parade.constructAbsolutePath(context, ""), path + (path.endsWith("/") || file.startsWith("/") ? "" : java.io.File.separator) + file); ParadeJNotifyListener.removeFileLock(absoluteFilePath); return (mapping.findForward("edit")); } if (op != null && op.startsWith("upload")) { request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("display", "command"); request.setAttribute("view", "commandOutput"); request.setAttribute("file", file); UploadForm uploadForm = (UploadForm) form; // Process the FormFile FormFile theFile = uploadForm.getTheFile(); String contentType = theFile.getContentType(); String fileName = theFile.getFileName(); int fileSize = theFile.getFileSize(); byte[] fileData = theFile.getFileData(); // upload the file Object result[] = CommandController.uploadFile(context, path, fileName, contentType, fileSize, fileData); request.setAttribute("result", result[0]); request.setAttribute("success", result[1]); return mapping.findForward("browse"); } request.setAttribute("context", context); request.setAttribute("path", path); request.setAttribute("file", file); request.setAttribute("display", "file"); return (mapping.findForward("browse")); }
diff --git a/src/com/android/settings/wifi/WifiDialog.java b/src/com/android/settings/wifi/WifiDialog.java index 9250ee08b..a4538a4c1 100644 --- a/src/com/android/settings/wifi/WifiDialog.java +++ b/src/com/android/settings/wifi/WifiDialog.java @@ -1,362 +1,363 @@ /* * 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.wifi; import com.android.settings.R; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.AuthAlgorithm; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiInfo; import android.os.Bundle; import android.security.Credentials; import android.security.KeyStore; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.text.format.Formatter; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.TextView; class WifiDialog extends AlertDialog implements View.OnClickListener, TextWatcher, AdapterView.OnItemSelectedListener { private static final String KEYSTORE_SPACE = "keystore://"; static final int BUTTON_SUBMIT = DialogInterface.BUTTON_POSITIVE; static final int BUTTON_FORGET = DialogInterface.BUTTON_NEUTRAL; final boolean edit; private final DialogInterface.OnClickListener mListener; private final AccessPoint mAccessPoint; private View mView; private TextView mSsid; private int mSecurity; private TextView mPassword; private Spinner mEapMethod; private Spinner mEapCaCert; private Spinner mEapUserCert; private TextView mEapIdentity; private TextView mEapAnonymous; static boolean requireKeyStore(WifiConfiguration config) { String values[] = {config.ca_cert.value(), config.client_cert.value(), config.private_key.value()}; for (String value : values) { if (value != null && value.startsWith(KEYSTORE_SPACE)) { return true; } } return false; } WifiDialog(Context context, DialogInterface.OnClickListener listener, AccessPoint accessPoint, boolean edit) { super(context); this.edit = edit; mListener = listener; mAccessPoint = accessPoint; mSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE : accessPoint.security; } WifiConfiguration getConfig() { if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) { return null; } WifiConfiguration config = new WifiConfiguration(); if (mAccessPoint == null) { config.SSID = mSsid.getText().toString(); // If the user adds a network manually, assume that it is hidden. config.hiddenSSID = true; } else if (mAccessPoint.networkId == -1) { config.SSID = mAccessPoint.ssid; } else { config.networkId = mAccessPoint.networkId; } switch (mSecurity) { case AccessPoint.SECURITY_NONE: config.allowedKeyManagement.set(KeyMgmt.NONE); return config; case AccessPoint.SECURITY_WEP: config.allowedKeyManagement.set(KeyMgmt.NONE); + config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); if (mPassword.length() != 0) { int length = mPassword.length(); String password = mPassword.getText().toString(); // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) { config.wepKeys[0] = password; } else { config.wepKeys[0] = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_PSK: config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); if (mPassword.length() != 0) { String password = mPassword.getText().toString(); if (password.matches("[0-9A-Fa-f]{64}")) { config.preSharedKey = password; } else { config.preSharedKey = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_EAP: config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); config.eap.setValue((String) mEapMethod.getSelectedItem()); config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.CA_CERTIFICATE + (String) mEapCaCert.getSelectedItem()); config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE + (String) mEapUserCert.getSelectedItem()); config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.PRIVATE_KEY + (String) mEapUserCert.getSelectedItem()); config.identity.setValue((mEapIdentity.length() == 0) ? "" : mEapIdentity.getText().toString()); config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" : mEapAnonymous.getText().toString()); if (mPassword.length() != 0) { config.password.setValue(mPassword.getText().toString()); } return config; } return null; } @Override protected void onCreate(Bundle savedInstanceState) { mView = getLayoutInflater().inflate(R.layout.wifi_dialog, null); setView(mView); setInverseBackgroundForced(true); Context context = getContext(); Resources resources = context.getResources(); if (mAccessPoint == null) { setTitle(R.string.wifi_add_network); mView.findViewById(R.id.type).setVisibility(View.VISIBLE); mSsid = (TextView) mView.findViewById(R.id.ssid); mSsid.addTextChangedListener(this); ((Spinner) mView.findViewById(R.id.security)).setOnItemSelectedListener(this); setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save), mListener); } else { setTitle(mAccessPoint.ssid); ViewGroup group = (ViewGroup) mView.findViewById(R.id.info); DetailedState state = mAccessPoint.getState(); if (state != null) { addRow(group, R.string.wifi_status, Summary.get(getContext(), state)); } String[] type = resources.getStringArray(R.array.wifi_security); addRow(group, R.string.wifi_security, type[mAccessPoint.security]); int level = mAccessPoint.getLevel(); if (level != -1) { String[] signal = resources.getStringArray(R.array.wifi_signal); addRow(group, R.string.wifi_signal, signal[level]); } WifiInfo info = mAccessPoint.getInfo(); if (info != null) { addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS); // TODO: fix the ip address for IPv6. int address = info.getIpAddress(); if (address != 0) { addRow(group, R.string.wifi_ip_address, Formatter.formatIpAddress(address)); } } if (mAccessPoint.networkId == -1 || edit) { showSecurityFields(); } if (edit) { setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save), mListener); } else { if (state == null && level != -1) { setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_connect), mListener); } if (mAccessPoint.networkId != -1) { setButton(BUTTON_FORGET, context.getString(R.string.wifi_forget), mListener); } } } setButton(DialogInterface.BUTTON_NEGATIVE, context.getString(R.string.wifi_cancel), mListener); super.onCreate(savedInstanceState); if (getButton(BUTTON_SUBMIT) != null) { validate(); } } private void addRow(ViewGroup group, int name, String value) { View row = getLayoutInflater().inflate(R.layout.wifi_dialog_row, group, false); ((TextView) row.findViewById(R.id.name)).setText(name); ((TextView) row.findViewById(R.id.value)).setText(value); group.addView(row); } private void validate() { // TODO: make sure this is complete. if ((mSsid != null && mSsid.length() == 0) || ((mAccessPoint == null || mAccessPoint.networkId == -1) && ((mSecurity == AccessPoint.SECURITY_WEP && mPassword.length() == 0) || (mSecurity == AccessPoint.SECURITY_PSK && mPassword.length() < 8)))) { getButton(BUTTON_SUBMIT).setEnabled(false); } else { getButton(BUTTON_SUBMIT).setEnabled(true); } } public void onClick(View view) { mPassword.setInputType( InputType.TYPE_CLASS_TEXT | (((CheckBox) view).isChecked() ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD : InputType.TYPE_TEXT_VARIATION_PASSWORD)); } public void onTextChanged(CharSequence s, int start, int before, int count) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void afterTextChanged(Editable editable) { validate(); } public void onItemSelected(AdapterView parent, View view, int position, long id) { mSecurity = position; showSecurityFields(); validate(); } public void onNothingSelected(AdapterView parent) { } private void showSecurityFields() { if (mSecurity == AccessPoint.SECURITY_NONE) { mView.findViewById(R.id.fields).setVisibility(View.GONE); return; } mView.findViewById(R.id.fields).setVisibility(View.VISIBLE); if (mPassword == null) { mPassword = (TextView) mView.findViewById(R.id.password); mPassword.addTextChangedListener(this); ((CheckBox) mView.findViewById(R.id.show_password)).setOnClickListener(this); if (mAccessPoint != null && mAccessPoint.networkId != -1) { mPassword.setHint(R.string.wifi_unchanged); } } if (mSecurity != AccessPoint.SECURITY_EAP) { mView.findViewById(R.id.eap).setVisibility(View.GONE); return; } mView.findViewById(R.id.eap).setVisibility(View.VISIBLE); if (mEapMethod == null) { mEapMethod = (Spinner) mView.findViewById(R.id.method); mEapCaCert = (Spinner) mView.findViewById(R.id.ca_cert); mEapUserCert = (Spinner) mView.findViewById(R.id.user_cert); mEapIdentity = (TextView) mView.findViewById(R.id.identity); mEapAnonymous = (TextView) mView.findViewById(R.id.anonymous); loadCertificates(mEapCaCert, Credentials.CA_CERTIFICATE); loadCertificates(mEapUserCert, Credentials.USER_PRIVATE_KEY); if (mAccessPoint != null && mAccessPoint.networkId != -1) { WifiConfiguration config = mAccessPoint.getConfig(); setSelection(mEapMethod, config.eap.value()); setCertificate(mEapCaCert, Credentials.CA_CERTIFICATE, config.ca_cert.value()); setCertificate(mEapUserCert, Credentials.USER_PRIVATE_KEY, config.private_key.value()); mEapIdentity.setText(config.identity.value()); mEapAnonymous.setText(config.anonymous_identity.value()); } } } private void loadCertificates(Spinner spinner, String prefix) { String[] certs = KeyStore.getInstance().saw(prefix); Context context = getContext(); String unspecified = context.getString(R.string.wifi_unspecified); if (certs == null || certs.length == 0) { certs = new String[] {unspecified}; } else { String[] array = new String[certs.length + 1]; array[0] = unspecified; System.arraycopy(certs, 0, array, 1, certs.length); certs = array; } ArrayAdapter<String> adapter = new ArrayAdapter<String>( context, android.R.layout.simple_spinner_item, certs); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } private void setCertificate(Spinner spinner, String prefix, String cert) { prefix = KEYSTORE_SPACE + prefix; if (cert != null && cert.startsWith(prefix)) { setSelection(spinner, cert.substring(prefix.length())); } } private void setSelection(Spinner spinner, String value) { if (value != null) { ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinner.getAdapter(); for (int i = adapter.getCount() - 1; i >= 0; --i) { if (value.equals(adapter.getItem(i))) { spinner.setSelection(i); break; } } } } }
true
true
WifiConfiguration getConfig() { if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) { return null; } WifiConfiguration config = new WifiConfiguration(); if (mAccessPoint == null) { config.SSID = mSsid.getText().toString(); // If the user adds a network manually, assume that it is hidden. config.hiddenSSID = true; } else if (mAccessPoint.networkId == -1) { config.SSID = mAccessPoint.ssid; } else { config.networkId = mAccessPoint.networkId; } switch (mSecurity) { case AccessPoint.SECURITY_NONE: config.allowedKeyManagement.set(KeyMgmt.NONE); return config; case AccessPoint.SECURITY_WEP: config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); if (mPassword.length() != 0) { int length = mPassword.length(); String password = mPassword.getText().toString(); // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) { config.wepKeys[0] = password; } else { config.wepKeys[0] = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_PSK: config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); if (mPassword.length() != 0) { String password = mPassword.getText().toString(); if (password.matches("[0-9A-Fa-f]{64}")) { config.preSharedKey = password; } else { config.preSharedKey = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_EAP: config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); config.eap.setValue((String) mEapMethod.getSelectedItem()); config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.CA_CERTIFICATE + (String) mEapCaCert.getSelectedItem()); config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE + (String) mEapUserCert.getSelectedItem()); config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.PRIVATE_KEY + (String) mEapUserCert.getSelectedItem()); config.identity.setValue((mEapIdentity.length() == 0) ? "" : mEapIdentity.getText().toString()); config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" : mEapAnonymous.getText().toString()); if (mPassword.length() != 0) { config.password.setValue(mPassword.getText().toString()); } return config; } return null; }
WifiConfiguration getConfig() { if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) { return null; } WifiConfiguration config = new WifiConfiguration(); if (mAccessPoint == null) { config.SSID = mSsid.getText().toString(); // If the user adds a network manually, assume that it is hidden. config.hiddenSSID = true; } else if (mAccessPoint.networkId == -1) { config.SSID = mAccessPoint.ssid; } else { config.networkId = mAccessPoint.networkId; } switch (mSecurity) { case AccessPoint.SECURITY_NONE: config.allowedKeyManagement.set(KeyMgmt.NONE); return config; case AccessPoint.SECURITY_WEP: config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); if (mPassword.length() != 0) { int length = mPassword.length(); String password = mPassword.getText().toString(); // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) if ((length == 10 || length == 26 || length == 58) && password.matches("[0-9A-Fa-f]*")) { config.wepKeys[0] = password; } else { config.wepKeys[0] = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_PSK: config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); if (mPassword.length() != 0) { String password = mPassword.getText().toString(); if (password.matches("[0-9A-Fa-f]{64}")) { config.preSharedKey = password; } else { config.preSharedKey = '"' + password + '"'; } } return config; case AccessPoint.SECURITY_EAP: config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); config.eap.setValue((String) mEapMethod.getSelectedItem()); config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.CA_CERTIFICATE + (String) mEapCaCert.getSelectedItem()); config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE + (String) mEapUserCert.getSelectedItem()); config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" : KEYSTORE_SPACE + Credentials.PRIVATE_KEY + (String) mEapUserCert.getSelectedItem()); config.identity.setValue((mEapIdentity.length() == 0) ? "" : mEapIdentity.getText().toString()); config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" : mEapAnonymous.getText().toString()); if (mPassword.length() != 0) { config.password.setValue(mPassword.getText().toString()); } return config; } return null; }
diff --git a/update/org.eclipse.update.core/src/org/eclipse/update/standalone/InstallCommand.java b/update/org.eclipse.update.core/src/org/eclipse/update/standalone/InstallCommand.java index 1f6d82856..d3c1b6a17 100644 --- a/update/org.eclipse.update.core/src/org/eclipse/update/standalone/InstallCommand.java +++ b/update/org.eclipse.update.core/src/org/eclipse/update/standalone/InstallCommand.java @@ -1,253 +1,254 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.update.standalone; import java.io.*; import java.net.*; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.update.configuration.*; import org.eclipse.update.core.*; import org.eclipse.update.internal.configurator.UpdateURLDecoder; import org.eclipse.update.internal.core.*; import org.eclipse.update.internal.operations.*; import org.eclipse.update.internal.search.*; import org.eclipse.update.operations.*; import org.eclipse.update.search.*; /** * Command to install a feature. * <p> * <b>Note:</b> This class/interface is part of an interim API that is still under development and expected to * change significantly before reaching stability. It is being made available at this early stage to solicit feedback * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken * (repeatedly) as the API evolves. * </p> * @since 3.0 */ public class InstallCommand extends ScriptedCommand { private IConfiguredSite targetSite; private UpdateSearchRequest searchRequest; private UpdateSearchResultCollector collector; private URL remoteSiteURL; private String featureId; private String version; public InstallCommand( String featureId, String version, String fromSite, String toSite, String verifyOnly) throws Exception { super(verifyOnly); try { this.featureId = featureId; this.version = version; //PAL foundation this.remoteSiteURL = new URL(UpdateURLDecoder.decode(fromSite, "UTF-8")); //$NON-NLS-1$ // Get site to install to targetSite = getTargetSite(toSite); // if no site, try selecting the site that already has the old feature - targetSite = UpdateUtils.getSiteWithFeature(getConfiguration(), featureId); + if (targetSite == null) + targetSite = UpdateUtils.getSiteWithFeature(getConfiguration(), featureId); // if still no site, pick the product site, if writeable if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isProductSite() && sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // if all else fails, pick the first updateable site if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // are we still checking for sites? forget about it if (targetSite == null) throw Utilities.newCoreException( Policy.bind("Standalone.cannotInstall") + featureId + " " + version, //$NON-NLS-1$ //$NON-NLS-2$ null); UpdateSearchScope searchScope = new UpdateSearchScope(); searchScope.addSearchSite( "remoteSite", //$NON-NLS-1$ remoteSiteURL, new String[0]); searchRequest = new UpdateSearchRequest(new SiteSearchCategory(), searchScope); VersionedIdentifier vid = new VersionedIdentifier(featureId, version); searchRequest.addFilter( new VersionedIdentifiersFilter( new VersionedIdentifier[] { vid })); searchRequest.addFilter(new EnvironmentFilter()); searchRequest.addFilter(new BackLevelFilter()); collector = new UpdateSearchResultCollector(); } catch (MalformedURLException e) { throw e; } catch (CoreException e) { throw e; } } /** */ public boolean run(IProgressMonitor monitor) { try { monitor.beginTask(Policy.bind("Standalone.installing"), 4); //$NON-NLS-1$ searchRequest.performSearch(collector, new SubProgressMonitor(monitor,1)); IInstallFeatureOperation[] operations = collector.getOperations(); if (operations == null || operations.length == 0) { throw Utilities.newCoreException( Policy.bind("Standalone.feature") //$NON-NLS-1$ + featureId + " " //$NON-NLS-1$ + version + Policy.bind("Standalone.notFound") //$NON-NLS-1$ + remoteSiteURL + Policy.bind("Standalone.newerInstalled"), //$NON-NLS-1$ null); } // Check for duplication conflicts ArrayList conflicts = DuplicateConflictsValidator.computeDuplicateConflicts( operations, getConfiguration()); if (conflicts != null) { throw Utilities.newCoreException(Policy.bind("Standalone.duplicate"), null); //$NON-NLS-1$ } if (isVerifyOnly()) { if (operations == null || operations.length == 0) return false; IStatus status = OperationsManager.getValidator().validatePendingChanges(operations); if (status != null && status.getCode() == IStatus.ERROR) throw new CoreException(status); else return true; } IBatchOperation installOperation = OperationsManager .getOperationFactory() .createBatchInstallOperation( operations); try { installOperation.execute(new SubProgressMonitor(monitor,3), this); System.out.println( Policy.bind("Standalone.feature") //$NON-NLS-1$ + featureId + " " //$NON-NLS-1$ + version + Policy.bind("Standalone.installed")); //$NON-NLS-1$ return true; } catch (Exception e) { throw Utilities.newCoreException( Policy.bind("Standalone.cannotInstall") + featureId + " " + version, //$NON-NLS-1$ //$NON-NLS-2$ e); } } catch (CoreException ce) { StandaloneUpdateApplication.exceptionLogged(); UpdateCore.log(ce); return false; } finally { monitor.done(); } } private IConfiguredSite getTargetSite(String toSite) throws Exception { if (toSite == null) return null; IConfiguredSite[] configuredSites = getConfiguration().getConfiguredSites(); File sitePath = new File(toSite); File secondaryPath = sitePath.getName().equals("eclipse") ? // $NON-NLS-1$ null : new File(sitePath, "eclipse"); // $NON-NLS-1$ for (int i = 0; i < configuredSites.length; i++) { IConfiguredSite csite = configuredSites[i]; if (csite.getSite().getURL().sameFile(sitePath.toURL())) return csite; else if (secondaryPath != null && csite.getSite().getURL().sameFile(secondaryPath.toURL())) return csite; } // extension site not found, need to create one if (!sitePath.exists()) sitePath.mkdirs(); URL toSiteURL = sitePath.toURL(); ISite site = SiteManager.getSite(toSiteURL, null); if (site == null) { throw new Exception(Policy.bind("Standalone.noSite") + toSite); //$NON-NLS-1$ } IConfiguredSite csite = site.getCurrentConfiguredSite(); if (csite == null) { csite = getConfiguration().createConfiguredSite(sitePath); IStatus status = csite.verifyUpdatableStatus(); if (status.isOK()) getConfiguration().addConfiguredSite(csite); else throw new CoreException(status); return csite; } return csite; } class UpdateSearchResultCollector implements IUpdateSearchResultCollector { private ArrayList operations = new ArrayList(); public void accept(IFeature feature) { if (feature .getVersionedIdentifier() .getIdentifier() .equals(featureId) && feature .getVersionedIdentifier() .getVersion() .toString() .equals( version)) { operations.add( OperationsManager .getOperationFactory() .createInstallOperation( targetSite, feature, null, null, null)); } } public IInstallFeatureOperation[] getOperations() { IInstallFeatureOperation[] opsArray = new IInstallFeatureOperation[operations.size()]; operations.toArray(opsArray); return opsArray; } } }
true
true
public InstallCommand( String featureId, String version, String fromSite, String toSite, String verifyOnly) throws Exception { super(verifyOnly); try { this.featureId = featureId; this.version = version; //PAL foundation this.remoteSiteURL = new URL(UpdateURLDecoder.decode(fromSite, "UTF-8")); //$NON-NLS-1$ // Get site to install to targetSite = getTargetSite(toSite); // if no site, try selecting the site that already has the old feature targetSite = UpdateUtils.getSiteWithFeature(getConfiguration(), featureId); // if still no site, pick the product site, if writeable if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isProductSite() && sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // if all else fails, pick the first updateable site if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // are we still checking for sites? forget about it if (targetSite == null) throw Utilities.newCoreException( Policy.bind("Standalone.cannotInstall") + featureId + " " + version, //$NON-NLS-1$ //$NON-NLS-2$ null); UpdateSearchScope searchScope = new UpdateSearchScope(); searchScope.addSearchSite( "remoteSite", //$NON-NLS-1$ remoteSiteURL, new String[0]); searchRequest = new UpdateSearchRequest(new SiteSearchCategory(), searchScope); VersionedIdentifier vid = new VersionedIdentifier(featureId, version); searchRequest.addFilter( new VersionedIdentifiersFilter( new VersionedIdentifier[] { vid })); searchRequest.addFilter(new EnvironmentFilter()); searchRequest.addFilter(new BackLevelFilter()); collector = new UpdateSearchResultCollector(); } catch (MalformedURLException e) { throw e; } catch (CoreException e) { throw e; } }
public InstallCommand( String featureId, String version, String fromSite, String toSite, String verifyOnly) throws Exception { super(verifyOnly); try { this.featureId = featureId; this.version = version; //PAL foundation this.remoteSiteURL = new URL(UpdateURLDecoder.decode(fromSite, "UTF-8")); //$NON-NLS-1$ // Get site to install to targetSite = getTargetSite(toSite); // if no site, try selecting the site that already has the old feature if (targetSite == null) targetSite = UpdateUtils.getSiteWithFeature(getConfiguration(), featureId); // if still no site, pick the product site, if writeable if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isProductSite() && sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // if all else fails, pick the first updateable site if (targetSite == null) { IConfiguredSite[] sites = getConfiguration().getConfiguredSites(); for (int i = 0; i < sites.length; i++) { if (sites[i].isUpdatable()) { targetSite = sites[i]; break; } } } // are we still checking for sites? forget about it if (targetSite == null) throw Utilities.newCoreException( Policy.bind("Standalone.cannotInstall") + featureId + " " + version, //$NON-NLS-1$ //$NON-NLS-2$ null); UpdateSearchScope searchScope = new UpdateSearchScope(); searchScope.addSearchSite( "remoteSite", //$NON-NLS-1$ remoteSiteURL, new String[0]); searchRequest = new UpdateSearchRequest(new SiteSearchCategory(), searchScope); VersionedIdentifier vid = new VersionedIdentifier(featureId, version); searchRequest.addFilter( new VersionedIdentifiersFilter( new VersionedIdentifier[] { vid })); searchRequest.addFilter(new EnvironmentFilter()); searchRequest.addFilter(new BackLevelFilter()); collector = new UpdateSearchResultCollector(); } catch (MalformedURLException e) { throw e; } catch (CoreException e) { throw e; } }
diff --git a/idm/impl/src/test/java/org/picketlink/test/idm/query/AgentQueryTestCase.java b/idm/impl/src/test/java/org/picketlink/test/idm/query/AgentQueryTestCase.java index bc5aed926..dd852d824 100644 --- a/idm/impl/src/test/java/org/picketlink/test/idm/query/AgentQueryTestCase.java +++ b/idm/impl/src/test/java/org/picketlink/test/idm/query/AgentQueryTestCase.java @@ -1,850 +1,850 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.picketlink.test.idm.query; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import java.util.Calendar; import java.util.Date; import java.util.List; import org.junit.Test; import org.picketlink.idm.IdentityManager; import org.picketlink.idm.model.Agent; import org.picketlink.idm.model.Attribute; import org.picketlink.idm.model.Group; import org.picketlink.idm.model.GroupRole; import org.picketlink.idm.model.IdentityType; import org.picketlink.idm.model.Realm; import org.picketlink.idm.model.Role; import org.picketlink.idm.model.SimpleAgent; import org.picketlink.idm.query.IdentityQuery; import org.picketlink.test.idm.AbstractIdentityManagerTestCase; /** * <p> * Test case for the Query API when retrieving {@link Agent} instances. * * @author <a href="mailto:[email protected]">Pedro Silva</a> * */ public class AgentQueryTestCase extends AbstractIdentityManagerTestCase { @Test public void testFindById() throws Exception { Agent agent = createAgent("someAgent"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.ID, agent.getId()); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(result.size() == 1); assertEquals(agent.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindByRealm() throws Exception { IdentityManager identityManager = getIdentityManager(); Agent someAgentDefaultRealm = new SimpleAgent("someAgentRealm"); identityManager.add(someAgentDefaultRealm); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); Realm defaultRealm = identityManager.getRealm(Realm.DEFAULT_REALM); assertNotNull(defaultRealm); query.setParameter(Agent.PARTITION, defaultRealm); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgentDefaultRealm.getLoginName())); Realm testingRealm = identityManager.getRealm("Testing"); if (testingRealm == null) { testingRealm = new Realm("Testing"); identityManager.createRealm(testingRealm); } Agent someAgentTestingRealm = new SimpleAgent("someAgentTestingRealm"); identityManager.forRealm(testingRealm).add(someAgentTestingRealm); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.PARTITION, testingRealm); result = query.getResultList(); assertFalse(result.isEmpty()); assertFalse(contains(result, someAgentDefaultRealm.getLoginName())); assertTrue(contains(result, someAgentTestingRealm.getLoginName())); } @Test public void testFindByLoginName() throws Exception { createAgent("someAgent"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.LOGIN_NAME, "someAgent"); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(result.size() == 1); assertEquals("someAgent", result.get(0).getLoginName()); } @Test public void testFindBySingleGroupRole() throws Exception { Agent user = createAgent("someAgent"); Group salesGroup = createGroup("Sales", null); Role managerRole = createRole("Manager"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_GROUP_ROLE, new GroupRole[] { new GroupRole(user, salesGroup, managerRole) }); List<Agent> result = query.getResultList(); assertTrue(result.isEmpty()); identityManager.grantGroupRole(user, managerRole, salesGroup); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_GROUP_ROLE, new GroupRole[] { new GroupRole(user, salesGroup, managerRole) }); result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindBySingleGroup() throws Exception { Agent user = createAgent("admin"); Group administratorGroup = createGroup("Administrators", null); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { "Administrators" }); List<Agent> result = query.getResultList(); assertTrue(result.isEmpty()); identityManager.addToGroup(user, administratorGroup); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { "Administrators" }); result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindBySingleRole() throws Exception { Agent user = createAgent("admin"); Role administratorRole = createRole("Administrators"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { "Administrators" }); List<Agent> result = query.getResultList(); assertTrue(result.isEmpty()); identityManager.grantRole(user, administratorRole); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { "Administrators" }); result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindByMultipleGroups() throws Exception { Agent user = createAgent("admin"); Group administratorGroup = createGroup("Administrators", null); Group someGroup = createGroup("someGroup", null); IdentityManager identityManager = getIdentityManager(); identityManager.addToGroup(user, administratorGroup); identityManager.addToGroup(user, someGroup); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { administratorGroup.getName(), someGroup.getName() }); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); identityManager.removeFromGroup(user, someGroup); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { administratorGroup.getName(), someGroup.getName() }); result = query.getResultList(); assertTrue(result.isEmpty()); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { administratorGroup.getName() }); result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindByMultipleRoles() throws Exception { Agent user = createAgent("admin"); Role administratorRole = createRole("Administrators"); Role someRole = createRole("someRole"); IdentityManager identityManager = getIdentityManager(); identityManager.grantRole(user, administratorRole); identityManager.grantRole(user, someRole); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { administratorRole.getName(), someRole.getName() }); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); identityManager.revokeRole(user, someRole); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { administratorRole.getName(), someRole.getName() }); result = query.getResultList(); assertTrue(result.isEmpty()); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { administratorRole.getName() }); result = query.getResultList(); assertFalse(result.isEmpty()); assertEquals(user.getLoginName(), result.get(0).getLoginName()); } @Test public void testFindByMultipleAgentWithGroups() throws Exception { Agent adminAgent = createAgent("admin"); Agent someAgent = createAgent("someAgent"); Group administratorGroup = createGroup("Administrators", null); Group someGroup = createGroup("someGroup", null); IdentityManager identityManager = getIdentityManager(); identityManager.addToGroup(adminAgent, administratorGroup); identityManager.addToGroup(someAgent, administratorGroup); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { administratorGroup.getName() }); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, adminAgent.getLoginName())); assertTrue(contains(result, someAgent.getLoginName())); identityManager.addToGroup(adminAgent, someGroup); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.MEMBER_OF, new String[] { administratorGroup.getName(), someGroup.getName() }); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, adminAgent.getLoginName())); assertFalse(contains(result, someAgent.getLoginName())); } @Test public void testFindByMultipleAgentWithRoles() throws Exception { Agent adminAgent = createAgent("admin"); Agent someAgent = createAgent("someAgent"); Role administratorRole = createRole("Administrators"); Role someRole = createRole("someRole"); IdentityManager identityManager = getIdentityManager(); identityManager.grantRole(adminAgent, administratorRole); identityManager.grantRole(someAgent, administratorRole); IdentityQuery<Agent> query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { administratorRole.getName() }); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, adminAgent.getLoginName())); assertTrue(contains(result, someAgent.getLoginName())); identityManager.grantRole(adminAgent, someRole); query = identityManager.createIdentityQuery(Agent.class); query.setParameter(Agent.HAS_ROLE, new String[] { administratorRole.getName(), someRole.getName() }); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, adminAgent.getLoginName())); assertFalse(contains(result, someAgent.getLoginName())); } @Test public void testFindEnabledAndDisabledAgents() throws Exception { Agent someAgent = createAgent("someAgent"); Agent someAnotherAgent = createAgent("someAnotherAgent"); someAgent.setEnabled(true); someAnotherAgent.setEnabled(true); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); identityManager.update(someAnotherAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.ENABLED, true); // all enabled users List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.ENABLED, false); // only disabled users. No users are disabled. result = query.getResultList(); assertFalse(contains(result, someAgent.getLoginName())); assertFalse(contains(result, someAnotherAgent.getLoginName())); someAgent.setEnabled(false); // let's disabled the user and try to find him identityManager.update(someAgent); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.ENABLED, false); // get the previously disabled user result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertFalse(contains(result, someAnotherAgent.getLoginName())); someAnotherAgent.setEnabled(false); // let's disabled the user and try to find him identityManager.update(someAnotherAgent); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.ENABLED, true); result = query.getResultList(); assertFalse(contains(result, someAgent.getLoginName())); assertFalse(contains(result, someAnotherAgent.getLoginName())); } @Test public void testFindCreationDate() throws Exception { Agent user = createAgent("someAgent"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.CREATED_DATE, user.getCreatedDate()); // only the previously created user List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(result.size() == 1); assertEquals("someAgent", result.get(0).getLoginName()); query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar futureDate = Calendar.getInstance(); futureDate.add(Calendar.MINUTE, 1); query.setParameter(Agent.CREATED_DATE, futureDate.getTime()); // no users result = query.getResultList(); assertTrue(result.isEmpty()); } @Test public void testFindExpiryDate() throws Exception { Agent user = createAgent("someAgent"); Date expirationDate = new Date(); IdentityManager identityManager = getIdentityManager(); user = identityManager.getAgent("someAgent"); user.setExpirationDate(expirationDate); identityManager.update(user); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.EXPIRY_DATE, user.getExpirationDate()); // all expired users List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, user.getLoginName())); assertEquals("someAgent", result.get(0).getLoginName()); query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); query.setParameter(Agent.EXPIRY_DATE, calendar.getTime()); // no users result = query.getResultList(); assertTrue(result.isEmpty()); } @Test public void testFindBetweenCreationDate() throws Exception { Agent someAgent = createAgent("someAgent"); Agent someAnotherAgent = createAgent("someAnotherAgent"); IdentityManager identityManager = getIdentityManager(); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); // users between the given time period query.setParameter(Agent.CREATED_AFTER, calendar.getTime()); query.setParameter(Agent.CREATED_BEFORE, new Date()); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); Agent someFutureAgent = createAgent("someFutureAgent"); Agent someAnotherFutureAgent = createAgent("someAnotherFutureAgent"); // users created after the given time query.setParameter(Agent.CREATED_AFTER, calendar.getTime()); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); // users created before the given time query.setParameter(Agent.CREATED_BEFORE, new Date()); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); query.setParameter(Agent.CREATED_AFTER, calendar.getTime()); result = query.getResultList(); assertTrue(result.isEmpty()); } @Test public void testFindUsingMultipleParameters() throws Exception { Agent user = createAgent("admin"); IdentityManager identityManager = getIdentityManager(); identityManager.update(user); user.setAttribute(new Attribute<String>("someAttribute", "someAttributeValue")); identityManager.update(user); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue"); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, user.getLoginName())); assertEquals(1, result.size()); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(Agent.LOGIN_NAME, "admin"); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue2"); result = query.getResultList(); assertTrue(result.isEmpty()); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue"); query.setParameter(Agent.LOGIN_NAME, "admin"); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, user.getLoginName())); assertEquals(1, result.size()); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue"); query.setParameter(Agent.LOGIN_NAME, "Bad ID"); result = query.getResultList(); assertTrue(result.isEmpty()); } @Test public void testFindBetweenExpirationDate() throws Exception { Agent someAgent = createAgent("someAgent"); Date currentDate = new Date(); someAgent.setExpirationDate(currentDate); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); Agent someAnotherAgent = createAgent("someAnotherAgent"); someAnotherAgent.setExpirationDate(currentDate); identityManager.update(someAnotherAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); Date expiryDate = calendar.getTime(); // users between the given time period query.setParameter(Agent.EXPIRY_AFTER, expiryDate); query.setParameter(Agent.EXPIRY_BEFORE, currentDate); Agent someFutureAgent = createAgent("someFutureAgent"); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); someFutureAgent.setExpirationDate(calendar.getTime()); identityManager.update(someFutureAgent); Agent someAnotherFutureAgent = createAgent("someAnotherFutureAgent"); someAnotherFutureAgent.setExpirationDate(new Date()); identityManager.update(someAnotherFutureAgent); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertFalse(contains(result, someFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); // users expired after the given time query.setParameter(Agent.EXPIRY_AFTER, expiryDate); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); // users expired before the given time query.setParameter(Agent.EXPIRY_BEFORE, calendar.getTime()); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); - calendar.add(Calendar.MINUTE, 1); + calendar.add(Calendar.MINUTE, 2); // users expired after the given time. Should return an empty list. query.setParameter(Agent.EXPIRY_AFTER, calendar.getTime()); result = query.getResultList(); assertTrue(result.isEmpty()); } @Test public void testFindByAgentDefinedAttributes() throws Exception { Agent someAgent = createAgent("someAgent"); someAgent.setAttribute(new Attribute<String>("someAttribute", "someAttributeValue")); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue"); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); someAgent.setAttribute(new Attribute<String>("someAttribute", "someAttributeValueChanged")); identityManager.update(someAgent); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValue"); result = query.getResultList(); assertFalse(contains(result, someAgent.getLoginName())); someAgent.setAttribute(new Attribute<String>("someAttribute2", "someAttributeValue2")); identityManager.update(someAgent); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), "someAttributeValueChanged"); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute2"), "someAttributeValue2"); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); } @Test public void testFindByAgentDefinedMultiValuedAttributes() throws Exception { Agent someAgent = createAgent("someAgent"); someAgent.setAttribute(new Attribute<String[]>("someAttribute", new String[] { "someAttributeValue1", "someAttributeValue2" })); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), new Object[] { "someAttributeValue1", "someAttributeValue2" }); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute2"), new Object[] { "someAttributeValue1", "someAttributeValue2" }); result = query.getResultList(); assertTrue(result.isEmpty()); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), new Object[] { "someAttributeValueChanged", "someAttributeValue2" }); result = query.getResultList(); assertTrue(result.isEmpty()); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), new Object[] { "someAttributeValue" }); result = query.getResultList(); assertFalse(contains(result, someAgent.getLoginName())); someAgent.setAttribute(new Attribute<String[]>("someAttribute", new String[] { "someAttributeValue1", "someAttributeValueChanged" })); someAgent.setAttribute(new Attribute<String[]>("someAttribute2", new String[] { "someAttribute2Value1", "someAttribute2Value2" })); identityManager.update(someAgent); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), new Object[] { "someAttributeValue1", "someAttributeValueChanged" }); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute2"), new Object[] { "someAttribute2Value1", "someAttribute2Value2" }); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute"), new Object[] { "someAttributeValue1", "someAttributeValueChanged" }); query.setParameter(IdentityType.ATTRIBUTE.byName("someAttribute2"), new Object[] { "someAttribute2ValueChanged", "someAttribute2Value2" }); result = query.getResultList(); assertTrue(result.isEmpty()); } private boolean contains(List<Agent> result, String userId) { for (Agent resultAgent : result) { if (resultAgent.getLoginName().equals(userId)) { return true; } } return false; } }
true
true
public void testFindBetweenExpirationDate() throws Exception { Agent someAgent = createAgent("someAgent"); Date currentDate = new Date(); someAgent.setExpirationDate(currentDate); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); Agent someAnotherAgent = createAgent("someAnotherAgent"); someAnotherAgent.setExpirationDate(currentDate); identityManager.update(someAnotherAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); Date expiryDate = calendar.getTime(); // users between the given time period query.setParameter(Agent.EXPIRY_AFTER, expiryDate); query.setParameter(Agent.EXPIRY_BEFORE, currentDate); Agent someFutureAgent = createAgent("someFutureAgent"); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); someFutureAgent.setExpirationDate(calendar.getTime()); identityManager.update(someFutureAgent); Agent someAnotherFutureAgent = createAgent("someAnotherFutureAgent"); someAnotherFutureAgent.setExpirationDate(new Date()); identityManager.update(someAnotherFutureAgent); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertFalse(contains(result, someFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); // users expired after the given time query.setParameter(Agent.EXPIRY_AFTER, expiryDate); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); // users expired before the given time query.setParameter(Agent.EXPIRY_BEFORE, calendar.getTime()); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); // users expired after the given time. Should return an empty list. query.setParameter(Agent.EXPIRY_AFTER, calendar.getTime()); result = query.getResultList(); assertTrue(result.isEmpty()); }
public void testFindBetweenExpirationDate() throws Exception { Agent someAgent = createAgent("someAgent"); Date currentDate = new Date(); someAgent.setExpirationDate(currentDate); IdentityManager identityManager = getIdentityManager(); identityManager.update(someAgent); Agent someAnotherAgent = createAgent("someAnotherAgent"); someAnotherAgent.setExpirationDate(currentDate); identityManager.update(someAnotherAgent); IdentityQuery<Agent> query = identityManager.<Agent> createIdentityQuery(Agent.class); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -1); Date expiryDate = calendar.getTime(); // users between the given time period query.setParameter(Agent.EXPIRY_AFTER, expiryDate); query.setParameter(Agent.EXPIRY_BEFORE, currentDate); Agent someFutureAgent = createAgent("someFutureAgent"); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); someFutureAgent.setExpirationDate(calendar.getTime()); identityManager.update(someFutureAgent); Agent someAnotherFutureAgent = createAgent("someAnotherFutureAgent"); someAnotherFutureAgent.setExpirationDate(new Date()); identityManager.update(someAnotherFutureAgent); List<Agent> result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertFalse(contains(result, someFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); // users expired after the given time query.setParameter(Agent.EXPIRY_AFTER, expiryDate); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 1); // users expired before the given time query.setParameter(Agent.EXPIRY_BEFORE, calendar.getTime()); result = query.getResultList(); assertFalse(result.isEmpty()); assertTrue(contains(result, someAgent.getLoginName())); assertTrue(contains(result, someAnotherAgent.getLoginName())); assertTrue(contains(result, someFutureAgent.getLoginName())); assertTrue(contains(result, someAnotherFutureAgent.getLoginName())); query = identityManager.<Agent> createIdentityQuery(Agent.class); calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 2); // users expired after the given time. Should return an empty list. query.setParameter(Agent.EXPIRY_AFTER, calendar.getTime()); result = query.getResultList(); assertTrue(result.isEmpty()); }
diff --git a/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java b/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java index ee4f3ff5e..a9ed4f515 100644 --- a/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java +++ b/src/org/apache/xerces/jaxp/validation/ValidatorHandlerImpl.java @@ -1,1139 +1,1139 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.jaxp.validation; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import javax.xml.validation.TypeInfoProvider; import javax.xml.validation.ValidatorHandler; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.validation.EntityState; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.xs.XMLSchemaValidator; import org.apache.xerces.util.AttributesProxy; import org.apache.xerces.util.SAXLocatorWrapper; import org.apache.xerces.util.SAXMessageFormatter; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.URI; import org.apache.xerces.util.XMLAttributesImpl; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLParseException; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.ItemPSVI; import org.apache.xerces.xs.PSVIProvider; import org.apache.xerces.xs.XSTypeDefinition; import org.w3c.dom.TypeInfo; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.ext.Attributes2; import org.xml.sax.ext.EntityResolver2; import org.xml.sax.ext.LexicalHandler; /** * <p>Implementation of ValidatorHandler for W3C XML Schemas and * also a validator helper for <code>SAXSource</code>s.</p> * * @author Kohsuke Kawaguchi ([email protected]) * @author Michael Glavassevich, IBM * * @version $Id$ */ final class ValidatorHandlerImpl extends ValidatorHandler implements DTDHandler, EntityState, PSVIProvider, ValidatorHelper, XMLDocumentHandler { // feature identifiers /** Feature identifier: namespace prefixes. */ private static final String NAMESPACE_PREFIXES = Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE; /** Feature identifier: string interning. */ private static final String STRING_INTERNING = Constants.SAX_FEATURE_PREFIX + Constants.STRING_INTERNING_FEATURE; /** Feature identifier: strings interned. */ private static final String STRINGS_INTERNED = Constants.XERCES_FEATURE_PREFIX + Constants.STRINGS_INTERNED_FEATURE; // property identifiers /** Property identifier: error reporter. */ private static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: lexical handler. */ private static final String LEXICAL_HANDLER = Constants.SAX_PROPERTY_PREFIX + Constants.LEXICAL_HANDLER_PROPERTY; /** Property identifier: namespace context. */ private static final String NAMESPACE_CONTEXT = Constants.XERCES_PROPERTY_PREFIX + Constants.NAMESPACE_CONTEXT_PROPERTY; /** Property identifier: XML Schema validator. */ private static final String SCHEMA_VALIDATOR = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; /** Property identifier: security manager. */ private static final String SECURITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; /** Property identifier: symbol table. */ private static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: validation manager. */ private static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; // // Data // /** Error reporter. */ private final XMLErrorReporter fErrorReporter; /** The namespace context of this document: stores namespaces in scope */ private final NamespaceContext fNamespaceContext; /** Schema validator. **/ private final XMLSchemaValidator fSchemaValidator; /** Symbol table **/ private final SymbolTable fSymbolTable; /** Validation manager. */ private final ValidationManager fValidationManager; /** Component manager. **/ private final XMLSchemaValidatorComponentManager fComponentManager; /** XML Locator wrapper for SAX. **/ private final SAXLocatorWrapper fSAXLocatorWrapper = new SAXLocatorWrapper(); /** Flag used to track whether the namespace context needs to be pushed. */ private boolean fNeedPushNSContext = true; /** Map for tracking unparsed entities. */ private HashMap fUnparsedEntities = null; /** Flag used to track whether XML names and Namespace URIs have been internalized. */ private boolean fStringsInternalized = false; /** Fields for start element, end element and characters. */ private final QName fElementQName = new QName(); private final QName fAttributeQName = new QName(); private final XMLAttributesImpl fAttributes = new XMLAttributesImpl(); private final AttributesProxy fAttrAdapter = new AttributesProxy(fAttributes); private final XMLString fTempString = new XMLString(); // // User Objects // private ContentHandler fContentHandler = null; /* * Constructors */ public ValidatorHandlerImpl(XSGrammarPoolContainer grammarContainer) { this(new XMLSchemaValidatorComponentManager(grammarContainer)); fComponentManager.addRecognizedFeatures(new String [] {NAMESPACE_PREFIXES}); fComponentManager.setFeature(NAMESPACE_PREFIXES, false); setErrorHandler(null); setResourceResolver(null); } public ValidatorHandlerImpl(XMLSchemaValidatorComponentManager componentManager) { fComponentManager = componentManager; fErrorReporter = (XMLErrorReporter) fComponentManager.getProperty(ERROR_REPORTER); fNamespaceContext = (NamespaceContext) fComponentManager.getProperty(NAMESPACE_CONTEXT); fSchemaValidator = (XMLSchemaValidator) fComponentManager.getProperty(SCHEMA_VALIDATOR); fSymbolTable = (SymbolTable) fComponentManager.getProperty(SYMBOL_TABLE); fValidationManager = (ValidationManager) fComponentManager.getProperty(VALIDATION_MANAGER); } /* * ValidatorHandler methods */ public void setContentHandler(ContentHandler receiver) { fContentHandler = receiver; } public ContentHandler getContentHandler() { return fContentHandler; } public void setErrorHandler(ErrorHandler errorHandler) { fComponentManager.setErrorHandler(errorHandler); } public ErrorHandler getErrorHandler() { return fComponentManager.getErrorHandler(); } public void setResourceResolver(LSResourceResolver resourceResolver) { fComponentManager.setResourceResolver(resourceResolver); } public LSResourceResolver getResourceResolver() { return fComponentManager.getResourceResolver(); } public TypeInfoProvider getTypeInfoProvider() { return fTypeInfoProvider; } public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { if (name == null) { throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "FeatureNameNull", null)); } if (STRINGS_INTERNED.equals(name)) { return fStringsInternalized; } try { return fComponentManager.getFeature(name); } catch (XMLConfigurationException e) { final String identifier = e.getIdentifier(); if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) { throw new SAXNotRecognizedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "feature-not-recognized", new Object [] {identifier})); } else { throw new SAXNotSupportedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "feature-not-supported", new Object [] {identifier})); } } } public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { if (name == null) { throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "FeatureNameNull", null)); } if (STRINGS_INTERNED.equals(name)) { fStringsInternalized = value; return; } try { fComponentManager.setFeature(name, value); } catch (XMLConfigurationException e) { final String identifier = e.getIdentifier(); if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) { throw new SAXNotRecognizedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "feature-not-recognized", new Object [] {identifier})); } else { throw new SAXNotSupportedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "feature-not-supported", new Object [] {identifier})); } } } public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { if (name == null) { throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "ProperyNameNull", null)); } try { return fComponentManager.getProperty(name); } catch (XMLConfigurationException e) { final String identifier = e.getIdentifier(); if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) { throw new SAXNotRecognizedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "property-not-recognized", new Object [] {identifier})); } else { throw new SAXNotSupportedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "property-not-supported", new Object [] {identifier})); } } } public void setProperty(String name, Object object) throws SAXNotRecognizedException, SAXNotSupportedException { if (name == null) { throw new NullPointerException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "ProperyNameNull", null)); } try { fComponentManager.setProperty(name, object); } catch (XMLConfigurationException e) { final String identifier = e.getIdentifier(); if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) { throw new SAXNotRecognizedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "property-not-recognized", new Object [] {identifier})); } else { throw new SAXNotSupportedException( SAXMessageFormatter.formatMessage(fComponentManager.getLocale(), "property-not-supported", new Object [] {identifier})); } } } /* * EntityState methods */ public boolean isEntityDeclared(String name) { return false; } public boolean isEntityUnparsed(String name) { if (fUnparsedEntities != null) { return fUnparsedEntities.containsKey(name); } return false; } /* * XMLDocumentHandler methods */ public void startDocument(XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fContentHandler.startDocument(); } catch (SAXException e) { throw new XNIException(e); } } } public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException {} public void doctypeDecl(String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException {} public void comment(XMLString text, Augmentations augs) throws XNIException {} public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fContentHandler.processingInstruction(target, data.toString()); } catch (SAXException e) { throw new XNIException(e); } } } public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fTypeInfoProvider.beginStartElement(augs, attributes); fContentHandler.startElement((element.uri != null) ? element.uri : XMLSymbols.EMPTY_STRING, element.localpart, element.rawname, fAttrAdapter); } catch (SAXException e) { throw new XNIException(e); } finally { fTypeInfoProvider.finishStartElement(); } } } public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { /** Split empty element event. **/ startElement(element, attributes, augs); endElement(element, augs); } public void startGeneralEntity(String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException {} public void textDecl(String version, String encoding, Augmentations augs) throws XNIException {} public void endGeneralEntity(String name, Augmentations augs) throws XNIException {} public void characters(XMLString text, Augmentations augs) throws XNIException { if (fContentHandler != null) { // if the type is union it is possible that we receive // a character call with empty data if (text.length == 0) { return; } try { fContentHandler.characters(text.ch, text.offset, text.length); } catch (SAXException e) { throw new XNIException(e); } } } public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fContentHandler.ignorableWhitespace(text.ch, text.offset, text.length); } catch (SAXException e) { throw new XNIException(e); } } } public void endElement(QName element, Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fTypeInfoProvider.beginEndElement(augs); fContentHandler.endElement((element.uri != null) ? element.uri : XMLSymbols.EMPTY_STRING, element.localpart, element.rawname); } catch (SAXException e) { throw new XNIException(e); } finally { fTypeInfoProvider.finishEndElement(); } } } public void startCDATA(Augmentations augs) throws XNIException {} public void endCDATA(Augmentations augs) throws XNIException {} public void endDocument(Augmentations augs) throws XNIException { if (fContentHandler != null) { try { fContentHandler.endDocument(); } catch (SAXException e) { throw new XNIException(e); } } } // NO-OP public void setDocumentSource(XMLDocumentSource source) {} public XMLDocumentSource getDocumentSource() { return fSchemaValidator; } /* * ContentHandler methods */ public void setDocumentLocator(Locator locator) { fSAXLocatorWrapper.setLocator(locator); if (fContentHandler != null) { fContentHandler.setDocumentLocator(locator); } } public void startDocument() throws SAXException { fComponentManager.reset(); fSchemaValidator.setDocumentHandler(this); fValidationManager.setEntityState(this); fTypeInfoProvider.finishStartElement(); // cleans up TypeInfoProvider fNeedPushNSContext = true; if (fUnparsedEntities != null && !fUnparsedEntities.isEmpty()) { // should only clear this if the last document contained unparsed entities fUnparsedEntities.clear(); } fErrorReporter.setDocumentLocator(fSAXLocatorWrapper); try { fSchemaValidator.startDocument(fSAXLocatorWrapper, fSAXLocatorWrapper.getEncoding(), fNamespaceContext, null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } } public void endDocument() throws SAXException { fSAXLocatorWrapper.setLocator(null); try { fSchemaValidator.endDocument(null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { String prefixSymbol; String uriSymbol; if (!fStringsInternalized) { prefixSymbol = (prefix != null) ? fSymbolTable.addSymbol(prefix) : XMLSymbols.EMPTY_STRING; uriSymbol = (uri != null && uri.length() > 0) ? fSymbolTable.addSymbol(uri) : null; } else { prefixSymbol = (prefix != null) ? prefix : XMLSymbols.EMPTY_STRING; uriSymbol = (uri != null && uri.length() > 0) ? uri : null; } if (fNeedPushNSContext) { fNeedPushNSContext = false; fNamespaceContext.pushContext(); } fNamespaceContext.declarePrefix(prefixSymbol, uriSymbol); if (fContentHandler != null) { fContentHandler.startPrefixMapping(prefix, uri); } } public void endPrefixMapping(String prefix) throws SAXException { if (fContentHandler != null) { fContentHandler.endPrefixMapping(prefix); } } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (fNeedPushNSContext) { fNamespaceContext.pushContext(); } fNeedPushNSContext = true; // Fill element QName fillQName(fElementQName, uri, localName, qName); // Fill XMLAttributes if (atts instanceof Attributes2) { fillXMLAttributes2((Attributes2) atts); } else { fillXMLAttributes(atts); } try { fSchemaValidator.startElement(fElementQName, fAttributes, null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } } public void endElement(String uri, String localName, String qName) throws SAXException { fillQName(fElementQName, uri, localName, qName); try { fSchemaValidator.endElement(fElementQName, null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } finally { fNamespaceContext.popContext(); } } public void characters(char[] ch, int start, int length) throws SAXException { try { fTempString.setValues(ch, start, length); fSchemaValidator.characters(fTempString, null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { try { fTempString.setValues(ch, start, length); fSchemaValidator.ignorableWhitespace(fTempString, null); } catch (XMLParseException e) { throw Util.toSAXParseException(e); } catch (XNIException e) { throw Util.toSAXException(e); } } public void processingInstruction(String target, String data) throws SAXException { /** * Processing instructions do not participate in schema validation, * so just forward the event to the application's content * handler. */ if (fContentHandler != null) { fContentHandler.processingInstruction(target, data); } } public void skippedEntity(String name) throws SAXException { // there seems to be no corresponding method on XMLDocumentFilter. // just pass it down to the output, if any. if (fContentHandler != null) { fContentHandler.skippedEntity(name); } } /* * DTDHandler methods */ public void notationDecl(String name, String publicId, String systemId) throws SAXException {} public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (fUnparsedEntities == null) { fUnparsedEntities = new HashMap(); } fUnparsedEntities.put(name, name); } /* * ValidatorHelper methods */ public void validate(Source source, Result result) throws SAXException, IOException { if (result instanceof SAXResult || result == null) { final SAXSource saxSource = (SAXSource) source; final SAXResult saxResult = (SAXResult) result; LexicalHandler lh = null; if (result != null) { ContentHandler ch = saxResult.getHandler(); lh = saxResult.getLexicalHandler(); /** If the lexical handler is not set try casting the ContentHandler. **/ if (lh == null && ch instanceof LexicalHandler) { lh = (LexicalHandler) ch; } setContentHandler(ch); } XMLReader reader = null; try { reader = saxSource.getXMLReader(); if (reader == null) { // create one now SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); try { reader = spf.newSAXParser().getXMLReader(); // If this is a Xerces SAX parser, set the security manager if there is one if (reader instanceof org.apache.xerces.parsers.SAXParser) { - SecurityManager securityManager = (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER); + Object securityManager = fComponentManager.getProperty(SECURITY_MANAGER); if (securityManager != null) { try { reader.setProperty(SECURITY_MANAGER, securityManager); } // Ignore the exception if the security manager cannot be set. catch (SAXException exc) {} } } } catch (Exception e) { // this is impossible, but better safe than sorry throw new FactoryConfigurationError(e); } } // If XML names and Namespace URIs are already internalized we // can avoid running them through the SymbolTable. try { fStringsInternalized = reader.getFeature(STRING_INTERNING); } catch (SAXException exc) { // The feature isn't recognized or getting it is not supported. // In either case, assume that strings are not internalized. fStringsInternalized = false; } ErrorHandler errorHandler = fComponentManager.getErrorHandler(); reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance()); reader.setEntityResolver(fResolutionForwarder); fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver()); reader.setContentHandler(this); reader.setDTDHandler(this); try { reader.setProperty(LEXICAL_HANDLER, lh); } // Ignore the exception if the lexical handler cannot be set. catch (SAXException exc) {} InputSource is = saxSource.getInputSource(); reader.parse(is); } finally { // Release the reference to user's ContentHandler ASAP setContentHandler(null); // Disconnect the validator and other objects from the XMLReader if (reader != null) { try { reader.setContentHandler(null); reader.setDTDHandler(null); reader.setErrorHandler(null); reader.setEntityResolver(null); fResolutionForwarder.setEntityResolver(null); reader.setProperty(LEXICAL_HANDLER, null); } // Ignore the exception if the lexical handler cannot be unset. catch (Exception exc) {} } } return; } throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "SourceResultMismatch", new Object [] {source.getClass().getName(), result.getClass().getName()})); } /* * PSVIProvider methods */ public ElementPSVI getElementPSVI() { return fTypeInfoProvider.getElementPSVI(); } public AttributePSVI getAttributePSVI(int index) { return fTypeInfoProvider.getAttributePSVI(index); } public AttributePSVI getAttributePSVIByName(String uri, String localname) { return fTypeInfoProvider.getAttributePSVIByName(uri, localname); } // // // helper methods // // /** Fills in a QName object. */ private void fillQName(QName toFill, String uri, String localpart, String raw) { if (!fStringsInternalized) { uri = (uri != null && uri.length() > 0) ? fSymbolTable.addSymbol(uri) : null; localpart = (localpart != null) ? fSymbolTable.addSymbol(localpart) : XMLSymbols.EMPTY_STRING; raw = (raw != null) ? fSymbolTable.addSymbol(raw) : XMLSymbols.EMPTY_STRING; } else { if (uri != null && uri.length() == 0) { uri = null; } if (localpart == null) { localpart = XMLSymbols.EMPTY_STRING; } if (raw == null) { raw = XMLSymbols.EMPTY_STRING; } } String prefix = XMLSymbols.EMPTY_STRING; int prefixIdx = raw.indexOf(':'); if (prefixIdx != -1) { prefix = fSymbolTable.addSymbol(raw.substring(0, prefixIdx)); } toFill.setValues(prefix, localpart, raw, uri); } /** Fills in the XMLAttributes object. */ private void fillXMLAttributes(Attributes att) { fAttributes.removeAllAttributes(); final int len = att.getLength(); for (int i = 0; i < len; ++i) { fillXMLAttribute(att, i); fAttributes.setSpecified(i, true); } } /** Fills in the XMLAttributes object. */ private void fillXMLAttributes2(Attributes2 att) { fAttributes.removeAllAttributes(); final int len = att.getLength(); for (int i = 0; i < len; ++i) { fillXMLAttribute(att, i); fAttributes.setSpecified(i, att.isSpecified(i)); if (att.isDeclared(i)) { fAttributes.getAugmentations(i).putItem(Constants.ATTRIBUTE_DECLARED, Boolean.TRUE); } } } /** Adds an attribute to the XMLAttributes object. */ private void fillXMLAttribute(Attributes att, int index) { fillQName(fAttributeQName, att.getURI(index), att.getLocalName(index), att.getQName(index)); String type = att.getType(index); fAttributes.addAttributeNS(fAttributeQName, (type != null) ? type : XMLSymbols.fCDATASymbol, att.getValue(index)); } /** * {@link TypeInfoProvider} implementation. * * REVISIT: I'm not sure if this code should belong here. */ private final XMLSchemaTypeInfoProvider fTypeInfoProvider = new XMLSchemaTypeInfoProvider(); private class XMLSchemaTypeInfoProvider extends TypeInfoProvider { /** Element augmentations: contains ElementPSVI. **/ private Augmentations fElementAugs; /** Attributes: augmentations for each attribute contain AttributePSVI. **/ private XMLAttributes fAttributes; /** In start element. **/ private boolean fInStartElement = false; private boolean fInEndElement = false; /** Initializes the TypeInfoProvider with type information for the current element. **/ void beginStartElement(Augmentations elementAugs, XMLAttributes attributes) { fInStartElement = true; fElementAugs = elementAugs; fAttributes = attributes; } /** Cleanup at the end of start element. **/ void finishStartElement() { fInStartElement = false; fElementAugs = null; fAttributes = null; } /** Initializes the TypeInfoProvider with type information for the current element. **/ void beginEndElement(Augmentations elementAugs) { fInEndElement = true; fElementAugs = elementAugs; } /** Cleanup at the end of end element. **/ void finishEndElement() { fInEndElement = false; fElementAugs = null; } /** * Throws a {@link IllegalStateException} if we are not in * the startElement callback. the JAXP API requires this * for most of the public methods which access attribute * type information. */ private void checkStateAttribute() { if (!fInStartElement) { throw new IllegalStateException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "TypeInfoProviderIllegalStateAttribute", null)); } } /** * Throws a {@link IllegalStateException} if we are not in * the startElement or endElement callbacks. the JAXP API requires * this for the public methods which access element type information. */ private void checkStateElement() { if (!fInStartElement && !fInEndElement) { throw new IllegalStateException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "TypeInfoProviderIllegalStateElement", null)); } } public TypeInfo getAttributeTypeInfo(int index) { checkStateAttribute(); return getAttributeType(index); } private TypeInfo getAttributeType( int index ) { checkStateAttribute(); if (index < 0 || fAttributes.getLength() <= index) { throw new IndexOutOfBoundsException(Integer.toString(index)); } Augmentations augs = fAttributes.getAugmentations(index); if (augs == null) { return null; } AttributePSVI psvi = (AttributePSVI)augs.getItem(Constants.ATTRIBUTE_PSVI); return getTypeInfoFromPSVI(psvi); } public TypeInfo getAttributeTypeInfo(String attributeUri, String attributeLocalName) { checkStateAttribute(); return getAttributeTypeInfo(fAttributes.getIndex(attributeUri,attributeLocalName)); } public TypeInfo getAttributeTypeInfo(String attributeQName) { checkStateAttribute(); return getAttributeTypeInfo(fAttributes.getIndex(attributeQName)); } public TypeInfo getElementTypeInfo() { checkStateElement(); if (fElementAugs == null) { return null; } ElementPSVI psvi = (ElementPSVI)fElementAugs.getItem(Constants.ELEMENT_PSVI); return getTypeInfoFromPSVI(psvi); } private TypeInfo getTypeInfoFromPSVI(ItemPSVI psvi) { if (psvi == null) { return null; } // TODO: make sure if this is correct. // TODO: since the number of types in a schema is quite limited, // TypeInfoImpl should be pooled. Even better, it should be a part // of the element decl. if (psvi.getValidity() == ItemPSVI.VALIDITY_VALID) { XSTypeDefinition t = psvi.getMemberTypeDefinition(); if (t != null) { return (t instanceof TypeInfo) ? (TypeInfo) t : null; } } XSTypeDefinition t = psvi.getTypeDefinition(); // TODO: can t be null? if (t != null) { return (t instanceof TypeInfo) ? (TypeInfo) t : null; } return null; } public boolean isIdAttribute(int index) { checkStateAttribute(); XSSimpleType type = (XSSimpleType)getAttributeType(index); if (type == null) { return false; } return type.isIDType(); } public boolean isSpecified(int index) { checkStateAttribute(); return fAttributes.isSpecified(index); } /* * Other methods */ // PSVIProvider support ElementPSVI getElementPSVI() { return (fElementAugs != null) ? (ElementPSVI) fElementAugs.getItem(Constants.ELEMENT_PSVI) : null; } AttributePSVI getAttributePSVI(int index) { if (fAttributes != null) { Augmentations augs = fAttributes.getAugmentations(index); if (augs != null) { return (AttributePSVI) augs.getItem(Constants.ATTRIBUTE_PSVI); } } return null; } AttributePSVI getAttributePSVIByName(String uri, String localname) { if (fAttributes != null) { Augmentations augs = fAttributes.getAugmentations(uri, localname); if (augs != null) { return (AttributePSVI) augs.getItem(Constants.ATTRIBUTE_PSVI); } } return null; } } /** SAX adapter for an LSResourceResolver. */ private final ResolutionForwarder fResolutionForwarder = new ResolutionForwarder(null); static final class ResolutionForwarder implements EntityResolver2 { // // Data // /** XML 1.0 type constant according to DOM L3 LS REC spec "http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/" */ private static final String XML_TYPE = "http://www.w3.org/TR/REC-xml"; /** The DOM entity resolver. */ protected LSResourceResolver fEntityResolver; // // Constructors // /** Default constructor. */ public ResolutionForwarder() {} /** Wraps the specified DOM entity resolver. */ public ResolutionForwarder(LSResourceResolver entityResolver) { setEntityResolver(entityResolver); } // // Public methods // /** Sets the DOM entity resolver. */ public void setEntityResolver(LSResourceResolver entityResolver) { fEntityResolver = entityResolver; } // setEntityResolver(LSResourceResolver) /** Returns the DOM entity resolver. */ public LSResourceResolver getEntityResolver() { return fEntityResolver; } // getEntityResolver():LSResourceResolver /** * Always returns <code>null</code>. An LSResourceResolver has no corresponding method. */ public InputSource getExternalSubset(String name, String baseURI) throws SAXException, IOException { return null; } /** * Resolves the given resource and adapts the <code>LSInput</code> * returned into an <code>InputSource</code>. */ public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { if (fEntityResolver != null) { LSInput lsInput = fEntityResolver.resolveResource(XML_TYPE, null, publicId, systemId, baseURI); if (lsInput != null) { final String pubId = lsInput.getPublicId(); final String sysId = lsInput.getSystemId(); final String baseSystemId = lsInput.getBaseURI(); final Reader charStream = lsInput.getCharacterStream(); final InputStream byteStream = lsInput.getByteStream(); final String data = lsInput.getStringData(); final String encoding = lsInput.getEncoding(); /** * An LSParser looks at inputs specified in LSInput in * the following order: characterStream, byteStream, * stringData, systemId, publicId. For consistency * with the DOM Level 3 Load and Save Recommendation * use the same lookup order here. */ InputSource inputSource = new InputSource(); inputSource.setPublicId(pubId); inputSource.setSystemId((baseSystemId != null) ? resolveSystemId(sysId, baseSystemId) : sysId); if (charStream != null) { inputSource.setCharacterStream(charStream); } else if (byteStream != null) { inputSource.setByteStream(byteStream); } else if (data != null && data.length() != 0) { inputSource.setCharacterStream(new StringReader(data)); } inputSource.setEncoding(encoding); return inputSource; } } return null; } /** Delegates to EntityResolver2.resolveEntity(String, String, String, String). */ public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return resolveEntity(null, publicId, null, systemId); } /** Resolves a system identifier against a base URI. */ private String resolveSystemId(String systemId, String baseURI) { try { return XMLEntityManager.expandSystemId(systemId, baseURI, false); } // In the event that resolution failed against the // base URI, just return the system id as is. There's not // much else we can do. catch (URI.MalformedURIException ex) { return systemId; } } } }
true
true
public void validate(Source source, Result result) throws SAXException, IOException { if (result instanceof SAXResult || result == null) { final SAXSource saxSource = (SAXSource) source; final SAXResult saxResult = (SAXResult) result; LexicalHandler lh = null; if (result != null) { ContentHandler ch = saxResult.getHandler(); lh = saxResult.getLexicalHandler(); /** If the lexical handler is not set try casting the ContentHandler. **/ if (lh == null && ch instanceof LexicalHandler) { lh = (LexicalHandler) ch; } setContentHandler(ch); } XMLReader reader = null; try { reader = saxSource.getXMLReader(); if (reader == null) { // create one now SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); try { reader = spf.newSAXParser().getXMLReader(); // If this is a Xerces SAX parser, set the security manager if there is one if (reader instanceof org.apache.xerces.parsers.SAXParser) { SecurityManager securityManager = (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER); if (securityManager != null) { try { reader.setProperty(SECURITY_MANAGER, securityManager); } // Ignore the exception if the security manager cannot be set. catch (SAXException exc) {} } } } catch (Exception e) { // this is impossible, but better safe than sorry throw new FactoryConfigurationError(e); } } // If XML names and Namespace URIs are already internalized we // can avoid running them through the SymbolTable. try { fStringsInternalized = reader.getFeature(STRING_INTERNING); } catch (SAXException exc) { // The feature isn't recognized or getting it is not supported. // In either case, assume that strings are not internalized. fStringsInternalized = false; } ErrorHandler errorHandler = fComponentManager.getErrorHandler(); reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance()); reader.setEntityResolver(fResolutionForwarder); fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver()); reader.setContentHandler(this); reader.setDTDHandler(this); try { reader.setProperty(LEXICAL_HANDLER, lh); } // Ignore the exception if the lexical handler cannot be set. catch (SAXException exc) {} InputSource is = saxSource.getInputSource(); reader.parse(is); } finally { // Release the reference to user's ContentHandler ASAP setContentHandler(null); // Disconnect the validator and other objects from the XMLReader if (reader != null) { try { reader.setContentHandler(null); reader.setDTDHandler(null); reader.setErrorHandler(null); reader.setEntityResolver(null); fResolutionForwarder.setEntityResolver(null); reader.setProperty(LEXICAL_HANDLER, null); } // Ignore the exception if the lexical handler cannot be unset. catch (Exception exc) {} } } return; } throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "SourceResultMismatch", new Object [] {source.getClass().getName(), result.getClass().getName()})); }
public void validate(Source source, Result result) throws SAXException, IOException { if (result instanceof SAXResult || result == null) { final SAXSource saxSource = (SAXSource) source; final SAXResult saxResult = (SAXResult) result; LexicalHandler lh = null; if (result != null) { ContentHandler ch = saxResult.getHandler(); lh = saxResult.getLexicalHandler(); /** If the lexical handler is not set try casting the ContentHandler. **/ if (lh == null && ch instanceof LexicalHandler) { lh = (LexicalHandler) ch; } setContentHandler(ch); } XMLReader reader = null; try { reader = saxSource.getXMLReader(); if (reader == null) { // create one now SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); try { reader = spf.newSAXParser().getXMLReader(); // If this is a Xerces SAX parser, set the security manager if there is one if (reader instanceof org.apache.xerces.parsers.SAXParser) { Object securityManager = fComponentManager.getProperty(SECURITY_MANAGER); if (securityManager != null) { try { reader.setProperty(SECURITY_MANAGER, securityManager); } // Ignore the exception if the security manager cannot be set. catch (SAXException exc) {} } } } catch (Exception e) { // this is impossible, but better safe than sorry throw new FactoryConfigurationError(e); } } // If XML names and Namespace URIs are already internalized we // can avoid running them through the SymbolTable. try { fStringsInternalized = reader.getFeature(STRING_INTERNING); } catch (SAXException exc) { // The feature isn't recognized or getting it is not supported. // In either case, assume that strings are not internalized. fStringsInternalized = false; } ErrorHandler errorHandler = fComponentManager.getErrorHandler(); reader.setErrorHandler(errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance()); reader.setEntityResolver(fResolutionForwarder); fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver()); reader.setContentHandler(this); reader.setDTDHandler(this); try { reader.setProperty(LEXICAL_HANDLER, lh); } // Ignore the exception if the lexical handler cannot be set. catch (SAXException exc) {} InputSource is = saxSource.getInputSource(); reader.parse(is); } finally { // Release the reference to user's ContentHandler ASAP setContentHandler(null); // Disconnect the validator and other objects from the XMLReader if (reader != null) { try { reader.setContentHandler(null); reader.setDTDHandler(null); reader.setErrorHandler(null); reader.setEntityResolver(null); fResolutionForwarder.setEntityResolver(null); reader.setProperty(LEXICAL_HANDLER, null); } // Ignore the exception if the lexical handler cannot be unset. catch (Exception exc) {} } } return; } throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), "SourceResultMismatch", new Object [] {source.getClass().getName(), result.getClass().getName()})); }
diff --git a/src/sai_cas/servlet/CrossMatchServlet.java b/src/sai_cas/servlet/CrossMatchServlet.java index 75fcbc8..cb6da75 100644 --- a/src/sai_cas/servlet/CrossMatchServlet.java +++ b/src/sai_cas/servlet/CrossMatchServlet.java @@ -1,317 +1,318 @@ /* Copyright (C) 2005-2006 Sergey Koposov Author: Sergey Koposov Email: [email protected] http://lnfm1.sai.msu.ru/~math This file is part of SAI CAS SAI CAS 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. SAI CAS 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 SAI CAS; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package sai_cas.servlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.File; import java.util.List; import java.util.Calendar; import java.util.logging.Logger; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.disk.*; import sai_cas.VOTABLEFile.VOTABLE; import sai_cas.VOTABLEFile.Votable; import sai_cas.VOTABLEFile.VotableException; import sai_cas.db.*; import sai_cas.output.CSVQueryResultsOutputter; import sai_cas.output.QueryResultsOutputter; import sai_cas.output.VOTableQueryResultsOutputter; import sai_cas.vo.*; public class CrossMatchServlet extends HttpServlet { static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("sai_cas.CrossMatchServlet"); public enum formats {VOTABLE, CSV}; public class CrossMatchServletException extends Exception { CrossMatchServletException() { super(); } CrossMatchServletException(String s) { super(s); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new CrossMatchServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); + Votable.setRandomResourceName(vot,"crossmatch_"); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { if (uploadedFile != null) { uploadedFile.delete(); } } catch (Exception e) { logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } } }
true
true
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new CrossMatchServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { if (uploadedFile != null) { uploadedFile.delete(); } } catch (Exception e) { logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { PrintWriter out = response.getWriter(); String cat = null, tab = null, radString = null, raColumn = null, decColumn = null, formatString = null; formats format; List<FileItem> fileItemList = null; FileItemFactory factory = new DiskFileItemFactory(); try { ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setSizeMax(50000000); /* Request size <= 50Mb */ fileItemList = sfu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e.getMessage()); /* Nothing ...*/ } FileItem fi = null; for (FileItem fi0: fileItemList) { if (fi0.getFieldName().equals("file"))//(!fi0.isFormField()) { fi = fi0; } if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField()) { tab = fi0.getString(); } if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField()) { cat = fi0.getString(); } if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField()) { radString = fi0.getString(); } if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField()) { raColumn = fi0.getString(); } if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField()) { decColumn = fi0.getString(); } if (fi0.getFieldName().equals("format"))//(!fi0.isFormField()) { formatString = fi0.getString(); } } if ((formatString==null)||(formatString.equalsIgnoreCase("votable"))) { format = formats.VOTABLE; } else if (formatString.equalsIgnoreCase("CSV")) { format = formats.CSV; } else { format = formats.VOTABLE; } QueryResultsOutputter qro = null; CSVQueryResultsOutputter csvqro = null; VOTableQueryResultsOutputter voqro = null; switch (format) { case CSV: response.setContentType("text/csv"); csvqro = new CSVQueryResultsOutputter(); qro = csvqro; break; case VOTABLE: response.setContentType("text/xml"); voqro = new VOTableQueryResultsOutputter(); qro = voqro; break; } File uploadedFile = null; Connection conn = null; DBInterface dbi = null; try { double rad = 0; rad = Double.parseDouble(radString); if (fi == null) { throw new CrossMatchServletException("File should be specified" + fileItemList.size() ); } long size = fi.getSize(); if (size > 10000000) { throw new CrossMatchServletException("File is too big"); } if (size == 0) { throw new CrossMatchServletException("File must not be empty"); } if (format.equals(formats.CSV)) { if ((raColumn==null)||(decColumn==null)) { throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC"); } } uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/")); try { fi.write(uploadedFile); } catch (Exception e) { throw new CrossMatchServletException("Error in writing your data in the temporary file"); } logger.debug("File written"); String[] userPasswd = sai_cas.Parameters.getDefaultTempDBUserPasswd(); String tempUser = userPasswd[0]; String tempPasswd = userPasswd[1]; conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd); dbi = new DBInterface(conn,tempUser); Votable vot = null; switch (format) { case CSV: vot = Votable.getVOTableFromCSV(uploadedFile); if ((!vot.checkColumnExistance(raColumn)) || (!vot.checkColumnExistance(decColumn))) { throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file"); } break; case VOTABLE: vot = new Votable (uploadedFile); Votable.setRandomResourceName(vot,"crossmatch_"); break; } String userDataSchema = dbi.getUserDataSchemaName(); String tableName = vot.insertDataToDB(dbi,userDataSchema); dbi.analyze(userDataSchema, tableName); String[] raDecArray = dbi.getRaDecColumns(cat, tab); String[] raDecArray1 = null; switch(format) { case VOTABLE: raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema, tableName); if (raDecArray1 == null) { throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch"); } break; case CSV: raDecArray1 = new String[2]; raDecArray1[0] = raColumn; raDecArray1[1] = decColumn; } response.setHeader("Content-Disposition", "attachment; filename=" + cat + "_" + fi.getName() + "_" + String.valueOf(rad) + ".dat"); dbi.executeQuery("select * from " + userDataSchema + "." + tableName + " AS a LEFT JOIN " + cat + "." + tab + " AS b "+ "ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+ raDecArray[0]+",b."+raDecArray[1]+","+rad+")"); if (format.equals(formats.VOTABLE)) { voqro.setResource(cat + "_" + fi.getName() ); voqro.setResourceDescription("This is the table obtained by "+ "crossmatching the table "+cat+"."+tab + " with the " + "user supplied table from the file " + fi.getName()+"\n"+ "Radius of the crossmatch: "+rad+"deg"); voqro.setTable("main" ); } qro.print(out,dbi); } catch (VotableException e) { qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)"); } catch (NumberFormatException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (CrossMatchServletException e) { qro.printError(out, "Error occured: " + e.getMessage()); } catch (DBException e) { logger.error("DBException " + e); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw); } catch (SQLException e) { logger.error("SQLException "+e); StringWriter sw =new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw); } finally { DBInterface.close(dbi,conn,false); /* Always rollback */ try { if (uploadedFile != null) { uploadedFile.delete(); } } catch (Exception e) { logger.error("Failed to delete the temporary file: " + uploadedFile.getCanonicalPath()); } } }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java index 9bf3f30d..7b3653f1 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/MetricsTool.java @@ -1,1127 +1,1143 @@ package jp.ac.osaka_u.ist.sel.metricstool.main; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.Java15AntlrAstTranslator; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.java.JavaAstVisitorManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.AstVisitorManager; import jp.ac.osaka_u.ist.sel.metricstool.main.ast.visitor.antlr.AntlrAstVisitor; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.ClassMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.FileMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MethodMetricsInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MetricNotRegisteredException; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ArrayTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FileInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FileInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.LocalVariableInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ModifierInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFieldInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFile; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFileManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetInnerClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetMethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetParameterInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.external.ExternalClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.NameResolver; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedArrayTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedClassInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedFieldInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedFieldUsage; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedLocalVariableInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedMethodCall; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedMethodInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedParameterInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedReferenceTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved.UnresolvedTypeInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVClassMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVFileMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.CSVMethodMetricsWriter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageEvent; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageListener; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePool; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource; import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java15Lexer; import jp.ac.osaka_u.ist.sel.metricstool.main.parse.Java15Parser; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.DefaultPluginLauncher; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginLauncher; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.PluginManager; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.AbstractPlugin.PluginInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.DefaultPluginLoader; import jp.ac.osaka_u.ist.sel.metricstool.main.plugin.loader.PluginLoadException; import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager; import jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE; import org.jargp.ArgumentProcessor; import org.jargp.BoolDef; import org.jargp.ParameterDef; import org.jargp.StringDef; import antlr.RecognitionException; import antlr.TokenStreamException; import antlr.collections.AST; /** * * @author y-higo * * MetricsTool�̃��C���N���X�D ���݂͉������D * * since 2006.11.12 * */ public class MetricsTool { static { // ���\���p�̃��X�i���쐬 MessagePool.getInstance(MESSAGE_TYPE.OUT).addMessageListener(new MessageListener() { public void messageReceived(MessageEvent event) { System.out.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }); MessagePool.getInstance(MESSAGE_TYPE.ERROR).addMessageListener(new MessageListener() { public void messageReceived(MessageEvent event) { System.err.print(event.getSource().getMessageSourceName() + " > " + event.getMessage()); } }); } /** * * @param args �Ώۃt�@�C���̃t�@�C���p�X * * ���݉������D �Ώۃt�@�C���̃f�[�^���i�[������C�\����͂��s���D */ public static void main(String[] args) { initSecurityManager(); ArgumentProcessor.processArgs(args, parameterDefs, new Settings()); // �w���v���[�h�Ə��\�����[�h�������ɃI���ɂȂ��Ă���ꍇ�͕s�� if (Settings.isHelpMode() && Settings.isDisplayMode()) { System.err.println("-h and -x can\'t be set at the same time!"); printUsage(); System.exit(0); } if (Settings.isHelpMode()) { // �w���v���[�h�̏ꍇ doHelpMode(); } else { LANGUAGE language = getLanguage(); loadPlugins(language, Settings.getMetricStrings()); if (Settings.isDisplayMode()) { // ���\�����[�h�̏ꍇ doDisplayMode(language); } else { // ��̓��[�h doAnalysisMode(language); } } } /** * �ǂݍ��񂾑Ώۃt�@�C���Q����͂���. * * @param language ��͑Ώۂ̌��� */ private static void analyzeTargetFiles(final LANGUAGE language) { // �Ώۃt�@�C������� AstVisitorManager<AST> visitorManager = null; if (language.equals(LANGUAGE.JAVA)) { visitorManager = new JavaAstVisitorManager<AST>(new AntlrAstVisitor( new Java15AntlrAstTranslator())); } out.println("Parse all target files."); for (TargetFile targetFile : TargetFileManager.getInstance()) { try { String name = targetFile.getName(); FileInfo fileInfo = new FileInfo(name); FileInfoManager.getInstance().add(fileInfo); out.println("parsing " + name); Java15Lexer lexer = new Java15Lexer(new FileInputStream(name)); Java15Parser parser = new Java15Parser(lexer); parser.compilationUnit(); targetFile.setCorrectSytax(true); if (visitorManager != null) { visitorManager.setPositionManager(parser.getPositionManger()); visitorManager.visitStart(parser.getAST()); } fileInfo.setLOC(lexer.getLine()); } catch (FileNotFoundException e) { err.println(e.getMessage()); } catch (RecognitionException e) { targetFile.setCorrectSytax(false); err.println(e.getMessage()); // TODO �G���[���N���������Ƃ� TargetFileData �Ȃǂɒʒm���鏈�����K�v } catch (TokenStreamException e) { targetFile.setCorrectSytax(false); err.println(e.getMessage()); // TODO �G���[���N���������Ƃ� TargetFileData �Ȃǂɒʒm���鏈�����K�v } } out.println("Resolve Definitions and Usages."); out.println("STEP1 : resolve class definitions."); registClassInfos(); out.println("STEP2 : resolve field definitions."); registFieldInfos(); out.println("STEP3 : resolve method definitions."); registMethodInfos(); out.println("STEP4 : resolve class inheritances."); addInheritanceInformationToClassInfos(); out.println("STEP5 : resolve method overrides."); addOverrideRelation(); out.println("STEP6 : resolve field and method usages."); addReferenceAssignmentCallRelateion(); // ���@���̂���t�@�C���ꗗ��\�� // err.println("The following files includes uncorrect syntax."); // err.println("Any metrics of them were not measured"); for (TargetFile targetFile : TargetFileManager.getInstance()) { if (!targetFile.isCorrectSyntax()) { err.println("Incorrect syntax file: " + targetFile.getName()); } } } /** * * �w���v���[�h�̈����̐��������m�F���邽�߂̃��\�b�h�D �s���Ȉ������w�肳��Ă����ꍇ�Cmain ���\�b�h�ɂ͖߂炸�C���̊֐����Ńv���O�������I������D * */ private static void checkHelpModeParameterValidation() { // -h �͑��̃I�v�V�����Ɠ����w��ł��Ȃ� if ((!Settings.getTargetDirectory().equals(Settings.INIT)) || (!Settings.getListFile().equals(Settings.INIT)) || (!Settings.getLanguageString().equals(Settings.INIT)) || (!Settings.getMetrics().equals(Settings.INIT)) || (!Settings.getFileMetricsFile().equals(Settings.INIT)) || (!Settings.getClassMetricsFile().equals(Settings.INIT)) || (!Settings.getMethodMetricsFile().equals(Settings.INIT))) { System.err.println("-h can\'t be specified with any other options!"); printUsage(); System.exit(0); } } /** * * ���\�����[�h�̈����̐��������m�F���邽�߂̃��\�b�h�D �s���Ȉ������w�肳��Ă����ꍇ�Cmain ���\�b�h�ɂ͖߂炸�C���̊֐����Ńv���O�������I������D * */ private static void checkDisplayModeParameterValidation() { // -d �͎g���Ȃ� if (!Settings.getTargetDirectory().equals(Settings.INIT)) { System.err.println("-d can\'t be specified in the display mode!"); printUsage(); System.exit(0); } // -i �͎g���Ȃ� if (!Settings.getListFile().equals(Settings.INIT)) { System.err.println("-i can't be specified in the display mode!"); printUsage(); System.exit(0); } // -F �͎g���Ȃ� if (!Settings.getFileMetricsFile().equals(Settings.INIT)) { System.err.println("-F can't be specified in the display mode!"); printUsage(); System.exit(0); } // -C �͎g���Ȃ� if (!Settings.getClassMetricsFile().equals(Settings.INIT)) { System.err.println("-C can't be specified in the display mode!"); printUsage(); System.exit(0); } // -M �͎g���Ȃ� if (!Settings.getMethodMetricsFile().equals(Settings.INIT)) { System.err.println("-M can't be specified in the display mode!"); printUsage(); System.exit(0); } } /** * * ��̓��[�h�̈����̐��������m�F���邽�߂̃��\�b�h�D �s���Ȉ������w�肳��Ă����ꍇ�Cmain ���\�b�h�ɂ͖߂炸�C���̊֐����Ńv���O�������I������D * * @param �w�肳�ꂽ���� * */ private static void checkAnalysisModeParameterValidation(LANGUAGE language) { // -d �� -i �̂ǂ�����w�肳��Ă���͕̂s�� if (Settings.getTargetDirectory().equals(Settings.INIT) && Settings.getListFile().equals(Settings.INIT)) { System.err.println("-d or -i must be specified in the analysis mode!"); printUsage(); System.exit(0); } // -d �� -i �̗������w�肳��Ă���͕̂s�� if (!Settings.getTargetDirectory().equals(Settings.INIT) && !Settings.getListFile().equals(Settings.INIT)) { System.err.println("-d and -i can't be specified at the same time!"); printUsage(); System.exit(0); } // ���ꂪ�w�肳��Ȃ������͕̂s�� if (null == language) { System.err.println("-l must be specified in the analysis mode."); printUsage(); System.exit(0); } boolean measureFileMetrics = false; boolean measureClassMetrics = false; boolean measureMethodMetrics = false; for (PluginInfo pluginInfo : PluginManager.getInstance().getPluginInfos()) { switch (pluginInfo.getMetricType()) { case FILE_METRIC: measureFileMetrics = true; break; case CLASS_METRIC: measureClassMetrics = true; break; case METHOD_METRIC: measureMethodMetrics = true; break; } } // �t�@�C�����g���N�X���v������ꍇ�� -F �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if (measureFileMetrics && (Settings.getFileMetricsFile().equals(Settings.INIT))) { System.err.println("-F must be used for specifying a file for file metrics!"); System.exit(0); } // �N���X���g���N�X���v������ꍇ�� -C �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if (measureClassMetrics && (Settings.getClassMetricsFile().equals(Settings.INIT))) { System.err.println("-C must be used for specifying a file for class metrics!"); System.exit(0); } // ���\�b�h���g���N�X���v������ꍇ�� -M �I�v�V�������w�肳��Ă��Ȃ���΂Ȃ�Ȃ� if (measureMethodMetrics && (Settings.getMethodMetricsFile().equals(Settings.INIT))) { System.err.println("-M must be used for specifying a file for method metrics!"); System.exit(0); } } /** * ��̓��[�h�����s����. * @param language �Ώی��� */ private static void doAnalysisMode(LANGUAGE language) { checkAnalysisModeParameterValidation(language); readTargetFiles(); analyzeTargetFiles(language); launchPlugins(); writeMetrics(); } /** * ���\�����[�h�����s���� * @param language �Ώی��� */ private static void doDisplayMode(LANGUAGE language) { checkDisplayModeParameterValidation(); // -l �Ō��ꂪ�w�肳��Ă��Ȃ��ꍇ�́C��͉”\����ꗗ��\�� if (null == language) { System.err.println("Available languages;"); LANGUAGE[] languages = LANGUAGE.values(); for (int i = 0; i < languages.length; i++) { System.err.println("\t" + languages[0].getName() + ": can be specified with term \"" + languages[0].getIdentifierName() + "\""); } // -l �Ō��ꂪ�w�肳��Ă���ꍇ�́C���̃v���O���~���O����Ŏg�p�”\�ȃ��g���N�X�ꗗ��\�� } else { System.err.println("Available metrics for " + language.getName()); for (AbstractPlugin plugin : PluginManager.getInstance().getPlugins()) { PluginInfo pluginInfo = plugin.getPluginInfo(); if (pluginInfo.isMeasurable(language)) { System.err.println("\t" + pluginInfo.getMetricName()); } } // TODO ���p�”\���g���N�X�ꗗ��\�� } } /** * �w���v���[�h�����s����. */ private static void doHelpMode() { checkHelpModeParameterValidation(); printUsage(); } /** * �Ώی�����擾����. * * @return �w�肳�ꂽ�Ώی���.�w�肳��Ȃ������ꍇ��null */ private static LANGUAGE getLanguage() { if (Settings.getLanguageString().equals(Settings.INIT)) { return null; } return Settings.getLanguage(); } /** * {@link MetricsToolSecurityManager} �̏��������s��. * �V�X�e���ɓo�^�ł���΁C�V�X�e���̃Z�L�����e�B�}�l�[�W���ɂ��o�^����. */ private static void initSecurityManager() { try { // MetricsToolSecurityManager�̃V���O���g���C���X�^���X���\�z���C�������ʌ����X���b�h�ɂȂ� System.setSecurityManager(MetricsToolSecurityManager.getInstance()); } catch (final SecurityException e) { // ���ɃZ�b�g����Ă���Z�L�����e�B�}�l�[�W���ɂ���āC�V���ȃZ�L�����e�B�}�l�[�W���̓o�^�����‚���Ȃ������D // �V�X�e���̃Z�L�����e�B�}�l�[�W���Ƃ��Ďg��Ȃ��Ă��C���ʌ����X���b�h�̃A�N�Z�X����͖��Ȃ����삷��̂łƂ肠������������ err .println("Failed to set system security manager. MetricsToolsecurityManager works only to manage privilege threads."); } } /** * ���[�h�ς݂̃v���O�C�������s����. */ private static void launchPlugins() { PluginLauncher launcher = new DefaultPluginLauncher(); launcher.setMaximumLaunchingNum(1); launcher.launchAll(PluginManager.getInstance().getPlugins()); do { try { Thread.sleep(1000); } catch (InterruptedException e) { // �C�ɂ��Ȃ� } } while (0 < launcher.getCurrentLaunchingNum() + launcher.getLaunchWaitingTaskNum()); launcher.stopLaunching(); } /** * �v���O�C�������[�h����. * �w�肳�ꂽ����C�w�肳�ꂽ���g���N�X�Ɋ֘A����v���O�C���݂̂� {@link PluginManager}�ɓo�^����. * @param language �w�肵���ꂽ����. */ private static void loadPlugins(final LANGUAGE language, final String[] metrics) { // �w�茾��ɑΉ�����v���O�C���Ŏw�肳�ꂽ���g���N�X���v������v���O�C�������[�h���ēo�^ // metrics[]���O�‚���Ȃ����C2�ˆȏ�w�肳��Ă��� or �P�‚����ǃf�t�H���g�̕����񂶂�Ȃ� boolean metricsSpecified = metrics.length != 0 && (1 < metrics.length || !metrics[0].equals(Settings.INIT)); final PluginManager pluginManager = PluginManager.getInstance(); try { for (final AbstractPlugin plugin : (new DefaultPluginLoader()).loadPlugins()) {// �v���O�C����S���[�h final PluginInfo info = plugin.getPluginInfo(); if (null == language || info.isMeasurable(language)) { // �Ώی��ꂪ�w�肳��Ă��Ȃ� or �Ώی�����v���”\ if (metricsSpecified) { // ���g���N�X���w�肳��Ă���̂ł��̃v���O�C���ƈ�v���邩�`�F�b�N final String pluginMetricName = info.getMetricName(); for (final String metric : metrics) { if (metric.equals(pluginMetricName)) { pluginManager.addPlugin(plugin); break; } } } else { // ���g���N�X���w�肳��Ă��Ȃ��̂łƂ肠�����S���o�^ pluginManager.addPlugin(plugin); } } } } catch (PluginLoadException e) { err.println(e.getMessage()); System.exit(0); } } /** * * �c�[���̎g�����i�R�}���h���C���I�v�V�����j��\������D * */ private static void printUsage() { System.err.println(); System.err.println("Available options:"); System.err.println("\t-d: root directory that you are going to analysis."); System.err.println("\t-i: List file including file paths that you are going to analysis."); System.err.println("\t-l: Programming language of the target files."); System.err .println("\t-m: Metrics that you want to get. Metrics names are separated with \',\'."); System.err.println("\t-C: File path that the class type metrics are output"); System.err.println("\t-F: File path that the file type metrics are output."); System.err.println("\t-M: File path that the method type metrics are output"); System.err.println(); System.err.println("Usage:"); System.err.println("\t<Help Mode>"); System.err.println("\tMetricsTool -h"); System.err.println(); System.err.println("\t<Display Mode>"); System.err.println("\tMetricsTool -x -l"); System.err.println("\tMetricsTool -x -l language -m"); System.err.println(); System.err.println("\t<Analysis Mode>"); System.err .println("\tMetricsTool -d directory -l language -m metrics1,metrics2 -C file1 -F file2 -M file3"); System.err .println("\tMetricsTool -l listFile -l language -m metrics1,metrics2 -C file1 -F file2 -M file3"); } /** * ��͑Ώۃt�@�C����o�^ */ private static void readTargetFiles() { // �f�B���N�g������ǂݍ��� if (!Settings.getTargetDirectory().equals(Settings.INIT)) { registerFilesFromDirectory(); // ���X�g�t�@�C������ǂݍ��� } else if (!Settings.getListFile().equals(Settings.INIT)) { registerFilesFromListFile(); } } /** * * ���X�g�t�@�C������Ώۃt�@�C����o�^����D �ǂݍ��݃G���[�����������ꍇ�́C���̃��\�b�h���Ńv���O�������I������D */ private static void registerFilesFromListFile() { try { TargetFileManager targetFiles = TargetFileManager.getInstance(); for (BufferedReader reader = new BufferedReader(new FileReader(Settings.getListFile())); reader .ready();) { String line = reader.readLine(); TargetFile targetFile = new TargetFile(line); targetFiles.add(targetFile); } } catch (FileNotFoundException e) { err.println("\"" + Settings.getListFile() + "\" is not a valid file!"); System.exit(0); } catch (IOException e) { err.println("\"" + Settings.getListFile() + "\" can\'t read!"); System.exit(0); } } /** * * registerFilesFromDirectory(File file)���Ăяo���̂݁D main���\�b�h�� new File(Settings.getTargetDirectory) * ����̂��C���������������ߍ쐬�D * */ private static void registerFilesFromDirectory() { File targetDirectory = new File(Settings.getTargetDirectory()); registerFilesFromDirectory(targetDirectory); } /** * * @param file �Ώۃt�@�C���܂��̓f�B���N�g�� * * �Ώۂ��f�B���N�g���̏ꍇ�́C���̎q�ɑ΂��čċA�I�ɏ���������D �Ώۂ��t�@�C���̏ꍇ�́C�Ώی���̃\�[�X�t�@�C���ł���΁C�o�^�������s���D */ private static void registerFilesFromDirectory(File file) { // �f�B���N�g���Ȃ�΁C�ċA�I�ɏ��� if (file.isDirectory()) { File[] subfiles = file.listFiles(); for (int i = 0; i < subfiles.length; i++) { registerFilesFromDirectory(subfiles[i]); } // �t�@�C���Ȃ�΁C�g���q���Ώی���ƈ�v����Γo�^ } else if (file.isFile()) { final LANGUAGE language = Settings.getLanguage(); final String extension = language.getExtension(); final String path = file.getAbsolutePath(); if (path.endsWith(extension)) { final TargetFileManager targetFiles = TargetFileManager.getInstance(); final TargetFile targetFile = new TargetFile(path); targetFiles.add(targetFile); } // �f�B���N�g���ł��t�@�C���ł��Ȃ��ꍇ�͕s�� } else { err.println("\"" + file.getAbsolutePath() + "\" is not a vaild file!"); System.exit(0); } } /** * ���g���N�X�����t�@�C���ɏo��. */ private static void writeMetrics() { if (!Settings.getFileMetricsFile().equals(Settings.INIT)) { try { FileMetricsInfoManager manager = FileMetricsInfoManager.getInstance(); manager.checkMetrics(); String fileName = Settings.getFileMetricsFile(); CSVFileMetricsWriter writer = new CSVFileMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { System.exit(0); } } if (!Settings.getClassMetricsFile().equals(Settings.INIT)) { try { ClassMetricsInfoManager manager = ClassMetricsInfoManager.getInstance(); manager.checkMetrics(); String fileName = Settings.getClassMetricsFile(); CSVClassMetricsWriter writer = new CSVClassMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { System.exit(0); } } if (!Settings.getMethodMetricsFile().equals(Settings.INIT)) { try { MethodMetricsInfoManager manager = MethodMetricsInfoManager.getInstance(); manager.checkMetrics(); String fileName = Settings.getMethodMetricsFile(); CSVMethodMetricsWriter writer = new CSVMethodMetricsWriter(fileName); writer.write(); } catch (MetricNotRegisteredException e) { System.exit(0); } } } /** * �����̎d�l�� Jargp �ɓn�����߂̔z��D */ private static ParameterDef[] parameterDefs = { new BoolDef('h', "helpMode", "display usage", true), new BoolDef('x', "displayMode", "display available language or metrics", true), new StringDef('d', "targetDirectory", "Target directory"), new StringDef('i', "listFile", "List file including paths of target files"), new StringDef('l', "language", "Programming language"), new StringDef('m', "metrics", "Measured metrics"), new StringDef('F', "fileMetricsFile", "File storing file metrics"), new StringDef('C', "classMetricsFile", "File storing class metrics"), new StringDef('M', "methodMetricsFile", "File storing method metrics") }; /** * �o�̓��b�Z�[�W�o�͗p�̃v�����^ */ private static final MessagePrinter out = new DefaultMessagePrinter(new MessageSource() { public String getMessageSourceName() { return "main"; } }, MESSAGE_TYPE.OUT); /** * �G���[���b�Z�[�W�o�͗p�̃v�����^ */ private static final MessagePrinter err = new DefaultMessagePrinter(new MessageSource() { public String getMessageSourceName() { return "main"; } }, MESSAGE_TYPE.ERROR); /** * �N���X�̒�`�� ClassInfoManager �ɓo�^����DAST �p�[�X�̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ��D */ private static void registClassInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // �C���q�C���S���薼�C�s���C�Ž����C�C���X�^���X�����o�[���ǂ������擾 final Set<ModifierInfo> modifiers = unresolvedClassInfo.getModifiers(); final String[] fullQualifiedName = unresolvedClassInfo.getFullQualifiedName(); final int loc = unresolvedClassInfo.getLOC(); final boolean privateVisible = unresolvedClassInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedClassInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedClassInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedClassInfo.isPublicVisible(); final boolean instance = unresolvedClassInfo.isInstanceMember(); final int fromLine = unresolvedClassInfo.getFromLine(); final int fromColumn = unresolvedClassInfo.getFromColumn(); final int toLine = unresolvedClassInfo.getToLine(); final int toColumn = unresolvedClassInfo.getToColumn(); // ClassInfo �I�u�W�F�N�g���쐬���CClassInfoManager�ɓo�^ final TargetClassInfo classInfo = new TargetClassInfo(modifiers, fullQualifiedName, loc, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, fromLine, fromColumn, toLine, toColumn); classInfoManager.add(classInfo); for (UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo .getInnerClasses()) { final TargetInnerClassInfo innerClass = registInnerClassInfo( unresolvedInnerClassInfo, classInfo, classInfoManager); classInfo.addInnerClass(innerClass); } } } /** * �C���i�[�N���X�̒�`�� ClassInfoManager �ɓo�^����D registClassInfos ����̂݌Ă΂��ׂ��ł���D * * @param unresolvedClassInfo ���O���������C���i�[�N���X�I�u�W�F�N�g * @param outerClass �O���̃N���X * @param classInfoManager �C���i�[�N���X��o�^����N���X�}�l�[�W�� * @return ���������C���i�[�N���X�� ClassInfo */ private static TargetInnerClassInfo registInnerClassInfo( final UnresolvedClassInfo unresolvedClassInfo, final TargetClassInfo outerClass, final ClassInfoManager classInfoManager) { // �C���q�C���S���薼�C�s���C�Ž������擾 final Set<ModifierInfo> modifiers = unresolvedClassInfo.getModifiers(); final String[] fullQualifiedName = unresolvedClassInfo.getFullQualifiedName(); final int loc = unresolvedClassInfo.getLOC(); final boolean privateVisible = unresolvedClassInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedClassInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedClassInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedClassInfo.isPublicVisible(); final boolean instance = unresolvedClassInfo.isInstanceMember(); final int fromLine = unresolvedClassInfo.getFromLine(); final int fromColumn = unresolvedClassInfo.getFromColumn(); final int toLine = unresolvedClassInfo.getToLine(); final int toColumn = unresolvedClassInfo.getToColumn(); // ClassInfo �I�u�W�F�N�g�𐶐����CClassInfo�}�l�[�W���ɓo�^ TargetInnerClassInfo classInfo = new TargetInnerClassInfo(modifiers, fullQualifiedName, outerClass, loc, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, fromLine, fromColumn, toLine, toColumn); classInfoManager.add(classInfo); // ���̃N���X�̃C���i�[�N���X�ɑ΂��čċA�I�ɏ��� for (UnresolvedClassInfo unresolvedInnerClassInfo : unresolvedClassInfo.getInnerClasses()) { final TargetInnerClassInfo innerClass = registInnerClassInfo(unresolvedInnerClassInfo, classInfo, classInfoManager); classInfo.addInnerClass(innerClass); } // ���̃N���X�� ClassInfo ��Ԃ� return classInfo; } /** * �N���X�̌p������ ClassInfo �ɒlj�����D��x�ڂ� AST �p�[�X�̌�C���� registClassInfos �̌�ɂ�т����Ȃ���΂Ȃ�Ȃ��D */ private static void addInheritanceInformationToClassInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // ClassInfo ���擾 final ClassInfo classInfo = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); // �eUnresolved�Ȑe�N���X���ɑ΂��� for (UnresolvedTypeInfo unresolvedSuperClassType : unresolvedClassInfo .getSuperClasses()) { ClassInfo superClass = (ClassInfo) NameResolver.resolveTypeInfo( unresolvedSuperClassType, classInfoManager); // ���‚���Ȃ������ꍇ�͖��O��Ԗ���UNKNOWN�ȃN���X��o�^���� if (null == superClass) { superClass = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedSuperClassType); classInfoManager.add((ExternalClassInfo) superClass); } classInfo.addSuperClass(superClass); superClass.addSubClass(classInfo); } } } /** * �t�B�[���h�̒�`�� FieldInfoManager �ɓo�^����D registClassInfos �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ� * */ private static void registFieldInfos() { // Unresolved �N���X���}�l�[�W���C�N���X���}�l�[�W���C�t�B�[���h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); final FieldInfoManager fieldInfoManager = FieldInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // ClassInfo ���擾 final ClassInfo ownerClass = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); if (!(ownerClass instanceof TargetClassInfo)) { throw new IllegalArgumentException(ownerClass.toString() + " must be an instance of TargetClassInfo!"); } // Unresolved�N���X�ɒ�`����Ă���eUnresolved�t�B�[���h�ɑ΂��� for (UnresolvedFieldInfo unresolvedFieldInfo : unresolvedClassInfo.getDefinedFields()) { // �C���q�C���O�C�^�C�Ž����C�C���X�^���X�����o�[���ǂ������擾 final Set<ModifierInfo> modifiers = unresolvedFieldInfo.getModifiers(); final String fieldName = unresolvedFieldInfo.getName(); final UnresolvedTypeInfo unresolvedFieldType = unresolvedFieldInfo.getType(); TypeInfo fieldType = NameResolver.resolveTypeInfo(unresolvedFieldType, classInfoManager); if (null == fieldType) { if (unresolvedFieldType instanceof UnresolvedReferenceTypeInfo) { fieldType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedFieldType); classInfoManager.add((ExternalClassInfo) fieldType); } else if (unresolvedFieldType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedFieldType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedFieldType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); fieldType = ArrayTypeInfo.getType(elementType, dimension); } } final boolean privateVisible = unresolvedFieldInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedFieldInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedFieldInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedFieldInfo.isPublicVisible(); final boolean instance = unresolvedFieldInfo.isInstanceMember(); final int fromLine = unresolvedFieldInfo.getFromLine(); final int fromColumn = unresolvedFieldInfo.getFromColumn(); final int toLine = unresolvedFieldInfo.getToLine(); final int toColumn = unresolvedFieldInfo.getToColumn(); // �t�B�[���h�I�u�W�F�N�g�𐶐� final TargetFieldInfo fieldInfo = new TargetFieldInfo(modifiers, fieldName, fieldType, ownerClass, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, fromLine, fromColumn, toLine, toColumn); // �t�B�[���h����lj� ((TargetClassInfo) ownerClass).addDefinedField(fieldInfo); fieldInfoManager.add(fieldInfo); } } } /** * ���\�b�h�̒�`�� MethodInfoManager �ɓo�^����DregistClassInfos �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ��D */ private static void registMethodInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W���C���\�b�h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); final MethodInfoManager methodInfoManager = MethodInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // ClassInfo ���擾 final ClassInfo ownerClass = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); if (!(ownerClass instanceof TargetClassInfo)) { throw new IllegalArgumentException(ownerClass.toString() + " must be an instance of TargetClassInfo"); } // Unresolved�N���X�ɒ�`����Ă���e���������\�b�h�ɑ΂��� for (UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // �C���q�C���O�C�Ԃ�l�C�s���C�R���X�g���N�^���ǂ����C�Ž����C�C���X�^���X�����o�[���ǂ������擾 final Set<ModifierInfo> methodModifiers = unresolvedMethodInfo.getModifiers(); final String methodName = unresolvedMethodInfo.getMethodName(); final UnresolvedTypeInfo unresolvedMethodReturnType = unresolvedMethodInfo .getReturnType(); TypeInfo methodReturnType = NameResolver.resolveTypeInfo( unresolvedMethodReturnType, classInfoManager); if (null == methodReturnType) { if (unresolvedMethodReturnType instanceof UnresolvedReferenceTypeInfo) { methodReturnType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedMethodReturnType); classInfoManager.add((ExternalClassInfo) methodReturnType); } else if (unresolvedMethodReturnType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); methodReturnType = ArrayTypeInfo.getType(elementType, dimension); } } final int methodLOC = unresolvedMethodInfo.getLOC(); final boolean constructor = unresolvedMethodInfo.isConstructor(); final boolean privateVisible = unresolvedMethodInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedMethodInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedMethodInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedMethodInfo.isPublicVisible(); final boolean instance = unresolvedMethodInfo.isInstanceMember(); final int methodFromLine = unresolvedMethodInfo.getFromLine(); final int methodFromColumn = unresolvedMethodInfo.getFromColumn(); final int methodToLine = unresolvedMethodInfo.getToLine(); final int methodToColumn = unresolvedMethodInfo.getToColumn(); // MethodInfo �I�u�W�F�N�g�𐶐����C������lj����Ă��� final TargetMethodInfo methodInfo = new TargetMethodInfo(methodModifiers, methodName, methodReturnType, ownerClass, constructor, methodLOC, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, methodFromLine, methodFromColumn, methodToLine, methodToColumn); for (UnresolvedParameterInfo unresolvedParameterInfo : unresolvedMethodInfo .getParameterInfos()) { // �C���q�C�p�����[�^���C�^�C�ʒu�����擾 final Set<ModifierInfo> parameterModifiers = unresolvedParameterInfo .getModifiers(); final String parameterName = unresolvedParameterInfo.getName(); final UnresolvedTypeInfo unresolvedParameterType = unresolvedParameterInfo .getType(); TypeInfo parameterType = NameResolver.resolveTypeInfo(unresolvedParameterType, classInfoManager); if (null == parameterType) { if (unresolvedParameterType instanceof UnresolvedReferenceTypeInfo) { parameterType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedParameterType); classInfoManager.add((ExternalClassInfo) parameterType); } else if (unresolvedParameterType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); parameterType = ArrayTypeInfo.getType(elementType, dimension); } } final int parameterFromLine = unresolvedParameterInfo.getFromLine(); final int parameterFromColumn = unresolvedParameterInfo.getFromColumn(); final int parameterToLine = unresolvedParameterInfo.getToLine(); final int parameterToColumn = unresolvedParameterInfo.getToColumn(); // �p�����[�^�I�u�W�F�N�g�𐶐����C���\�b�h�ɒlj� final TargetParameterInfo parameterInfo = new TargetParameterInfo( parameterModifiers, parameterName, parameterType, parameterFromLine, parameterFromColumn, parameterToLine, parameterToColumn); methodInfo.addParameter(parameterInfo); } // ���\�b�h���Œ�`����Ă���e���������[�J���ϐ��ɑ΂��� for (UnresolvedLocalVariableInfo unresolvedLocalVariable : unresolvedMethodInfo .getLocalVariables()) { // �C���q�C�ϐ����C�^���擾 final Set<ModifierInfo> localModifiers = unresolvedLocalVariable.getModifiers(); final String variableName = unresolvedLocalVariable.getName(); final UnresolvedTypeInfo unresolvedVariableType = unresolvedLocalVariable .getType(); - final TypeInfo variableType = NameResolver.resolveTypeInfo( + TypeInfo variableType = NameResolver.resolveTypeInfo( unresolvedVariableType, classInfoManager); + if (null == variableType) { + if (unresolvedVariableType instanceof UnresolvedReferenceTypeInfo) { + variableType = NameResolver + .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedVariableType); + classInfoManager.add((ExternalClassInfo) variableType); + } else if (unresolvedVariableType instanceof UnresolvedArrayTypeInfo) { + final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedVariableType) + .getElementType(); + final int dimension = ((UnresolvedArrayTypeInfo) unresolvedVariableType) + .getDimension(); + final TypeInfo elementType = NameResolver + .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); + classInfoManager.add((ExternalClassInfo) elementType); + variableType = ArrayTypeInfo.getType(elementType, dimension); + } + } final int localFromLine = unresolvedLocalVariable.getFromLine(); final int localFromColumn = unresolvedLocalVariable.getFromColumn(); final int localToLine = unresolvedLocalVariable.getToLine(); final int localToColumn = unresolvedLocalVariable.getToColumn(); // ���[�J���ϐ��I�u�W�F�N�g�𐶐����CMethodInfo�ɒlj� final LocalVariableInfo localVariable = new LocalVariableInfo(localModifiers, variableName, variableType, localFromLine, localFromColumn, localToLine, localToColumn); methodInfo.addLocalVariable(localVariable); } // ���\�b�h����lj� ((TargetClassInfo) ownerClass).addDefinedMethod(methodInfo); methodInfoManager.add(methodInfo); } } } /** * ���\�b�h�I�[�o�[���C�h�����eMethodInfo�ɒlj�����DaddInheritanceInfomationToClassInfos �̌� ���� registMethodInfos * �̌�ɌĂяo���Ȃ���΂Ȃ�Ȃ� */ private static void addOverrideRelation() { // �S�Ă̑ΏۃN���X�ɑ΂��� for (TargetClassInfo classInfo : ClassInfoManager.getInstance().getTargetClassInfos()) { // �e�ΏۃN���X�̐e�N���X�ɑ΂��� for (ClassInfo superClassInfo : classInfo.getSuperClasses()) { // �e�ΏۃN���X�̊e���\�b�h�ɂ‚��āC�e�N���X�̃��\�b�h���I�[�����x���Ă��邩�𒲍� for (MethodInfo methodInfo : classInfo.getDefinedMethods()) { addOverrideRelation(superClassInfo, methodInfo); } } } } /** * ���\�b�h�I�[�o�[���C�h����lj�����D�����Ŏw�肳�ꂽ�N���X�Œ�`����Ă��郁�\�b�h�ɑ΂��đ�����s��. * AddOverrideInformationToMethodInfos()�̒�����̂݌Ăяo�����D * * @param classInfo �N���X��� * @param overrider �I�[�o�[���C�h�Ώۂ̃��\�b�h */ private static void addOverrideRelation(final ClassInfo classInfo, final MethodInfo overrider) { if ((null == classInfo) || (null == overrider)) { throw new NullPointerException(); } if (!(classInfo instanceof TargetClassInfo)) { return; } for (TargetMethodInfo methodInfo : ((TargetClassInfo) classInfo).getDefinedMethods()) { if (methodInfo.isSameSignature(overrider)) { overrider.addOverridee(methodInfo); methodInfo.addOverrider(overrider); // ���ڂ̃I�[�o�[���C�h�֌W�������o���Ȃ��̂ŁC���̃N���X�̐e�N���X�͒������Ȃ� return; } } // �e�N���X�Q�ɑ΂��čċA�I�ɏ��� for (ClassInfo superClassInfo : classInfo.getSuperClasses()) { addOverrideRelation(superClassInfo, overrider); } } /** * �G���e�B�e�B�i�t�B�[���h��N���X�j�̑���E�Q�ƁC���\�b�h�̌Ăяo���֌W��lj�����D */ private static void addReferenceAssignmentCallRelateion() { final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); final FieldInfoManager fieldInfoManager = FieldInfoManager.getInstance(); final MethodInfoManager methodInfoManager = MethodInfoManager.getInstance(); final Map<UnresolvedTypeInfo, TypeInfo> resolvedCache = new HashMap<UnresolvedTypeInfo, TypeInfo>(); // �e�������N���X��� �ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // �������N���X��񂩂�C�����ς݃N���X�����擾 final TargetClassInfo userClass = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); // �e���������\�b�h���ɑ΂��� for (UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // ���������\�b�h��񂩂�C�����ς݃��\�b�h�����擾 final TargetMethodInfo caller = NameResolver.resolveMethodInfo( unresolvedMethodInfo, classInfoManager); // �e�������Q�ƃG���e�B�e�B�̖��O�������� for (UnresolvedFieldUsage referencee : unresolvedMethodInfo.getFieldReferences()) { // �������Q�Ə��������� NameResolver.resolveFieldReference(referencee, userClass, caller, classInfoManager, fieldInfoManager, methodInfoManager, resolvedCache); } // ����������G���e�B�e�B�̖��O�������� for (UnresolvedFieldUsage assignmentee : unresolvedMethodInfo.getFieldAssignments()) { // ������������������� NameResolver.resolveFieldAssignment(assignmentee, userClass, caller, classInfoManager, fieldInfoManager, methodInfoManager, resolvedCache); } // �e���������\�b�h�Ăяo�������̉������� for (UnresolvedMethodCall methodCall : unresolvedMethodInfo.getMethodCalls()) { // �e���������\�b�h�Ăяo������������ NameResolver.resolveMethodCall(methodCall, userClass, caller, classInfoManager, fieldInfoManager, methodInfoManager, resolvedCache); } } } } }
false
true
private static void registMethodInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W���C���\�b�h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); final MethodInfoManager methodInfoManager = MethodInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // ClassInfo ���擾 final ClassInfo ownerClass = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); if (!(ownerClass instanceof TargetClassInfo)) { throw new IllegalArgumentException(ownerClass.toString() + " must be an instance of TargetClassInfo"); } // Unresolved�N���X�ɒ�`����Ă���e���������\�b�h�ɑ΂��� for (UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // �C���q�C���O�C�Ԃ�l�C�s���C�R���X�g���N�^���ǂ����C�Ž����C�C���X�^���X�����o�[���ǂ������擾 final Set<ModifierInfo> methodModifiers = unresolvedMethodInfo.getModifiers(); final String methodName = unresolvedMethodInfo.getMethodName(); final UnresolvedTypeInfo unresolvedMethodReturnType = unresolvedMethodInfo .getReturnType(); TypeInfo methodReturnType = NameResolver.resolveTypeInfo( unresolvedMethodReturnType, classInfoManager); if (null == methodReturnType) { if (unresolvedMethodReturnType instanceof UnresolvedReferenceTypeInfo) { methodReturnType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedMethodReturnType); classInfoManager.add((ExternalClassInfo) methodReturnType); } else if (unresolvedMethodReturnType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); methodReturnType = ArrayTypeInfo.getType(elementType, dimension); } } final int methodLOC = unresolvedMethodInfo.getLOC(); final boolean constructor = unresolvedMethodInfo.isConstructor(); final boolean privateVisible = unresolvedMethodInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedMethodInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedMethodInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedMethodInfo.isPublicVisible(); final boolean instance = unresolvedMethodInfo.isInstanceMember(); final int methodFromLine = unresolvedMethodInfo.getFromLine(); final int methodFromColumn = unresolvedMethodInfo.getFromColumn(); final int methodToLine = unresolvedMethodInfo.getToLine(); final int methodToColumn = unresolvedMethodInfo.getToColumn(); // MethodInfo �I�u�W�F�N�g�𐶐����C������lj����Ă��� final TargetMethodInfo methodInfo = new TargetMethodInfo(methodModifiers, methodName, methodReturnType, ownerClass, constructor, methodLOC, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, methodFromLine, methodFromColumn, methodToLine, methodToColumn); for (UnresolvedParameterInfo unresolvedParameterInfo : unresolvedMethodInfo .getParameterInfos()) { // �C���q�C�p�����[�^���C�^�C�ʒu�����擾 final Set<ModifierInfo> parameterModifiers = unresolvedParameterInfo .getModifiers(); final String parameterName = unresolvedParameterInfo.getName(); final UnresolvedTypeInfo unresolvedParameterType = unresolvedParameterInfo .getType(); TypeInfo parameterType = NameResolver.resolveTypeInfo(unresolvedParameterType, classInfoManager); if (null == parameterType) { if (unresolvedParameterType instanceof UnresolvedReferenceTypeInfo) { parameterType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedParameterType); classInfoManager.add((ExternalClassInfo) parameterType); } else if (unresolvedParameterType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); parameterType = ArrayTypeInfo.getType(elementType, dimension); } } final int parameterFromLine = unresolvedParameterInfo.getFromLine(); final int parameterFromColumn = unresolvedParameterInfo.getFromColumn(); final int parameterToLine = unresolvedParameterInfo.getToLine(); final int parameterToColumn = unresolvedParameterInfo.getToColumn(); // �p�����[�^�I�u�W�F�N�g�𐶐����C���\�b�h�ɒlj� final TargetParameterInfo parameterInfo = new TargetParameterInfo( parameterModifiers, parameterName, parameterType, parameterFromLine, parameterFromColumn, parameterToLine, parameterToColumn); methodInfo.addParameter(parameterInfo); } // ���\�b�h���Œ�`����Ă���e���������[�J���ϐ��ɑ΂��� for (UnresolvedLocalVariableInfo unresolvedLocalVariable : unresolvedMethodInfo .getLocalVariables()) { // �C���q�C�ϐ����C�^���擾 final Set<ModifierInfo> localModifiers = unresolvedLocalVariable.getModifiers(); final String variableName = unresolvedLocalVariable.getName(); final UnresolvedTypeInfo unresolvedVariableType = unresolvedLocalVariable .getType(); final TypeInfo variableType = NameResolver.resolveTypeInfo( unresolvedVariableType, classInfoManager); final int localFromLine = unresolvedLocalVariable.getFromLine(); final int localFromColumn = unresolvedLocalVariable.getFromColumn(); final int localToLine = unresolvedLocalVariable.getToLine(); final int localToColumn = unresolvedLocalVariable.getToColumn(); // ���[�J���ϐ��I�u�W�F�N�g�𐶐����CMethodInfo�ɒlj� final LocalVariableInfo localVariable = new LocalVariableInfo(localModifiers, variableName, variableType, localFromLine, localFromColumn, localToLine, localToColumn); methodInfo.addLocalVariable(localVariable); } // ���\�b�h����lj� ((TargetClassInfo) ownerClass).addDefinedMethod(methodInfo); methodInfoManager.add(methodInfo); } } }
private static void registMethodInfos() { // Unresolved �N���X���}�l�[�W���C �N���X���}�l�[�W���C���\�b�h���}�l�[�W�����擾 final UnresolvedClassInfoManager unresolvedClassInfoManager = UnresolvedClassInfoManager .getInstance(); final ClassInfoManager classInfoManager = ClassInfoManager.getInstance(); final MethodInfoManager methodInfoManager = MethodInfoManager.getInstance(); // �e Unresolved�N���X�ɑ΂��� for (UnresolvedClassInfo unresolvedClassInfo : unresolvedClassInfoManager.getClassInfos()) { // ClassInfo ���擾 final ClassInfo ownerClass = NameResolver.resolveClassInfo(unresolvedClassInfo, classInfoManager); if (!(ownerClass instanceof TargetClassInfo)) { throw new IllegalArgumentException(ownerClass.toString() + " must be an instance of TargetClassInfo"); } // Unresolved�N���X�ɒ�`����Ă���e���������\�b�h�ɑ΂��� for (UnresolvedMethodInfo unresolvedMethodInfo : unresolvedClassInfo .getDefinedMethods()) { // �C���q�C���O�C�Ԃ�l�C�s���C�R���X�g���N�^���ǂ����C�Ž����C�C���X�^���X�����o�[���ǂ������擾 final Set<ModifierInfo> methodModifiers = unresolvedMethodInfo.getModifiers(); final String methodName = unresolvedMethodInfo.getMethodName(); final UnresolvedTypeInfo unresolvedMethodReturnType = unresolvedMethodInfo .getReturnType(); TypeInfo methodReturnType = NameResolver.resolveTypeInfo( unresolvedMethodReturnType, classInfoManager); if (null == methodReturnType) { if (unresolvedMethodReturnType instanceof UnresolvedReferenceTypeInfo) { methodReturnType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedMethodReturnType); classInfoManager.add((ExternalClassInfo) methodReturnType); } else if (unresolvedMethodReturnType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedMethodReturnType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); methodReturnType = ArrayTypeInfo.getType(elementType, dimension); } } final int methodLOC = unresolvedMethodInfo.getLOC(); final boolean constructor = unresolvedMethodInfo.isConstructor(); final boolean privateVisible = unresolvedMethodInfo.isPrivateVisible(); final boolean namespaceVisible = unresolvedMethodInfo.isNamespaceVisible(); final boolean inheritanceVisible = unresolvedMethodInfo.isInheritanceVisible(); final boolean publicVisible = unresolvedMethodInfo.isPublicVisible(); final boolean instance = unresolvedMethodInfo.isInstanceMember(); final int methodFromLine = unresolvedMethodInfo.getFromLine(); final int methodFromColumn = unresolvedMethodInfo.getFromColumn(); final int methodToLine = unresolvedMethodInfo.getToLine(); final int methodToColumn = unresolvedMethodInfo.getToColumn(); // MethodInfo �I�u�W�F�N�g�𐶐����C������lj����Ă��� final TargetMethodInfo methodInfo = new TargetMethodInfo(methodModifiers, methodName, methodReturnType, ownerClass, constructor, methodLOC, privateVisible, namespaceVisible, inheritanceVisible, publicVisible, instance, methodFromLine, methodFromColumn, methodToLine, methodToColumn); for (UnresolvedParameterInfo unresolvedParameterInfo : unresolvedMethodInfo .getParameterInfos()) { // �C���q�C�p�����[�^���C�^�C�ʒu�����擾 final Set<ModifierInfo> parameterModifiers = unresolvedParameterInfo .getModifiers(); final String parameterName = unresolvedParameterInfo.getName(); final UnresolvedTypeInfo unresolvedParameterType = unresolvedParameterInfo .getType(); TypeInfo parameterType = NameResolver.resolveTypeInfo(unresolvedParameterType, classInfoManager); if (null == parameterType) { if (unresolvedParameterType instanceof UnresolvedReferenceTypeInfo) { parameterType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedParameterType); classInfoManager.add((ExternalClassInfo) parameterType); } else if (unresolvedParameterType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedParameterType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); parameterType = ArrayTypeInfo.getType(elementType, dimension); } } final int parameterFromLine = unresolvedParameterInfo.getFromLine(); final int parameterFromColumn = unresolvedParameterInfo.getFromColumn(); final int parameterToLine = unresolvedParameterInfo.getToLine(); final int parameterToColumn = unresolvedParameterInfo.getToColumn(); // �p�����[�^�I�u�W�F�N�g�𐶐����C���\�b�h�ɒlj� final TargetParameterInfo parameterInfo = new TargetParameterInfo( parameterModifiers, parameterName, parameterType, parameterFromLine, parameterFromColumn, parameterToLine, parameterToColumn); methodInfo.addParameter(parameterInfo); } // ���\�b�h���Œ�`����Ă���e���������[�J���ϐ��ɑ΂��� for (UnresolvedLocalVariableInfo unresolvedLocalVariable : unresolvedMethodInfo .getLocalVariables()) { // �C���q�C�ϐ����C�^���擾 final Set<ModifierInfo> localModifiers = unresolvedLocalVariable.getModifiers(); final String variableName = unresolvedLocalVariable.getName(); final UnresolvedTypeInfo unresolvedVariableType = unresolvedLocalVariable .getType(); TypeInfo variableType = NameResolver.resolveTypeInfo( unresolvedVariableType, classInfoManager); if (null == variableType) { if (unresolvedVariableType instanceof UnresolvedReferenceTypeInfo) { variableType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedVariableType); classInfoManager.add((ExternalClassInfo) variableType); } else if (unresolvedVariableType instanceof UnresolvedArrayTypeInfo) { final UnresolvedTypeInfo unresolvedElementType = ((UnresolvedArrayTypeInfo) unresolvedVariableType) .getElementType(); final int dimension = ((UnresolvedArrayTypeInfo) unresolvedVariableType) .getDimension(); final TypeInfo elementType = NameResolver .createExternalClassInfo((UnresolvedReferenceTypeInfo) unresolvedElementType); classInfoManager.add((ExternalClassInfo) elementType); variableType = ArrayTypeInfo.getType(elementType, dimension); } } final int localFromLine = unresolvedLocalVariable.getFromLine(); final int localFromColumn = unresolvedLocalVariable.getFromColumn(); final int localToLine = unresolvedLocalVariable.getToLine(); final int localToColumn = unresolvedLocalVariable.getToColumn(); // ���[�J���ϐ��I�u�W�F�N�g�𐶐����CMethodInfo�ɒlj� final LocalVariableInfo localVariable = new LocalVariableInfo(localModifiers, variableName, variableType, localFromLine, localFromColumn, localToLine, localToColumn); methodInfo.addLocalVariable(localVariable); } // ���\�b�h����lj� ((TargetClassInfo) ownerClass).addDefinedMethod(methodInfo); methodInfoManager.add(methodInfo); } } }
diff --git a/core/src/visad/trunk/examples/Test05.java b/core/src/visad/trunk/examples/Test05.java index 6288c0471..546a4192c 100644 --- a/core/src/visad/trunk/examples/Test05.java +++ b/core/src/visad/trunk/examples/Test05.java @@ -1,147 +1,148 @@ /* VisAD system for interactive analysis and visualization of numerical data. Copyright (C) 1996 - 2006 Bill Hibbard, Curtis Rueden, Tom Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and Tommy Jasmin. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.rmi.RemoteException; import visad.*; import visad.java3d.DisplayImplJ3D; import visad.util.ContourWidget; public class Test05 extends UISkeleton { private boolean uneven; public Test05() { } public Test05(String[] args) throws RemoteException, VisADException { super(args); } public void initializeArgs() { uneven = false; } public int checkKeyword(String testName, int argc, String[] args) { uneven = true; return 1; } DisplayImpl[] setupServerDisplays() throws RemoteException, VisADException { DisplayImpl[] dpys = new DisplayImpl[1]; dpys[0] = new DisplayImplJ3D("display"); return dpys; } void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException { RealType[] types = {RealType.Latitude, RealType.Longitude}; RealTupleType earth_location = new RealTupleType(types); RealType vis_radiance = RealType.getRealType("vis_radiance"); RealType ir_radiance = RealType.getRealType("ir_radiance"); RealType[] types2 = {vis_radiance, ir_radiance}; RealTupleType radiance = new RealTupleType(types2); FunctionType image_tuple = new FunctionType(earth_location, radiance); int size = 64; FlatField imaget1 = FlatField.makeField(image_tuple, size, false); dpys[0].addMap(new ScalarMap(RealType.Latitude, Display.YAxis)); dpys[0].addMap(new ScalarMap(RealType.Longitude, Display.XAxis)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.Green)); + dpys[0].addMap(new ScalarMap(vis_radiance, Display.RGB)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.ZAxis)); dpys[0].addMap(new ConstantMap(0.5, Display.Blue)); dpys[0].addMap(new ConstantMap(0.5, Display.Red)); ScalarMap map1contour; map1contour = new ScalarMap(vis_radiance, Display.IsoContour); dpys[0].addMap(map1contour); if (uneven) { ContourControl control = (ContourControl) map1contour.getControl(); float[] levs = {10.0f, 12.0f, 14.0f, 16.0f, 24.0f, 32.0f, 40.0f}; control.setLevels(levs, 15.0f, true); control.enableLabels(true); } DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1"); ref_imaget1.setData(imaget1); dpys[0].addReference(ref_imaget1, null); } private String getFrameTitle0() { return "regular contours in Java3D"; } private String getFrameTitle1() { return "VisAD contour controls"; } void setupUI(LocalDisplay[] dpys) throws RemoteException, VisADException { JFrame jframe = new JFrame(getFrameTitle0() + getClientServerTitle()); jframe.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); jframe.setContentPane((JPanel) dpys[0].getComponent()); jframe.pack(); jframe.setVisible(true); if (!uneven) { ScalarMap map1contour = (ScalarMap )dpys[0].getMapVector().lastElement(); ContourWidget cw = new ContourWidget(map1contour); JPanel big_panel = new JPanel(); big_panel.setLayout(new BorderLayout()); big_panel.add("Center", cw); JFrame jframe2 = new JFrame(getFrameTitle1()); jframe2.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); jframe2.setContentPane(big_panel); jframe2.pack(); jframe2.setVisible(true); } } public String toString() { return " uneven: colored 2-D contours from regular grids and ContourWidget"; } public static void main(String[] args) throws RemoteException, VisADException { new Test05(args); } }
true
true
void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException { RealType[] types = {RealType.Latitude, RealType.Longitude}; RealTupleType earth_location = new RealTupleType(types); RealType vis_radiance = RealType.getRealType("vis_radiance"); RealType ir_radiance = RealType.getRealType("ir_radiance"); RealType[] types2 = {vis_radiance, ir_radiance}; RealTupleType radiance = new RealTupleType(types2); FunctionType image_tuple = new FunctionType(earth_location, radiance); int size = 64; FlatField imaget1 = FlatField.makeField(image_tuple, size, false); dpys[0].addMap(new ScalarMap(RealType.Latitude, Display.YAxis)); dpys[0].addMap(new ScalarMap(RealType.Longitude, Display.XAxis)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.Green)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.ZAxis)); dpys[0].addMap(new ConstantMap(0.5, Display.Blue)); dpys[0].addMap(new ConstantMap(0.5, Display.Red)); ScalarMap map1contour; map1contour = new ScalarMap(vis_radiance, Display.IsoContour); dpys[0].addMap(map1contour); if (uneven) { ContourControl control = (ContourControl) map1contour.getControl(); float[] levs = {10.0f, 12.0f, 14.0f, 16.0f, 24.0f, 32.0f, 40.0f}; control.setLevels(levs, 15.0f, true); control.enableLabels(true); } DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1"); ref_imaget1.setData(imaget1); dpys[0].addReference(ref_imaget1, null); }
void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException { RealType[] types = {RealType.Latitude, RealType.Longitude}; RealTupleType earth_location = new RealTupleType(types); RealType vis_radiance = RealType.getRealType("vis_radiance"); RealType ir_radiance = RealType.getRealType("ir_radiance"); RealType[] types2 = {vis_radiance, ir_radiance}; RealTupleType radiance = new RealTupleType(types2); FunctionType image_tuple = new FunctionType(earth_location, radiance); int size = 64; FlatField imaget1 = FlatField.makeField(image_tuple, size, false); dpys[0].addMap(new ScalarMap(RealType.Latitude, Display.YAxis)); dpys[0].addMap(new ScalarMap(RealType.Longitude, Display.XAxis)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.Green)); dpys[0].addMap(new ScalarMap(vis_radiance, Display.RGB)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.ZAxis)); dpys[0].addMap(new ConstantMap(0.5, Display.Blue)); dpys[0].addMap(new ConstantMap(0.5, Display.Red)); ScalarMap map1contour; map1contour = new ScalarMap(vis_radiance, Display.IsoContour); dpys[0].addMap(map1contour); if (uneven) { ContourControl control = (ContourControl) map1contour.getControl(); float[] levs = {10.0f, 12.0f, 14.0f, 16.0f, 24.0f, 32.0f, 40.0f}; control.setLevels(levs, 15.0f, true); control.enableLabels(true); } DataReferenceImpl ref_imaget1 = new DataReferenceImpl("ref_imaget1"); ref_imaget1.setData(imaget1); dpys[0].addReference(ref_imaget1, null); }
diff --git a/src/edu/first/team2903/robot/commands/TeleopMode.java b/src/edu/first/team2903/robot/commands/TeleopMode.java index 357d3ec..c18e9bd 100644 --- a/src/edu/first/team2903/robot/commands/TeleopMode.java +++ b/src/edu/first/team2903/robot/commands/TeleopMode.java @@ -1,37 +1,38 @@ package edu.first.team2903.robot.commands; import edu.first.team2903.robot.OI; public class TeleopMode extends CommandBase { public TeleopMode() { requires(drivetrain); requires(shooter); } protected void initialize() { //Todo, spindown code } protected void execute() { + //DEBUG REMOVE LATER if (OI.rightStick.getZ() > 0) { - shooter.Shoot(OI.rightStick.getZ()); + shooter.setSpeed(OI.rightStick.getZ()); } drivetrain.drive(OI.leftStick.getY(), OI.rightStick.getY()); } protected boolean isFinished() { //Will end when teleop is done return false; } protected void end() { } protected void interrupted() { } }
false
true
protected void execute() { if (OI.rightStick.getZ() > 0) { shooter.Shoot(OI.rightStick.getZ()); } drivetrain.drive(OI.leftStick.getY(), OI.rightStick.getY()); }
protected void execute() { //DEBUG REMOVE LATER if (OI.rightStick.getZ() > 0) { shooter.setSpeed(OI.rightStick.getZ()); } drivetrain.drive(OI.leftStick.getY(), OI.rightStick.getY()); }
diff --git a/org.aspectj.matcher/src/org/aspectj/weaver/Lint.java b/org.aspectj.matcher/src/org/aspectj/weaver/Lint.java index 4c4f5f7dd..bc2b44ba4 100644 --- a/org.aspectj.matcher/src/org/aspectj/weaver/Lint.java +++ b/org.aspectj.matcher/src/org/aspectj/weaver/Lint.java @@ -1,319 +1,325 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 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: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.tools.Trace; import org.aspectj.weaver.tools.TraceFactory; public class Lint { /* private */Map kinds = new HashMap(); /* private */World world; public final Kind invalidAbsoluteTypeName = new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}"); public final Kind invalidWildcardTypeName = new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}"); public final Kind unresolvableMember = new Kind("unresolvableMember", "can not resolve this member: {0}"); public final Kind typeNotExposedToWeaver = new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}"); public final Kind shadowNotInStructure = new Kind("shadowNotInStructure", "the shadow for this join point is not exposed in the structure model: {0}"); public final Kind unmatchedSuperTypeInCall = new Kind("unmatchedSuperTypeInCall", "does not match because declaring type is {0}, if match desired use target({1})"); public final Kind unmatchedTargetKind = new Kind("unmatchedTargetKind", "does not match because annotation {0} has @Target{1}"); public final Kind canNotImplementLazyTjp = new Kind("canNotImplementLazyTjp", "can not implement lazyTjp on this joinpoint {0} because around advice is used"); public final Kind multipleAdviceStoppingLazyTjp = new Kind("multipleAdviceStoppingLazyTjp", "can not implement lazyTjp at joinpoint {0} because of advice conflicts, see secondary locations to find conflicting advice"); public final Kind needsSerialVersionUIDField = new Kind("needsSerialVersionUIDField", "serialVersionUID of type {0} needs to be set because of {1}"); public final Kind serialVersionUIDBroken = new Kind("brokeSerialVersionCompatibility", "serialVersionUID of type {0} is broken because of added field {1}"); public final Kind noInterfaceCtorJoinpoint = new Kind("noInterfaceCtorJoinpoint", "no interface constructor-execution join point - use {0}+ for implementing classes"); public final Kind noJoinpointsForBridgeMethods = new Kind( "noJoinpointsForBridgeMethods", "pointcut did not match on the method call to a bridge method. Bridge methods are generated by the compiler and have no join points"); public final Kind enumAsTargetForDecpIgnored = new Kind("enumAsTargetForDecpIgnored", "enum type {0} matches a declare parents type pattern but is being ignored"); public final Kind annotationAsTargetForDecpIgnored = new Kind("annotationAsTargetForDecpIgnored", "annotation type {0} matches a declare parents type pattern but is being ignored"); public final Kind cantMatchArrayTypeOnVarargs = new Kind("cantMatchArrayTypeOnVarargs", "an array type as the last parameter in a signature does not match on the varargs declared method: {0}"); public final Kind adviceDidNotMatch = new Kind("adviceDidNotMatch", "advice defined in {0} has not been applied"); public final Kind invalidTargetForAnnotation = new Kind("invalidTargetForAnnotation", "{0} is not a valid target for annotation {1}, this annotation can only be applied to {2}"); public final Kind elementAlreadyAnnotated = new Kind("elementAlreadyAnnotated", "{0} - already has an annotation of type {1}, cannot add a second instance"); public final Kind runtimeExceptionNotSoftened = new Kind("runtimeExceptionNotSoftened", "{0} will not be softened as it is already a RuntimeException"); public final Kind uncheckedArgument = new Kind("uncheckedArgument", "unchecked match of {0} with {1} when argument is an instance of {2} at join point {3}"); public final Kind uncheckedAdviceConversion = new Kind("uncheckedAdviceConversion", "unchecked conversion when advice applied at shadow {0}, expected {1} but advice uses {2}"); public final Kind noGuardForLazyTjp = new Kind("noGuardForLazyTjp", "can not build thisJoinPoint lazily for this advice since it has no suitable guard"); public final Kind noExplicitConstructorCall = new Kind("noExplicitConstructorCall", "inter-type constructor does not contain explicit constructor call: field initializers in the target type will not be executed"); public final Kind aspectExcludedByConfiguration = new Kind("aspectExcludedByConfiguration", "aspect {0} exluded for class loader {1}"); public final Kind unorderedAdviceAtShadow = new Kind("unorderedAdviceAtShadow", "at this shadow {0} no precedence is specified between advice applying from aspect {1} and aspect {2}"); public final Kind swallowedExceptionInCatchBlock = new Kind("swallowedExceptionInCatchBlock", "exception swallowed in catch block"); public final Kind calculatingSerialVersionUID = new Kind("calculatingSerialVersionUID", "calculated SerialVersionUID for type {0} to be {1}"); // there are a lot of messages in the cant find type family - I'm defining an umbrella lint warning that // allows a user to control their severity (for e.g. ltw or binary weaving) public final Kind cantFindType = new Kind("cantFindType", "{0}"); public final Kind cantFindTypeAffectingJoinPointMatch = new Kind("cantFindTypeAffectingJPMatch", "{0}"); public final Kind advisingSynchronizedMethods = new Kind("advisingSynchronizedMethods", "advice matching the synchronized method shadow ''{0}'' will be executed outside the lock rather than inside (compiler limitation)"); public final Kind mustWeaveXmlDefinedAspects = new Kind( "mustWeaveXmlDefinedAspects", "XML Defined aspects must be woven in cases where cflow pointcuts are involved. Currently the include/exclude patterns exclude ''{0}''"); public final Kind cannotAdviseJoinpointInInterfaceWithAroundAdvice = new Kind( "cannotAdviseJoinpointInInterfaceWithAroundAdvice", "The joinpoint ''{0}'' cannot be advised and is being skipped as the compiler implementation will lead to creation of methods with bodies in an interface (compiler limitation)"); /** * Indicates an aspect could not be found when attempting reweaving. */ public final Kind missingAspectForReweaving = new Kind("missingAspectForReweaving", "aspect {0} cannot be found when reweaving {1}"); private static Trace trace = TraceFactory.getTraceFactory().getTrace(Lint.class); public Lint(World world) { if (trace.isTraceEnabled()) trace.enter("<init>", this, world); this.world = world; if (trace.isTraceEnabled()) trace.exit("<init>"); } public void setAll(String messageKind) { if (trace.isTraceEnabled()) trace.enter("setAll", this, messageKind); setAll(getMessageKind(messageKind)); if (trace.isTraceEnabled()) trace.exit("setAll"); } private void setAll(IMessage.Kind messageKind) { for (Iterator i = kinds.values().iterator(); i.hasNext();) { Kind kind = (Kind) i.next(); kind.setKind(messageKind); } } public void setFromProperties(File file) { if (trace.isTraceEnabled()) trace.enter("setFromProperties", this, file); try { InputStream s = new FileInputStream(file); setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_LOAD_ERROR, file.getPath(), ioe .getMessage())); } if (trace.isTraceEnabled()) trace.exit("setFromProperties"); } public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR)); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM, ioe .getMessage())); + } finally { + try { + s.close(); + } catch (IOException ioe) { + // ... + } } } private void setFromProperties(InputStream s) throws IOException { Properties p = new Properties(); p.load(s); setFromProperties(p); } public void setFromProperties(Properties properties) { for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); Kind kind = (Kind) kinds.get(entry.getKey()); if (kind == null) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR, entry.getKey())); } else { kind.setKind(getMessageKind((String) entry.getValue())); } } } public Collection allKinds() { return kinds.values(); } public Kind getLintKind(String name) { return (Kind) kinds.get(name); } // temporarily suppress the given lint messages public void suppressKinds(Collection lintKind) { if (lintKind.isEmpty()) return; for (Iterator iter = lintKind.iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(true); } } // remove any suppression of lint warnings in place public void clearAllSuppressions() { for (Iterator iter = kinds.values().iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(false); } } public void clearSuppressions(Collection lintKind) { if (lintKind.isEmpty()) return; for (Iterator iter = lintKind.iterator(); iter.hasNext();) { Kind k = (Kind) iter.next(); k.setSuppressed(false); } } private IMessage.Kind getMessageKind(String v) { if (v.equals("ignore")) return null; else if (v.equals("warning")) return IMessage.WARNING; else if (v.equals("error")) return IMessage.ERROR; MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_VALUE_ERROR, v)); return null; } public Kind fromKey(String lintkey) { return (Lint.Kind) kinds.get(lintkey); } public class Kind { private final String name; private final String message; private IMessage.Kind kind = IMessage.WARNING; private boolean isSupressed = false; // by SuppressAjWarnings public Kind(String name, String message) { this.name = name; this.message = message; kinds.put(this.name, this); } public void setSuppressed(boolean shouldBeSuppressed) { this.isSupressed = shouldBeSuppressed; } public boolean isEnabled() { return (kind != null) && !isSupressed(); } private boolean isSupressed() { // can't suppress errors! return isSupressed && (kind != IMessage.ERROR); } public String getName() { return name; } public IMessage.Kind getKind() { return kind; } public void setKind(IMessage.Kind kind) { this.kind = kind; } public void signal(String info, ISourceLocation location) { if (kind == null) return; String text = MessageFormat.format(message, new Object[] { info }); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, null, getLintKind(name))); } public void signal(String[] infos, ISourceLocation location, ISourceLocation[] extraLocations) { if (kind == null) return; String text = MessageFormat.format(message, (Object[]) infos); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new LintMessage(text, kind, location, extraLocations, getLintKind(name))); } } }
true
true
public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR)); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM, ioe .getMessage())); } }
public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_ERROR)); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINTDEFAULT_LOAD_PROBLEM, ioe .getMessage())); } finally { try { s.close(); } catch (IOException ioe) { // ... } } }
diff --git a/src/com/android/alarmclock/AnalogAppWidgetProvider.java b/src/com/android/alarmclock/AnalogAppWidgetProvider.java index 711179a9..b5181ada 100644 --- a/src/com/android/alarmclock/AnalogAppWidgetProvider.java +++ b/src/com/android/alarmclock/AnalogAppWidgetProvider.java @@ -1,55 +1,54 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.alarmclock; import com.android.deskclock.AlarmClock; import com.android.deskclock.R; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; /** * Simple widget to show analog clock. */ public class AnalogAppWidgetProvider extends BroadcastReceiver { static final String TAG = "AnalogAppWidgetProvider"; public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.analog_appwidget); views.setOnClickPendingIntent(R.id.analog_appwidget, PendingIntent.getActivity(context, 0, - new Intent(context, AlarmClock.class), - PendingIntent.FLAG_CANCEL_CURRENT)); + new Intent(context, AlarmClock.class), 0)); int[] appWidgetIds = intent.getIntArrayExtra( AppWidgetManager.EXTRA_APPWIDGET_IDS); AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(appWidgetIds, views); } } }
true
true
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.analog_appwidget); views.setOnClickPendingIntent(R.id.analog_appwidget, PendingIntent.getActivity(context, 0, new Intent(context, AlarmClock.class), PendingIntent.FLAG_CANCEL_CURRENT)); int[] appWidgetIds = intent.getIntArrayExtra( AppWidgetManager.EXTRA_APPWIDGET_IDS); AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(appWidgetIds, views); } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.analog_appwidget); views.setOnClickPendingIntent(R.id.analog_appwidget, PendingIntent.getActivity(context, 0, new Intent(context, AlarmClock.class), 0)); int[] appWidgetIds = intent.getIntArrayExtra( AppWidgetManager.EXTRA_APPWIDGET_IDS); AppWidgetManager gm = AppWidgetManager.getInstance(context); gm.updateAppWidget(appWidgetIds, views); } }
diff --git a/test/src/org/omegat/gui/glossary/GlossaryTextAreaTest.java b/test/src/org/omegat/gui/glossary/GlossaryTextAreaTest.java index 17ce03a3..b353bb97 100644 --- a/test/src/org/omegat/gui/glossary/GlossaryTextAreaTest.java +++ b/test/src/org/omegat/gui/glossary/GlossaryTextAreaTest.java @@ -1,175 +1,176 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2007 Maxym Mykhalchuk 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.gui.glossary; import java.util.ArrayList; import java.util.List; import javax.swing.SwingUtilities; import org.omegat.core.TestCore; import org.omegat.core.TestCoreInitializer; import org.omegat.core.data.SourceTextEntry; import org.omegat.gui.editor.EditorSettings; import org.omegat.gui.editor.IEditor; import org.omegat.gui.editor.IPopupMenuConstructor; import org.omegat.gui.editor.mark.Mark; import org.omegat.util.Preferences; /** * * @author Maxym Mykhalchuk */ public class GlossaryTextAreaTest extends TestCore { /** * Testing setGlossaryEntries of org.omegat.gui.main.GlossaryTextArea. */ public void testSetGlossaryEntries() throws Exception { Preferences.setPreference(org.omegat.util.Preferences.TRANSTIPS, false); final List<GlossaryEntry> entries = new ArrayList<GlossaryEntry>(); entries.add(new GlossaryEntry("source1", "translation1", "")); entries.add(new GlossaryEntry("source2", "translation2", "comment2")); final GlossaryTextArea gta = new GlossaryTextArea(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { gta.setFoundResult(null, entries); } }); String GTATEXT = "source1 = translation1\n\nsource2 = translation2\ncomment2\n\n"; if (!gta.getText().equals(GTATEXT)) fail("Glossary pane doesn't show what it should."); } /** * Testing clear in org.omegat.gui.main.GlossaryTextArea. */ public void testClear() throws Exception { Preferences.setPreference(org.omegat.util.Preferences.TRANSTIPS, false); final List<GlossaryEntry> entries = new ArrayList<GlossaryEntry>(); entries.add(new GlossaryEntry("source1", "translation1", "")); entries.add(new GlossaryEntry("source2", "translation2", "comment2")); final GlossaryTextArea gta = new GlossaryTextArea(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { gta.setFoundResult(null, entries); } }); gta.clear(); if (gta.getText().length() > 0) fail("Glossary pane isn't empty."); } @Override protected void setUp() throws Exception { + super.setUp(); TestCoreInitializer.initEditor(new IEditor() { public void activateEntry() { } public void changeCase(CHANGE_CASE_TO newCase) { } public void commitAndDeactivate() { } public void commitAndLeave() { } public SourceTextEntry getCurrentEntry() { return null; } public int getCurrentEntryNumber() { return 0; } public String getCurrentFile() { return null; } public String getSelectedText() { return null; } public EditorSettings getSettings() { return null; } public void gotoEntry(int entryNum) { } public void gotoFile(int fileIndex) { } public void gotoHistoryBack() { } public void gotoHistoryForward() { } public void insertText(String text) { } public void markActiveEntrySource( SourceTextEntry requiredActiveEntry, List<Mark> marks, String markerClassName) { } public void nextEntry() { } public void nextUntranslatedEntry() { } public void prevEntry() { } public void undo() { } public void redo() { } public void registerPopupMenuConstructors(int priority, IPopupMenuConstructor constructor) { } public void replaceEditText(String text) { } public void requestFocus() { } public void remarkOneMarker(String markerClassName) { } public void addFilter(List<Integer> entryList) { } public void removeFilter() { } }); } }
true
true
protected void setUp() throws Exception { TestCoreInitializer.initEditor(new IEditor() { public void activateEntry() { } public void changeCase(CHANGE_CASE_TO newCase) { } public void commitAndDeactivate() { } public void commitAndLeave() { } public SourceTextEntry getCurrentEntry() { return null; } public int getCurrentEntryNumber() { return 0; } public String getCurrentFile() { return null; } public String getSelectedText() { return null; } public EditorSettings getSettings() { return null; } public void gotoEntry(int entryNum) { } public void gotoFile(int fileIndex) { } public void gotoHistoryBack() { } public void gotoHistoryForward() { } public void insertText(String text) { } public void markActiveEntrySource( SourceTextEntry requiredActiveEntry, List<Mark> marks, String markerClassName) { } public void nextEntry() { } public void nextUntranslatedEntry() { } public void prevEntry() { } public void undo() { } public void redo() { } public void registerPopupMenuConstructors(int priority, IPopupMenuConstructor constructor) { } public void replaceEditText(String text) { } public void requestFocus() { } public void remarkOneMarker(String markerClassName) { } public void addFilter(List<Integer> entryList) { } public void removeFilter() { } }); }
protected void setUp() throws Exception { super.setUp(); TestCoreInitializer.initEditor(new IEditor() { public void activateEntry() { } public void changeCase(CHANGE_CASE_TO newCase) { } public void commitAndDeactivate() { } public void commitAndLeave() { } public SourceTextEntry getCurrentEntry() { return null; } public int getCurrentEntryNumber() { return 0; } public String getCurrentFile() { return null; } public String getSelectedText() { return null; } public EditorSettings getSettings() { return null; } public void gotoEntry(int entryNum) { } public void gotoFile(int fileIndex) { } public void gotoHistoryBack() { } public void gotoHistoryForward() { } public void insertText(String text) { } public void markActiveEntrySource( SourceTextEntry requiredActiveEntry, List<Mark> marks, String markerClassName) { } public void nextEntry() { } public void nextUntranslatedEntry() { } public void prevEntry() { } public void undo() { } public void redo() { } public void registerPopupMenuConstructors(int priority, IPopupMenuConstructor constructor) { } public void replaceEditText(String text) { } public void requestFocus() { } public void remarkOneMarker(String markerClassName) { } public void addFilter(List<Integer> entryList) { } public void removeFilter() { } }); }
diff --git a/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java b/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java index a1d104726..cd421c38d 100644 --- a/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java +++ b/plugins/SPIMAcquisition/spim/progacq/OMETIFFHandler.java @@ -1,198 +1,198 @@ package spim.progacq; import java.io.File; import ij.ImagePlus; import ij.process.ImageProcessor; import org.micromanager.utils.ReportingUtils; import loci.common.DataTools; import loci.common.services.ServiceFactory; import loci.formats.IFormatWriter; import loci.formats.ImageWriter; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.services.OMEXMLService; import mmcorej.CMMCore; import ome.xml.model.enums.DimensionOrder; import ome.xml.model.enums.PixelType; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; public class OMETIFFHandler implements AcqOutputHandler { private File outputDirectory; private IMetadata meta; private int imageCounter, sliceCounter; private IFormatWriter writer; private CMMCore core; private int stacks, timesteps; private AcqRow[] acqRows; private double deltat; public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev, String cDev, String zDev, String tDev, AcqRow[] acqRows, int iTimeSteps, double iDeltaT) { if(outDir == null || !outDir.exists() || !outDir.isDirectory()) throw new IllegalArgumentException("Null path specified: " + outDir.toString()); imageCounter = -1; sliceCounter = 0; stacks = acqRows.length; core = iCore; timesteps = iTimeSteps; deltat = iDeltaT; outputDirectory = outDir; this.acqRows = acqRows; try { meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata(); meta.createRoot(); meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0); for (int image = 0; image < stacks; ++image) { meta.setImageID(MetadataTools.createLSID("Image", image), image); AcqRow row = acqRows[image]; int depth = row.getDepth(); meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image); meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image); meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0); meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image); meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0); meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0); for (int t = 0; t < timesteps; ++t) { String fileName = makeFilename(image, t); for(int z = 0; z < depth; ++z) { int td = depth*t + z; meta.setUUIDFileName(fileName, image, td); // meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td); meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td); meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td); meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td); meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td); }; }; meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image); meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image); meta.setPixelsSizeZ(new PositiveInteger(depth), image); meta.setPixelsSizeC(new PositiveInteger(1), image); meta.setPixelsSizeT(new PositiveInteger(timesteps), image); - meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()), image); - meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()), image); - meta.setPixelsPhysicalSizeZ(new PositiveFloat(row.getZStepSize()*1.5D), image); // TODO: This is hardcoded. Change the DAL. + meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()*1.5D), image); + meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()*1.5D), image); + meta.setPixelsPhysicalSizeZ(new PositiveFloat(Math.max(row.getZStepSize(), 1.0D)*1.5D), image); // TODO: These are hardcoded. Change the DAL. meta.setPixelsTimeIncrement(new Double(deltat), image); } writer = new ImageWriter().getWriter(makeFilename(0, 0)); writer.setWriteSequentially(true); writer.setMetadataRetrieve(meta); writer.setInterleaved(false); writer.setValidBitsPerPixel((int) core.getImageBitDepth()); writer.setCompression("Uncompressed"); } catch(Throwable t) { t.printStackTrace(); throw new IllegalArgumentException(t); } } private static String makeFilename(int angleIndex, int timepoint) { return String.format("spim_TL%02d_Angle%01d.ome.tiff", (timepoint + 1), angleIndex); } private void openWriter(int angleIndex, int timepoint) throws Exception { writer.changeOutputFile(new File(outputDirectory, meta.getUUIDFileName(angleIndex, acqRows[angleIndex].getDepth()*timepoint)).getAbsolutePath()); writer.setSeries(angleIndex); meta.setUUID(meta.getUUIDValue(angleIndex, acqRows[angleIndex].getDepth()*timepoint)); sliceCounter = 0; } @Override public ImagePlus getImagePlus() throws Exception { // TODO Auto-generated method stub return null; } @Override public void beginStack(int axis) throws Exception { ReportingUtils.logMessage("Beginning stack along dimension " + axis); if(++imageCounter < stacks * timesteps) openWriter(imageCounter % stacks, imageCounter / stacks); } private int doubleAnnotations = 0; private int storeDouble(int image, int plane, int n, String name, double val) { String key = String.format("%d/%d/%d: %s", image, plane, n, name); meta.setDoubleAnnotationID(key, doubleAnnotations); meta.setDoubleAnnotationValue(val, doubleAnnotations); meta.setPlaneAnnotationRef(key, image, plane, n); return doubleAnnotations++; } @Override public void processSlice(ImageProcessor ip, double X, double Y, double Z, double theta, double deltaT) throws Exception { long bitDepth = core.getImageBitDepth(); byte[] data = bitDepth == 8 ? (byte[])ip.getPixels() : DataTools.shortsToBytes((short[])ip.getPixels(), true); int image = imageCounter % stacks; int timePoint = imageCounter / stacks; int plane = timePoint*acqRows[image].getDepth() + sliceCounter; meta.setPlanePositionX(X, image, plane); meta.setPlanePositionY(Y, image, plane); meta.setPlanePositionZ(Z, image, plane); meta.setPlaneTheZ(new NonNegativeInteger(sliceCounter), image, plane); meta.setPlaneTheT(new NonNegativeInteger(timePoint), image, plane); meta.setPlaneDeltaT(deltaT, image, plane); storeDouble(image, plane, 0, "Theta", theta); try { writer.saveBytes(plane, data); } catch(java.io.IOException ioe) { finalizeStack(0); if(writer != null) writer.close(); throw new Exception("Error writing OME-TIFF.", ioe); } ++sliceCounter; } @Override public void finalizeStack(int depth) throws Exception { ReportingUtils.logMessage("Finished stack along dimension " + depth); } @Override public void finalizeAcquisition() throws Exception { if(writer != null) writer.close(); imageCounter = 0; writer = null; } }
true
true
public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev, String cDev, String zDev, String tDev, AcqRow[] acqRows, int iTimeSteps, double iDeltaT) { if(outDir == null || !outDir.exists() || !outDir.isDirectory()) throw new IllegalArgumentException("Null path specified: " + outDir.toString()); imageCounter = -1; sliceCounter = 0; stacks = acqRows.length; core = iCore; timesteps = iTimeSteps; deltat = iDeltaT; outputDirectory = outDir; this.acqRows = acqRows; try { meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata(); meta.createRoot(); meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0); for (int image = 0; image < stacks; ++image) { meta.setImageID(MetadataTools.createLSID("Image", image), image); AcqRow row = acqRows[image]; int depth = row.getDepth(); meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image); meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image); meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0); meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image); meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0); meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0); for (int t = 0; t < timesteps; ++t) { String fileName = makeFilename(image, t); for(int z = 0; z < depth; ++z) { int td = depth*t + z; meta.setUUIDFileName(fileName, image, td); // meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td); meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td); meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td); meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td); meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td); }; }; meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image); meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image); meta.setPixelsSizeZ(new PositiveInteger(depth), image); meta.setPixelsSizeC(new PositiveInteger(1), image); meta.setPixelsSizeT(new PositiveInteger(timesteps), image); meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()), image); meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()), image); meta.setPixelsPhysicalSizeZ(new PositiveFloat(row.getZStepSize()*1.5D), image); // TODO: This is hardcoded. Change the DAL. meta.setPixelsTimeIncrement(new Double(deltat), image); } writer = new ImageWriter().getWriter(makeFilename(0, 0)); writer.setWriteSequentially(true); writer.setMetadataRetrieve(meta); writer.setInterleaved(false); writer.setValidBitsPerPixel((int) core.getImageBitDepth()); writer.setCompression("Uncompressed"); } catch(Throwable t) { t.printStackTrace(); throw new IllegalArgumentException(t); } }
public OMETIFFHandler(CMMCore iCore, File outDir, String xyDev, String cDev, String zDev, String tDev, AcqRow[] acqRows, int iTimeSteps, double iDeltaT) { if(outDir == null || !outDir.exists() || !outDir.isDirectory()) throw new IllegalArgumentException("Null path specified: " + outDir.toString()); imageCounter = -1; sliceCounter = 0; stacks = acqRows.length; core = iCore; timesteps = iTimeSteps; deltat = iDeltaT; outputDirectory = outDir; this.acqRows = acqRows; try { meta = new ServiceFactory().getInstance(OMEXMLService.class).createOMEXMLMetadata(); meta.createRoot(); meta.setDatasetID(MetadataTools.createLSID("Dataset", 0), 0); for (int image = 0; image < stacks; ++image) { meta.setImageID(MetadataTools.createLSID("Image", image), image); AcqRow row = acqRows[image]; int depth = row.getDepth(); meta.setPixelsID(MetadataTools.createLSID("Pixels", 0), image); meta.setPixelsDimensionOrder(DimensionOrder.XYCZT, image); meta.setPixelsBinDataBigEndian(Boolean.FALSE, image, 0); meta.setPixelsType(core.getImageBitDepth() == 8 ? PixelType.UINT8 : PixelType.UINT16, image); meta.setChannelID(MetadataTools.createLSID("Channel", 0), image, 0); meta.setChannelSamplesPerPixel(new PositiveInteger(1), image, 0); for (int t = 0; t < timesteps; ++t) { String fileName = makeFilename(image, t); for(int z = 0; z < depth; ++z) { int td = depth*t + z; meta.setUUIDFileName(fileName, image, td); // meta.setUUIDValue("urn:uuid:" + (String)UUID.nameUUIDFromBytes(fileName.getBytes()).toString(), image, td); meta.setTiffDataPlaneCount(new NonNegativeInteger(1), image, td); meta.setTiffDataFirstT(new NonNegativeInteger(t), image, td); meta.setTiffDataFirstC(new NonNegativeInteger(0), image, td); meta.setTiffDataFirstZ(new NonNegativeInteger(z), image, td); }; }; meta.setPixelsSizeX(new PositiveInteger((int)core.getImageWidth()), image); meta.setPixelsSizeY(new PositiveInteger((int)core.getImageHeight()), image); meta.setPixelsSizeZ(new PositiveInteger(depth), image); meta.setPixelsSizeC(new PositiveInteger(1), image); meta.setPixelsSizeT(new PositiveInteger(timesteps), image); meta.setPixelsPhysicalSizeX(new PositiveFloat(core.getPixelSizeUm()*1.5D), image); meta.setPixelsPhysicalSizeY(new PositiveFloat(core.getPixelSizeUm()*1.5D), image); meta.setPixelsPhysicalSizeZ(new PositiveFloat(Math.max(row.getZStepSize(), 1.0D)*1.5D), image); // TODO: These are hardcoded. Change the DAL. meta.setPixelsTimeIncrement(new Double(deltat), image); } writer = new ImageWriter().getWriter(makeFilename(0, 0)); writer.setWriteSequentially(true); writer.setMetadataRetrieve(meta); writer.setInterleaved(false); writer.setValidBitsPerPixel((int) core.getImageBitDepth()); writer.setCompression("Uncompressed"); } catch(Throwable t) { t.printStackTrace(); throw new IllegalArgumentException(t); } }
diff --git a/src/com/bukkit/cian1500ww/giveit/Giveme.java b/src/com/bukkit/cian1500ww/giveit/Giveme.java index 98dd926..ae20efb 100644 --- a/src/com/bukkit/cian1500ww/giveit/Giveme.java +++ b/src/com/bukkit/cian1500ww/giveit/Giveme.java @@ -1,112 +1,114 @@ package com.bukkit.cian1500ww.giveit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.ChatColor; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; /** * GiveIt for Bukkit * * @author cian1500ww [email protected] * @version 1.2 * This class deals with the /giveme command * */ public class Giveme { // Use the values defined in GiveIt public String name = GiveIt.name; public int amount = GiveIt.amount; private IdChange idchange = new IdChange(); private final LogToFile log = new LogToFile(); // Carry out checks and give player requested items public boolean giveme(CommandSender sender, String[] trimmedArgs){ System.out.println("Value after entering idChange:" +idchange.idChange(trimmedArgs[0])); if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } Player player = (Player)sender; PlayerInventory inventory = player.getInventory(); String item = idchange.idChange(trimmedArgs[0]); // Check to see if the player requested an item that isn't allowed if(GiveIt.prop.getProperty(item)==null){ player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry but it is not possible to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==true){ // Parse the player's name from the allowed.txt file String in = GiveIt.prop.getProperty(item); int position = in.indexOf("."); amount = Integer.parseInt(in.substring(0, position)); name = in.substring(position+1,in.length()); if(Integer.parseInt(trimmedArgs[1])<=amount && name.equalsIgnoreCase(player.getName())){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); + count--; } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount && name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); else if(!name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, but you are not allowed to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==false){ amount = Integer.parseInt(GiveIt.prop.getProperty(item)); if(Integer.parseInt(trimmedArgs[1])<=amount){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); + count--; } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); return true; } else return false; } }
false
true
public boolean giveme(CommandSender sender, String[] trimmedArgs){ System.out.println("Value after entering idChange:" +idchange.idChange(trimmedArgs[0])); if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } Player player = (Player)sender; PlayerInventory inventory = player.getInventory(); String item = idchange.idChange(trimmedArgs[0]); // Check to see if the player requested an item that isn't allowed if(GiveIt.prop.getProperty(item)==null){ player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry but it is not possible to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==true){ // Parse the player's name from the allowed.txt file String in = GiveIt.prop.getProperty(item); int position = in.indexOf("."); amount = Integer.parseInt(in.substring(0, position)); name = in.substring(position+1,in.length()); if(Integer.parseInt(trimmedArgs[1])<=amount && name.equalsIgnoreCase(player.getName())){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount && name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); else if(!name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, but you are not allowed to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==false){ amount = Integer.parseInt(GiveIt.prop.getProperty(item)); if(Integer.parseInt(trimmedArgs[1])<=amount){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); return true; } else return false; }
public boolean giveme(CommandSender sender, String[] trimmedArgs){ System.out.println("Value after entering idChange:" +idchange.idChange(trimmedArgs[0])); if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } Player player = (Player)sender; PlayerInventory inventory = player.getInventory(); String item = idchange.idChange(trimmedArgs[0]); // Check to see if the player requested an item that isn't allowed if(GiveIt.prop.getProperty(item)==null){ player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry but it is not possible to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==true){ // Parse the player's name from the allowed.txt file String in = GiveIt.prop.getProperty(item); int position = in.indexOf("."); amount = Integer.parseInt(in.substring(0, position)); name = in.substring(position+1,in.length()); if(Integer.parseInt(trimmedArgs[1])<=amount && name.equalsIgnoreCase(player.getName())){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); count--; } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount && name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); else if(!name.equalsIgnoreCase(player.getName())) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, but you are not allowed to spawn that item"); return true; } else if(GiveIt.prop.getProperty(item).contains(".")==false){ amount = Integer.parseInt(GiveIt.prop.getProperty(item)); if(Integer.parseInt(trimmedArgs[1])<=amount){ if(Integer.parseInt(trimmedArgs[1])>64){ int count = (Integer.parseInt(trimmedArgs[1]))/64; int remainder = (Integer.parseInt(trimmedArgs[1]))-((Integer.parseInt(trimmedArgs[1]))*count); while(count != 0){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(64); inventory.addItem(itemstack); count--; } ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(remainder); inventory.addItem(itemstack); } else if(Integer.parseInt(trimmedArgs[1])<=64){ ItemStack itemstack = new ItemStack(Integer.valueOf(item)); itemstack.setAmount(Integer.parseInt(trimmedArgs[1])); inventory.addItem(itemstack); } player.sendMessage(ChatColor.BLUE+ "GiveIt: Item added to your inventory"); // Log the player's requested items to log file log.writeOut(player, item, trimmedArgs[1]); } // Send a message to the player telling them to choose a lower amount else if(Integer.parseInt(trimmedArgs[1])>amount) player.sendMessage(ChatColor.DARK_RED+ "GiveIt: Sorry, please choose a lower amount"); return true; } else return false; }
diff --git a/src/org/melonbrew/fe/database/databases/SQLDB.java b/src/org/melonbrew/fe/database/databases/SQLDB.java index 6c0cd7c..0974de5 100755 --- a/src/org/melonbrew/fe/database/databases/SQLDB.java +++ b/src/org/melonbrew/fe/database/databases/SQLDB.java @@ -1,215 +1,215 @@ package org.melonbrew.fe.database.databases; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.melonbrew.fe.Fe; import org.melonbrew.fe.database.Account; import org.melonbrew.fe.database.Database; import com.niccholaspage.nSQL.Table; import com.niccholaspage.nSQL.query.SelectQuery; public abstract class SQLDB extends Database { private final Fe plugin; private final boolean supportsModification; private Connection connection; private String accountsName; private Table accounts; public SQLDB(Fe plugin, boolean supportsModification){ super(plugin); this.plugin = plugin; this.supportsModification = supportsModification; accountsName = "fe_accounts"; } public void setAccountTable(String accountsName){ this.accountsName = accountsName; } public boolean init(){ if (!checkConnection()){ return false; } return true; } public boolean checkConnection(){ try { if (connection == null || connection.isClosed()){ connection = getNewConnection(); if (connection.isClosed()){ return false; } accounts = new Table(connection, accountsName); accounts.create().create("name varchar(64)").create("money double").execute(); if (supportsModification){ query("ALTER TABLE " + accounts + " MODIFY name varchar(64)"); } } } catch (SQLException e){ e.printStackTrace(); return false; } return true; } protected abstract Connection getNewConnection(); public boolean query(String sql){ try { return connection.createStatement().execute(sql); } catch (SQLException e){ e.printStackTrace(); return false; } } public Connection getConnection(){ return connection; } public void close(){ try { connection.close(); } catch (SQLException e){ e.printStackTrace(); } } public List<Account> getTopAccounts(int size){ checkConnection(); String sql = "SELECT name FROM " + accountsName + " ORDER BY money DESC limit " + size; List<Account> topAccounts = new ArrayList<Account>(); try { ResultSet set = connection.createStatement().executeQuery(sql); while (set.next()){ topAccounts.add(getAccount(set.getString("name"))); } } catch (SQLException e){ } return topAccounts; } public List<Account> getAccounts(){ checkConnection(); List<Account> accounts = new ArrayList<Account>(); ResultSet set = this.accounts.select("name").execute(); try { while (set.next()){ accounts.add(getAccount(set.getString("name"))); } } catch (SQLException e){ } return accounts; } public double loadAccountMoney(String name){ checkConnection(); double money = -1; try { SelectQuery query = accounts.select().where("name", name); ResultSet set = query.execute(); while (set.next()){ money = set.getDouble("money"); } query.close(); } catch (SQLException e){ e.printStackTrace(); return -1; } return money; } public void removeAccount(String name){ checkConnection(); accounts.delete().where("name", name); } protected void saveAccount(String name, double money){ checkConnection(); if (accountExists(name)){ accounts.update().set("money", money).where("name", name).execute(); }else { accounts.insert().insert("name").insert("money").value(name).value(money).execute(); } } public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; - StringBuilder builder = new StringBuilder("DELETE FROM " + accounts + " WHERE name IN ("); + StringBuilder builder = new StringBuilder("DELETE FROM " + accountsName + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); builder.delete(builder.length() - 2, builder.length()).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } } }
true
true
public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; StringBuilder builder = new StringBuilder("DELETE FROM " + accounts + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); builder.delete(builder.length() - 2, builder.length()).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } }
public void clean(){ checkConnection(); try { SelectQuery query = accounts.select().where("money", plugin.getAPI().getDefaultHoldings()); ResultSet set = query.execute(); boolean executeQuery = false; StringBuilder builder = new StringBuilder("DELETE FROM " + accountsName + " WHERE name IN ("); while (set.next()){ String name = set.getString("name"); if (plugin.getServer().getPlayerExact(name) != null){ continue; } executeQuery = true; builder.append("'").append(name).append("', "); } set.close(); builder.delete(builder.length() - 2, builder.length()).append(")"); System.out.println(builder); if (executeQuery){ query(builder.toString()); } } catch (SQLException e){ } }
diff --git a/modules/dcache/src/main/java/diskCacheV111/vehicles/IoJobInfo.java b/modules/dcache/src/main/java/diskCacheV111/vehicles/IoJobInfo.java index 93b90321d7..e9af44c28e 100755 --- a/modules/dcache/src/main/java/diskCacheV111/vehicles/IoJobInfo.java +++ b/modules/dcache/src/main/java/diskCacheV111/vehicles/IoJobInfo.java @@ -1,40 +1,40 @@ // $Id: IoJobInfo.java,v 1.3 2004-11-05 12:07:19 tigran Exp $ // package diskCacheV111.vehicles; import diskCacheV111.util.* ; import org.dcache.pool.classic.PoolIORequest; public class IoJobInfo extends JobInfo { private final long _bytesTransferred; private final long _transferTime; private final long _lastTransferred; private final PnfsId _pnfsId; private static final long serialVersionUID = -7987228538353684951L; public IoJobInfo(final PoolIORequest request, int id){ super( request.getCreationTime(), - request.getTransferTime(), + request.getStartTime(), request.getState().toString(), id, request.getClient(), request.getClientId()) ; _pnfsId = request.getPnfsId(); _bytesTransferred = request.getBytesTransferred() ; _transferTime = request.getTransferTime(); _lastTransferred = request.getLastTransferred() ; } public long getTransferTime(){ return _transferTime ; } public long getBytesTransferred(){ return _bytesTransferred ; } public long getLastTransferred(){ return _lastTransferred ; } public PnfsId getPnfsId(){ return _pnfsId ; } public String toString(){ return super.toString()+ _pnfsId+ ";B="+_bytesTransferred+ ";T="+_transferTime+ ";L="+((System.currentTimeMillis()-_lastTransferred)/1000)+";"; } }
true
true
public IoJobInfo(final PoolIORequest request, int id){ super( request.getCreationTime(), request.getTransferTime(), request.getState().toString(), id, request.getClient(), request.getClientId()) ; _pnfsId = request.getPnfsId(); _bytesTransferred = request.getBytesTransferred() ; _transferTime = request.getTransferTime(); _lastTransferred = request.getLastTransferred() ; }
public IoJobInfo(final PoolIORequest request, int id){ super( request.getCreationTime(), request.getStartTime(), request.getState().toString(), id, request.getClient(), request.getClientId()) ; _pnfsId = request.getPnfsId(); _bytesTransferred = request.getBytesTransferred() ; _transferTime = request.getTransferTime(); _lastTransferred = request.getLastTransferred() ; }
diff --git a/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterSql.java b/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterSql.java index 0da49a1f0f..3708bccae4 100644 --- a/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterSql.java +++ b/sonar-core/src/main/java/org/sonar/core/measure/MeasureFilterSql.java @@ -1,266 +1,266 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.core.measure; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.sonar.api.measures.Metric; import org.sonar.core.persistence.Database; import org.sonar.core.persistence.DatabaseUtils; import org.sonar.core.persistence.dialect.PostgreSql; import org.sonar.core.resource.SnapshotDto; import javax.annotation.Nullable; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; class MeasureFilterSql { private final Database database; private final MeasureFilter filter; private final MeasureFilterContext context; private final StringBuilder sql = new StringBuilder(1000); private final List<Date> dateParameters = Lists.newArrayList(); MeasureFilterSql(Database database, MeasureFilter filter, MeasureFilterContext context) { this.database = database; this.filter = filter; this.context = context; init(); } List<MeasureFilterRow> execute(Connection connection) throws SQLException { PreparedStatement statement = connection.prepareStatement(sql.toString()); ResultSet rs = null; try { for (int index = 0; index < dateParameters.size(); index++) { statement.setDate(index + 1, dateParameters.get(index)); } rs = statement.executeQuery(); return process(rs); } finally { DatabaseUtils.closeQuietly(rs); DatabaseUtils.closeQuietly(statement); } } String sql() { return sql.toString(); } private void init() { - sql.append("SELECT block.id, max(block.rid) AS rid, max(block.rootid) AS rootid, max(sortval) AS sortval1, CASE WHEN sortval IS NULL THEN 1 ELSE 0 END AS sortval2 "); + sql.append("SELECT block.id, max(block.rid) AS rid, max(block.rootid) AS rootid, max(sortval) AS sortvalmax, CASE WHEN sortval IS NULL THEN 1 ELSE 0 END AS sortflag "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { sql.append(", max(crit_").append(index).append(")"); } sql.append(" FROM ("); appendSortBlock(); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { MeasureFilterCondition condition = filter.getMeasureConditions().get(index); sql.append(" UNION "); appendConditionBlock(index, condition); } - sql.append(") block GROUP BY block.id, sortval2"); + sql.append(") block GROUP BY block.id, sortflag"); if (!filter.getMeasureConditions().isEmpty()) { sql.append(" HAVING "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { if (index > 0) { sql.append(" AND "); } sql.append(" max(crit_").append(index).append(") IS NOT NULL "); } } if (filter.sort().isSortedByDatabase()) { - sql.append(" ORDER BY sortval2 ASC, sortval1 "); + sql.append(" ORDER BY sortflag ASC, sortvalmax "); sql.append(filter.sort().isAsc() ? "ASC " : "DESC "); } } private void appendSortBlock() { sql.append(" SELECT s.id, s.project_id AS rid, s.root_project_id AS rootid, ").append(filter.sort().column()).append(" AS sortval "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { MeasureFilterCondition condition = filter.getMeasureConditions().get(index); sql.append(", ").append(nullSelect(condition.metric())).append(" AS crit_").append(index); } sql.append(" FROM snapshots s INNER JOIN projects p ON s.project_id=p.id "); if (filter.isOnFavourites()) { sql.append(" INNER JOIN properties props ON props.resource_id=s.project_id "); } if (filter.sort().onMeasures()) { sql.append(" LEFT OUTER JOIN project_measures pm ON s.id=pm.snapshot_id AND pm.metric_id="); sql.append(filter.sort().metric().getId()); sql.append(" AND pm.rule_id IS NULL AND pm.rule_priority IS NULL AND pm.characteristic_id IS NULL AND pm.person_id IS NULL "); } sql.append(" WHERE "); appendResourceConditions(); } private void appendConditionBlock(int conditionIndex, MeasureFilterCondition condition) { sql.append(" SELECT s.id, s.project_id AS rid, s.root_project_id AS rootid, null AS sortval "); for (int j = 0; j < filter.getMeasureConditions().size(); j++) { sql.append(", "); if (j == conditionIndex) { sql.append(condition.valueColumn()); } else { sql.append(nullSelect(filter.getMeasureConditions().get(j).metric())); } sql.append(" AS crit_").append(j); } sql.append(" FROM snapshots s INNER JOIN projects p ON s.project_id=p.id INNER JOIN project_measures pm ON s.id=pm.snapshot_id "); if (filter.isOnFavourites()) { sql.append(" INNER JOIN properties props ON props.resource_id=s.project_id "); } sql.append(" WHERE "); appendResourceConditions(); sql.append(" AND pm.rule_id IS NULL AND pm.rule_priority IS NULL AND pm.characteristic_id IS NULL AND pm.person_id IS NULL AND "); condition.appendSqlCondition(sql); } private void appendResourceConditions() { sql.append(" s.status='P' AND s.islast=").append(database.getDialect().getTrueSqlValue()); if (context.getBaseSnapshot() == null) { sql.append(" AND p.copy_resource_id IS NULL "); } if (!filter.getResourceQualifiers().isEmpty()) { sql.append(" AND s.qualifier IN "); appendInStatement(filter.getResourceQualifiers(), sql); } if (!filter.getResourceScopes().isEmpty()) { sql.append(" AND s.scope IN "); appendInStatement(filter.getResourceScopes(), sql); } if (!filter.getResourceLanguages().isEmpty()) { sql.append(" AND p.language IN "); appendInStatement(filter.getResourceLanguages(), sql); } appendDateConditions(); appendFavouritesCondition(); appendResourceNameCondition(); appendResourceKeyCondition(); appendResourceBaseCondition(); } private void appendDateConditions() { if (filter.getFromDate() != null) { sql.append(" AND s.created_at >= ? "); dateParameters.add(new Date(filter.getFromDate().getTime())); } if (filter.getToDate() != null) { sql.append(" AND s.created_at <= ? "); dateParameters.add(new Date(filter.getToDate().getTime())); } } private void appendFavouritesCondition() { if (filter.isOnFavourites()) { sql.append(" AND props.prop_key='favourite' AND props.resource_id IS NOT NULL AND props.user_id="); sql.append(context.getUserId()); sql.append(" "); } } private void appendResourceBaseCondition() { SnapshotDto baseSnapshot = context.getBaseSnapshot(); if (baseSnapshot != null) { if (filter.isOnBaseResourceChildren()) { sql.append(" AND s.parent_snapshot_id=").append(baseSnapshot.getId()); } else { Long rootSnapshotId = (baseSnapshot.getRootId() != null ? baseSnapshot.getRootId() : baseSnapshot.getId()); sql.append(" AND s.root_snapshot_id=").append(rootSnapshotId); sql.append(" AND s.path LIKE '").append(StringUtils.defaultString(baseSnapshot.getPath())).append(baseSnapshot.getId()).append(".%'"); } } } private void appendResourceKeyCondition() { if (StringUtils.isNotBlank(filter.getResourceKeyRegexp())) { sql.append(" AND UPPER(p.kee) LIKE '"); // limitation : special characters _ and % are not escaped String regexp = StringEscapeUtils.escapeSql(filter.getResourceKeyRegexp()); regexp = StringUtils.replaceChars(regexp, '*', '%'); regexp = StringUtils.replaceChars(regexp, '?', '_'); sql.append(StringUtils.upperCase(regexp)).append("'"); } } private void appendResourceNameCondition() { if (StringUtils.isNotBlank(filter.getResourceName())) { sql.append(" AND s.project_id IN (SELECT rindex.resource_id FROM resource_index rindex WHERE rindex.kee like '"); sql.append(StringEscapeUtils.escapeSql(StringUtils.lowerCase(filter.getResourceName()))); sql.append("%'"); if (!filter.getResourceQualifiers().isEmpty()) { sql.append(" AND rindex.qualifier IN "); appendInStatement(filter.getResourceQualifiers(), sql); } sql.append(") "); } } List<MeasureFilterRow> process(ResultSet rs) throws SQLException { List<MeasureFilterRow> rows = Lists.newArrayList(); boolean sortTextValues = !filter.sort().isSortedByDatabase(); while (rs.next()) { MeasureFilterRow row = new MeasureFilterRow(rs.getLong(1), rs.getLong(2), rs.getLong(3)); if (sortTextValues) { row.setSortText(rs.getString(4)); } rows.add(row); } if (sortTextValues) { // database does not manage case-insensitive text sorting. It must be done programmatically Function<MeasureFilterRow, String> function = new Function<MeasureFilterRow, String>() { public String apply(@Nullable MeasureFilterRow row) { return (row != null ? StringUtils.defaultString(row.getSortText()) : ""); } }; Ordering<MeasureFilterRow> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).onResultOf(function).nullsFirst(); if (!filter.sort().isAsc()) { ordering = ordering.reverse(); } rows = ordering.sortedCopy(rows); } return rows; } private String nullSelect(Metric metric) { if (metric.isNumericType() && PostgreSql.ID.equals(database.getDialect().getId())) { return "null::integer"; } return "null"; } private static void appendInStatement(List<String> values, StringBuilder to) { to.append(" ('"); to.append(StringUtils.join(values, "','")); to.append("') "); } }
false
true
private void init() { sql.append("SELECT block.id, max(block.rid) AS rid, max(block.rootid) AS rootid, max(sortval) AS sortval1, CASE WHEN sortval IS NULL THEN 1 ELSE 0 END AS sortval2 "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { sql.append(", max(crit_").append(index).append(")"); } sql.append(" FROM ("); appendSortBlock(); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { MeasureFilterCondition condition = filter.getMeasureConditions().get(index); sql.append(" UNION "); appendConditionBlock(index, condition); } sql.append(") block GROUP BY block.id, sortval2"); if (!filter.getMeasureConditions().isEmpty()) { sql.append(" HAVING "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { if (index > 0) { sql.append(" AND "); } sql.append(" max(crit_").append(index).append(") IS NOT NULL "); } } if (filter.sort().isSortedByDatabase()) { sql.append(" ORDER BY sortval2 ASC, sortval1 "); sql.append(filter.sort().isAsc() ? "ASC " : "DESC "); } }
private void init() { sql.append("SELECT block.id, max(block.rid) AS rid, max(block.rootid) AS rootid, max(sortval) AS sortvalmax, CASE WHEN sortval IS NULL THEN 1 ELSE 0 END AS sortflag "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { sql.append(", max(crit_").append(index).append(")"); } sql.append(" FROM ("); appendSortBlock(); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { MeasureFilterCondition condition = filter.getMeasureConditions().get(index); sql.append(" UNION "); appendConditionBlock(index, condition); } sql.append(") block GROUP BY block.id, sortflag"); if (!filter.getMeasureConditions().isEmpty()) { sql.append(" HAVING "); for (int index = 0; index < filter.getMeasureConditions().size(); index++) { if (index > 0) { sql.append(" AND "); } sql.append(" max(crit_").append(index).append(") IS NOT NULL "); } } if (filter.sort().isSortedByDatabase()) { sql.append(" ORDER BY sortflag ASC, sortvalmax "); sql.append(filter.sort().isAsc() ? "ASC " : "DESC "); } }
diff --git a/x10.compiler/src/polyglot/visit/InnerClassRemover.java b/x10.compiler/src/polyglot/visit/InnerClassRemover.java index 6d054654c..7502acbc7 100644 --- a/x10.compiler/src/polyglot/visit/InnerClassRemover.java +++ b/x10.compiler/src/polyglot/visit/InnerClassRemover.java @@ -1,519 +1,519 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * This file was originally derived from the Polyglot extensible compiler framework. * * (C) Copyright 2000-2007 Polyglot project group, Cornell University * (C) Copyright IBM Corporation 2007-2012. */ package polyglot.visit; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import polyglot.ast.*; import polyglot.frontend.Job; import polyglot.main.Reporter; import polyglot.types.*; import polyglot.util.InternalCompilerError; import polyglot.util.Pair; import polyglot.util.Position; import polyglot.util.UniqueID; import polyglot.util.CollectionUtil; import x10.util.CollectionFactory; // TODO: //Convert closures to anon //Add frame classes around anon and local //now all classes access only final locals //Convert local and anon to member //Dup inner member to static //Remove inner member public abstract class InnerClassRemover extends ContextVisitor { // Name of field used to carry a pointer to the enclosing class. public static final Name OUTER_FIELD_NAME = Name.make("out$"); public InnerClassRemover(Job job, TypeSystem ts, NodeFactory nf) { super(job, ts, nf); } protected Map<ClassDef, FieldDef> outerFieldInstance = CollectionFactory.newHashMap(); /** Get a reference to the enclosing instance of the current class that is of type containerClass */ Expr getContainer(Position pos, Expr this_, ClassType currentClass, ClassType containerClass) { if (containerClass.def() == currentClass.def()) return this_; pos = pos.markCompilerGenerated(); ClassType currentContainer = currentClass.container().toClass(); FieldDef fi = boxThis(currentClass, currentContainer); Field f = nf.Field(pos, this_, nf.Id(pos, OUTER_FIELD_NAME)); f = f.fieldInstance(fi.asInstance()); f = (Field) f.type(fi.asInstance().type()); f = f.targetImplicit(false); return getContainer(pos, f, currentContainer, containerClass); } protected abstract ContextVisitor localClassRemover(); public Node override(Node parent, Node n) { if (n instanceof SourceFile) { ContextVisitor lcv = localClassRemover(); lcv = (ContextVisitor) lcv.begin(); lcv = (ContextVisitor) lcv.context(context); if (reporter.should_report(Reporter.innerremover, 1)) { System.out.println(">>> output ----------------------"); n.prettyPrint(System.out); System.out.println("<<< output ----------------------"); } n = n.visit(lcv); if (reporter.should_report(Reporter.innerremover, 1)) { System.out.println(">>> locals removed ----------------------"); n.prettyPrint(System.out); System.out.println("<<< locals removed ----------------------"); } n = this.visitEdgeNoOverride(parent, n); if (reporter.should_report(Reporter.innerremover, 1)) { System.out.println(">>> inners removed ----------------------"); n.prettyPrint(System.out); System.out.println("<<< inners removed ----------------------"); } return n; } else { return null; } } protected Node leaveCall(Node old, Node n, NodeVisitor v) { if (n instanceof Special) { return fixSpecial((Special) n); } else if (n instanceof Field) { return fixField((Field) n); } else if (n instanceof FieldAssign) { return fixFieldAssign((FieldAssign) n); } else if (n instanceof Call) { return fixCall((Call) n); } else if (n instanceof New) { return fixNew((New) n); } else if (n instanceof ConstructorCall) { return fixConstructorCall((ConstructorCall) n); } else if (n instanceof ClassDecl) { return fixClassDecl((ClassDecl) n); } else if (n instanceof TypeNode) { return fixTypeNode((TypeNode) n); } return n; } protected Expr fixSpecial(Special s) { if (s.qualifier() == null) return s; assert s.qualifier().type().toClass() != null; Context context = this.context(); if (s.qualifier().type().toClass().def() == context.currentClassDef()) return s; Position pos = s.position().markCompilerGenerated(); return getContainer(pos, nf.This(pos).type(context.currentClass()), context.currentClass(), s.qualifier().type().toClass()); } protected Node fixField(Field f) { if (f.isTargetImplicit() && !(f.target() instanceof Special)) return f.targetImplicit(false); return f; } protected Node fixFieldAssign(FieldAssign f) { if (f.targetImplicit() && !(f.target() instanceof Special)) return f.targetImplicit(false); return f; } protected Node fixCall(Call c) { if (c.isTargetImplicit() && !(c.target() instanceof Special)) return c.targetImplicit(false); return c; } public TypeNode fixTypeNode(TypeNode tn) { return tn; } public New fixNew(New neu) { Expr q = neu.qualifier(); if (q == null) return neu; // Add the qualifier as an argument to constructor invocations. neu = neu.qualifier(null); ConstructorInstance ci = neu.constructorInstance(); // Fix the ci. List<Type> argTypes = new ArrayList<Type>(); argTypes.add(q.type()); argTypes.addAll(ci.formalTypes()); ci = ci.formalTypes(argTypes); neu = neu.constructorInstance(ci); List<Expr> args = new ArrayList<Expr>(); args.add(q); args.addAll(neu.arguments()); neu = (New) neu.arguments(args); return neu; } protected Node fixConstructorCall(ConstructorCall cc) { // Add the qualifier as an argument to constructor invocations. if (cc.kind() != ConstructorCall.SUPER) { // FIXME: [IP] Why? What about calls to this()? return cc; } ConstructorInstance ci = cc.constructorInstance(); ClassType ct = ci.container().toClass(); // NOTE: we require that a constructor call to a non-static member have a qualifier. // We can't check for this now, though, since the type information may already have been // rewritten. // // Add a qualifier to non-static member class super() calls if not present. // if (ct.isMember() && ! ct.flags().isStatic()) { // if (cc.qualifier() == null) { // cc = cc.qualifier(nf.This(pos).type(context.currentClass())); // } // } if (cc.qualifier() == null) { return cc; } Expr q = cc.qualifier(); cc = cc.qualifier(null); boolean fixCI = cc.arguments().size()+1 != ci.formalTypes().size(); // if (q == null) { // if (ct.isMember() && ! ct.flags().isStatic()) { // q = getContainer(pos, nf.Special(pos, Special.THIS).type(context.currentClass()), context.currentClass(), ct); // } // else if (ct.isMember()) { // // might have already been rewritten to static. If so, the CI should have been rewritten also. // if (((ConstructorInstance) ci.declaration()).formalTypes().size() >= cc.arguments().size()) { // q = nf.Special(pos, Special.THIS).type(context.currentClass()); // } // } // } // Fix the ci if a copy; otherwise, let the ci be modified at the declaration node. if (fixCI) { List<Type> args = new ArrayList<Type>(); args.add(q.type()); args.addAll(ci.formalTypes()); ci = ci.formalTypes(args); cc = cc.constructorInstance(ci); } List<Expr> args = new ArrayList<Expr>(); args.add(q); args.addAll(cc.arguments()); cc = (ConstructorCall) cc.arguments(args); return cc; } public static boolean isInner(ClassDef def) { return def.isMember() && (!def.flags().isStatic() || def.wasInner()); } protected ClassDecl fixClassDecl(ClassDecl cd) { if (cd.classDef().isMember() && !cd.flags().flags().isStatic()) { cd.classDef().setWasInner(true); cd.classDef().flags(cd.classDef().flags().Static()); Flags f = cd.classDef().flags(); cd = cd.flags(cd.flags().flags(f)); Context context = this.context(); assert (Types.get(cd.classDef().container()).toClass().def() == context.currentClass().def()); // Add a field for the enclosing class. ClassType ct = context.currentClass(); FieldDef fi = boxThis(cd.classDef().asType(), ct); cd = addFieldsToClass(cd, Collections.singletonList(fi), ts, nf, true); cd = fixQualifiers(cd); } return cd; } public ClassDecl fixQualifiers(ClassDecl cd) { return (ClassDecl) cd.visitChildren(new NodeVisitor() { LocalDef li; public Node override(Node parent, Node n) { if (n instanceof ClassBody) { return null; } if (n instanceof ConstructorDecl) { return null; } if (parent instanceof ConstructorDecl && n instanceof Formal) { Formal f = (Formal) n; LocalDef li = f.localDef(); if (li.name().equals(OUTER_FIELD_NAME)) { this.li = li; } return n; } if (parent instanceof ConstructorDecl && n instanceof Block) { return null; } if (parent instanceof Block && n instanceof ConstructorCall) { return null; } if (parent instanceof ConstructorCall) { return null; } return n; // // if (n instanceof ClassMember) { // this.li = null; // return n; // } // // return null; } public Node leave(Node parent, Node old, Node n, NodeVisitor v) { if (parent instanceof ConstructorCall && li != null && n instanceof Expr) { return fixQualifier((Expr) n, li); } return n; } }); } public Expr fixQualifier(Expr e, final LocalDef li) { return (Expr) e.visit(new NodeVisitor() { public Node leave(Node old, Node n, NodeVisitor v) { if (n instanceof Field) { Field f = (Field) n; if (f.target() instanceof Special) { Special s = (Special) f.target(); if (s.kind() == Special.THIS && f.name().id().equals(OUTER_FIELD_NAME)) { Local l = nf.Local(n.position().markCompilerGenerated(), f.name()); l = l.localInstance(li.asInstance()); l = (Local) l.type(li.asInstance().type()); return l; } } } if (n instanceof FieldAssign) { FieldAssign f = (FieldAssign) n; if (f.target() instanceof Special) { Special s = (Special) f.target(); if (s.kind() == Special.THIS && f.name().id().equals(OUTER_FIELD_NAME)) { Local l = nf.Local(n.position().markCompilerGenerated(), f.name()); l = l.localInstance(li.asInstance()); l = (Local) l.type(li.asInstance().type()); return l; } } } return n; } }); } public ClassDecl addFieldsToClass(ClassDecl cd, List<FieldDef> newFields, TypeSystem ts, NodeFactory nf, boolean rewriteMembers) { if (newFields.isEmpty()) { return cd; } ClassBody b = cd.body(); // Add the new fields to the class. List<ClassMember> newMembers = new ArrayList<ClassMember>(); for (Iterator<FieldDef> i = newFields.iterator(); i.hasNext(); ) { FieldDef fi = i.next(); Position pos = fi.position().markCompilerGenerated(); FieldDecl fd = nf.FieldDecl(pos, nf.FlagsNode(pos, fi.flags()), nf.CanonicalTypeNode(pos, fi.type()), nf.Id(pos, fi.name())); fd = fd.fieldDef(fi); newMembers.add(fd); } for (Iterator<ClassMember> i = b.members().iterator(); i.hasNext(); ) { ClassMember m = i.next(); if (m instanceof ConstructorDecl) { ConstructorDecl td = (ConstructorDecl) m; // Create a list of formals to add to the constructor. List<Formal> formals = new ArrayList<Formal>(); List<LocalDef> locals = new ArrayList<LocalDef>(); for (FieldDef fi : newFields) { Position pos = fi.position().markCompilerGenerated(); LocalDef li = ts.localDef(pos, Flags.FINAL, fi.type(), fi.name()); li.setNotConstant(); Formal formal = nf.Formal(pos, nf.FlagsNode(pos, li.flags()), nf.CanonicalTypeNode(pos, li.type()), nf.Id(pos, li.name())); formal = formal.localDef(li); formals.add(formal); locals.add(li); } List<Formal> newFormals = new ArrayList<Formal>(); newFormals.addAll(formals); newFormals.addAll(td.formals()); td = td.formals(newFormals); // Create a list of field assignments. List<Stmt> statements = new ArrayList<Stmt>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); LocalDef li = formals.get(j).localDef(); Position pos = fi.position().markCompilerGenerated(); Local l = nf.Local(pos, nf.Id(pos, li.name())); l = (Local) l.type(li.asInstance().type()); l = l.localInstance(li.asInstance()); FieldAssign a = nf.FieldAssign(pos, nf.This(pos).type(fi.asInstance().container()), nf.Id(pos, fi.name()), Assign.ASSIGN, l); a = (FieldAssign) a.type(fi.asInstance().type()); a = (FieldAssign) a.fieldInstance(fi.asInstance()); a = a.targetImplicit(false); Eval e = nf.Eval(pos, a); statements.add(e); } // Add the assignments to the constructor body after the super call. // Or, add pass the locals to another constructor if a this call. Block block = td.body(); if (block.statements().size() > 0) { Stmt s0 = (Stmt) block.statements().get(0); if (s0 instanceof ConstructorCall) { ConstructorCall cc = (ConstructorCall) s0; ConstructorInstance ci = cc.constructorInstance(); if (cc.kind() == ConstructorCall.THIS) { // Not a super call. Pass the locals as arguments. List<Expr> arguments = new ArrayList<Expr>(); for (Iterator<Stmt> j = statements.iterator(); j.hasNext(); ) { Stmt si = j.next(); Eval e = (Eval) si; Assign a = (Assign) e.expr(); arguments.add(a.right()); } // Modify the CI if it is a copy of the declaration CI. // If not a copy, it will get modified at the declaration. { List<Type> newFormalTypes = new ArrayList<Type>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); newFormalTypes.add(fi.asInstance().type()); } newFormalTypes.addAll(ci.formalTypes()); ci = ci.formalTypes(newFormalTypes); cc = cc.constructorInstance(ci); } arguments.addAll(cc.arguments()); cc = (ConstructorCall) cc.arguments(arguments); } else { // A super call. Don't rewrite it here; the visitor will handle it elsewhere. } // prepend the super call statements.add(0, cc); } else { // [DC] The absence of this case in previous versions was a bug // but I believe it would only have caused a problem with the root (Object) // which was not an inner class (and was @NativeRep anyway) - statements.add(0, s0); + statements.add(s0); } statements.addAll(block.statements().subList(1, block.statements().size())); } else { statements.addAll(block.statements()); } block = block.statements(statements); td = (ConstructorDecl) td.body(block); newMembers.add(td); adjustConstructorFormals(td.constructorDef(), newFormals); } else { newMembers.add(m); } } b = b.members(newMembers); return cd.body(b); } protected void adjustConstructorFormals(ConstructorDef ci, List<Formal> newFormals) { List<Ref<? extends Type>> newFormalTypes = new ArrayList<Ref<? extends Type>>(); for (Formal f : newFormals) { newFormalTypes.add(f.type().typeRef()); } ci.setFormalTypes(newFormalTypes); } // Add local variables to the argument list until it matches the declaration. List<Expr> addArgs(ProcedureCall n, ConstructorInstance nci, Expr q) { if (nci == null || q == null) return n.arguments(); List<Expr> args = new ArrayList<Expr>(); args.add(q); args.addAll(n.arguments()); assert args.size() == nci.formalTypes().size(); return args; } // Create a field instance for a qualified this. protected FieldDef boxThis(ClassType currClass, ClassType outerClass) { FieldDef fi = outerFieldInstance.get(currClass.def()); if (fi != null) return fi; Position pos = outerClass.position(); fi = ts.fieldDef(pos, Types.ref(currClass), Flags.FINAL.Private(), Types.ref(outerClass), OUTER_FIELD_NAME); fi.setNotConstant(); currClass.def().addField(fi); // FIXME: should boxThis() be idempotent? outerFieldInstance.put(currClass.def(), fi); return fi; } public static <K,V> V hashGet(Map<K,V> map, K k, V v) { return LocalClassRemover.<K,V>hashGet(map, k, v); } }
true
true
public ClassDecl addFieldsToClass(ClassDecl cd, List<FieldDef> newFields, TypeSystem ts, NodeFactory nf, boolean rewriteMembers) { if (newFields.isEmpty()) { return cd; } ClassBody b = cd.body(); // Add the new fields to the class. List<ClassMember> newMembers = new ArrayList<ClassMember>(); for (Iterator<FieldDef> i = newFields.iterator(); i.hasNext(); ) { FieldDef fi = i.next(); Position pos = fi.position().markCompilerGenerated(); FieldDecl fd = nf.FieldDecl(pos, nf.FlagsNode(pos, fi.flags()), nf.CanonicalTypeNode(pos, fi.type()), nf.Id(pos, fi.name())); fd = fd.fieldDef(fi); newMembers.add(fd); } for (Iterator<ClassMember> i = b.members().iterator(); i.hasNext(); ) { ClassMember m = i.next(); if (m instanceof ConstructorDecl) { ConstructorDecl td = (ConstructorDecl) m; // Create a list of formals to add to the constructor. List<Formal> formals = new ArrayList<Formal>(); List<LocalDef> locals = new ArrayList<LocalDef>(); for (FieldDef fi : newFields) { Position pos = fi.position().markCompilerGenerated(); LocalDef li = ts.localDef(pos, Flags.FINAL, fi.type(), fi.name()); li.setNotConstant(); Formal formal = nf.Formal(pos, nf.FlagsNode(pos, li.flags()), nf.CanonicalTypeNode(pos, li.type()), nf.Id(pos, li.name())); formal = formal.localDef(li); formals.add(formal); locals.add(li); } List<Formal> newFormals = new ArrayList<Formal>(); newFormals.addAll(formals); newFormals.addAll(td.formals()); td = td.formals(newFormals); // Create a list of field assignments. List<Stmt> statements = new ArrayList<Stmt>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); LocalDef li = formals.get(j).localDef(); Position pos = fi.position().markCompilerGenerated(); Local l = nf.Local(pos, nf.Id(pos, li.name())); l = (Local) l.type(li.asInstance().type()); l = l.localInstance(li.asInstance()); FieldAssign a = nf.FieldAssign(pos, nf.This(pos).type(fi.asInstance().container()), nf.Id(pos, fi.name()), Assign.ASSIGN, l); a = (FieldAssign) a.type(fi.asInstance().type()); a = (FieldAssign) a.fieldInstance(fi.asInstance()); a = a.targetImplicit(false); Eval e = nf.Eval(pos, a); statements.add(e); } // Add the assignments to the constructor body after the super call. // Or, add pass the locals to another constructor if a this call. Block block = td.body(); if (block.statements().size() > 0) { Stmt s0 = (Stmt) block.statements().get(0); if (s0 instanceof ConstructorCall) { ConstructorCall cc = (ConstructorCall) s0; ConstructorInstance ci = cc.constructorInstance(); if (cc.kind() == ConstructorCall.THIS) { // Not a super call. Pass the locals as arguments. List<Expr> arguments = new ArrayList<Expr>(); for (Iterator<Stmt> j = statements.iterator(); j.hasNext(); ) { Stmt si = j.next(); Eval e = (Eval) si; Assign a = (Assign) e.expr(); arguments.add(a.right()); } // Modify the CI if it is a copy of the declaration CI. // If not a copy, it will get modified at the declaration. { List<Type> newFormalTypes = new ArrayList<Type>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); newFormalTypes.add(fi.asInstance().type()); } newFormalTypes.addAll(ci.formalTypes()); ci = ci.formalTypes(newFormalTypes); cc = cc.constructorInstance(ci); } arguments.addAll(cc.arguments()); cc = (ConstructorCall) cc.arguments(arguments); } else { // A super call. Don't rewrite it here; the visitor will handle it elsewhere. } // prepend the super call statements.add(0, cc); } else { // [DC] The absence of this case in previous versions was a bug // but I believe it would only have caused a problem with the root (Object) // which was not an inner class (and was @NativeRep anyway) statements.add(0, s0); } statements.addAll(block.statements().subList(1, block.statements().size())); } else { statements.addAll(block.statements()); } block = block.statements(statements); td = (ConstructorDecl) td.body(block); newMembers.add(td); adjustConstructorFormals(td.constructorDef(), newFormals); } else { newMembers.add(m); } } b = b.members(newMembers); return cd.body(b); }
public ClassDecl addFieldsToClass(ClassDecl cd, List<FieldDef> newFields, TypeSystem ts, NodeFactory nf, boolean rewriteMembers) { if (newFields.isEmpty()) { return cd; } ClassBody b = cd.body(); // Add the new fields to the class. List<ClassMember> newMembers = new ArrayList<ClassMember>(); for (Iterator<FieldDef> i = newFields.iterator(); i.hasNext(); ) { FieldDef fi = i.next(); Position pos = fi.position().markCompilerGenerated(); FieldDecl fd = nf.FieldDecl(pos, nf.FlagsNode(pos, fi.flags()), nf.CanonicalTypeNode(pos, fi.type()), nf.Id(pos, fi.name())); fd = fd.fieldDef(fi); newMembers.add(fd); } for (Iterator<ClassMember> i = b.members().iterator(); i.hasNext(); ) { ClassMember m = i.next(); if (m instanceof ConstructorDecl) { ConstructorDecl td = (ConstructorDecl) m; // Create a list of formals to add to the constructor. List<Formal> formals = new ArrayList<Formal>(); List<LocalDef> locals = new ArrayList<LocalDef>(); for (FieldDef fi : newFields) { Position pos = fi.position().markCompilerGenerated(); LocalDef li = ts.localDef(pos, Flags.FINAL, fi.type(), fi.name()); li.setNotConstant(); Formal formal = nf.Formal(pos, nf.FlagsNode(pos, li.flags()), nf.CanonicalTypeNode(pos, li.type()), nf.Id(pos, li.name())); formal = formal.localDef(li); formals.add(formal); locals.add(li); } List<Formal> newFormals = new ArrayList<Formal>(); newFormals.addAll(formals); newFormals.addAll(td.formals()); td = td.formals(newFormals); // Create a list of field assignments. List<Stmt> statements = new ArrayList<Stmt>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); LocalDef li = formals.get(j).localDef(); Position pos = fi.position().markCompilerGenerated(); Local l = nf.Local(pos, nf.Id(pos, li.name())); l = (Local) l.type(li.asInstance().type()); l = l.localInstance(li.asInstance()); FieldAssign a = nf.FieldAssign(pos, nf.This(pos).type(fi.asInstance().container()), nf.Id(pos, fi.name()), Assign.ASSIGN, l); a = (FieldAssign) a.type(fi.asInstance().type()); a = (FieldAssign) a.fieldInstance(fi.asInstance()); a = a.targetImplicit(false); Eval e = nf.Eval(pos, a); statements.add(e); } // Add the assignments to the constructor body after the super call. // Or, add pass the locals to another constructor if a this call. Block block = td.body(); if (block.statements().size() > 0) { Stmt s0 = (Stmt) block.statements().get(0); if (s0 instanceof ConstructorCall) { ConstructorCall cc = (ConstructorCall) s0; ConstructorInstance ci = cc.constructorInstance(); if (cc.kind() == ConstructorCall.THIS) { // Not a super call. Pass the locals as arguments. List<Expr> arguments = new ArrayList<Expr>(); for (Iterator<Stmt> j = statements.iterator(); j.hasNext(); ) { Stmt si = j.next(); Eval e = (Eval) si; Assign a = (Assign) e.expr(); arguments.add(a.right()); } // Modify the CI if it is a copy of the declaration CI. // If not a copy, it will get modified at the declaration. { List<Type> newFormalTypes = new ArrayList<Type>(); for (int j = 0; j < newFields.size(); j++) { FieldDef fi = newFields.get(j); newFormalTypes.add(fi.asInstance().type()); } newFormalTypes.addAll(ci.formalTypes()); ci = ci.formalTypes(newFormalTypes); cc = cc.constructorInstance(ci); } arguments.addAll(cc.arguments()); cc = (ConstructorCall) cc.arguments(arguments); } else { // A super call. Don't rewrite it here; the visitor will handle it elsewhere. } // prepend the super call statements.add(0, cc); } else { // [DC] The absence of this case in previous versions was a bug // but I believe it would only have caused a problem with the root (Object) // which was not an inner class (and was @NativeRep anyway) statements.add(s0); } statements.addAll(block.statements().subList(1, block.statements().size())); } else { statements.addAll(block.statements()); } block = block.statements(statements); td = (ConstructorDecl) td.body(block); newMembers.add(td); adjustConstructorFormals(td.constructorDef(), newFormals); } else { newMembers.add(m); } } b = b.members(newMembers); return cd.body(b); }
diff --git a/source/de/anomic/document/parser/docParser.java b/source/de/anomic/document/parser/docParser.java index a91a541b0..d50ff7641 100644 --- a/source/de/anomic/document/parser/docParser.java +++ b/source/de/anomic/document/parser/docParser.java @@ -1,134 +1,134 @@ //docParser.java //------------------------ //part of YaCy //(C) by Michael Peter Christen; [email protected] //first published on http://www.anomic.de //Frankfurt, Germany, 2005 // //this file is contributed by Martin Thelian // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // //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 de.anomic.document.parser; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Set; import de.anomic.document.AbstractParser; import de.anomic.document.Idiom; import de.anomic.document.ParserException; import de.anomic.document.Document; import de.anomic.yacy.yacyURL; import org.apache.poi.hwpf.extractor.WordExtractor; public class docParser extends AbstractParser implements Idiom { /** * a list of mime types that are supported by this parser class * @see #getSupportedMimeTypes() */ public static final Set<String> SUPPORTED_MIME_TYPES = new HashSet<String>(); public static final Set<String> SUPPORTED_EXTENSIONS = new HashSet<String>(); static { SUPPORTED_EXTENSIONS.add("doc"); SUPPORTED_MIME_TYPES.add("application/msword"); SUPPORTED_MIME_TYPES.add("application/doc"); SUPPORTED_MIME_TYPES.add("appl/text"); SUPPORTED_MIME_TYPES.add("application/vnd.msword"); SUPPORTED_MIME_TYPES.add("application/vnd.ms-word"); SUPPORTED_MIME_TYPES.add("application/winword"); SUPPORTED_MIME_TYPES.add("application/word"); SUPPORTED_MIME_TYPES.add("application/x-msw6"); SUPPORTED_MIME_TYPES.add("application/x-msword"); } public docParser() { super("Word Document Parser"); } public Document parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException { final WordExtractor extractor; try { extractor = new WordExtractor(source); - } catch (IOException e) { + } catch (Exception e) { throw new ParserException("error in docParser, WordTextExtractorFactory: " + e.getMessage(), location); } StringBuilder contents = new StringBuilder(); try { contents.append(extractor.getText().trim()); contents.append(" "); contents.append(extractor.getHeaderText()); contents.append(" "); contents.append(extractor.getFooterText()); } catch (Exception e) { throw new ParserException("error in docParser, getText: " + e.getMessage(), location); } String title = (contents.length() > 240) ? contents.substring(0,240) : contents.toString().trim(); title.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim(); if (title.length() > 80) title = title.substring(0, 80); int l = title.length(); while (true) { title = title.replaceAll(" ", " "); if (title.length() == l) break; l = title.length(); } Document theDoc; try { theDoc = new Document( location, mimeType, "UTF-8", null, null, title, "", // TODO: AUTHOR null, null, contents.toString().getBytes("UTF-8"), null, null); } catch (UnsupportedEncodingException e) { throw new ParserException("error in docParser, getBytes: " + e.getMessage(), location); } return theDoc; } public Set<String> supportedMimeTypes() { return SUPPORTED_MIME_TYPES; } public Set<String> supportedExtensions() { return SUPPORTED_EXTENSIONS; } @Override public void reset() { // Nothing todo here at the moment super.reset(); } }
true
true
public Document parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException { final WordExtractor extractor; try { extractor = new WordExtractor(source); } catch (IOException e) { throw new ParserException("error in docParser, WordTextExtractorFactory: " + e.getMessage(), location); } StringBuilder contents = new StringBuilder(); try { contents.append(extractor.getText().trim()); contents.append(" "); contents.append(extractor.getHeaderText()); contents.append(" "); contents.append(extractor.getFooterText()); } catch (Exception e) { throw new ParserException("error in docParser, getText: " + e.getMessage(), location); } String title = (contents.length() > 240) ? contents.substring(0,240) : contents.toString().trim(); title.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim(); if (title.length() > 80) title = title.substring(0, 80); int l = title.length(); while (true) { title = title.replaceAll(" ", " "); if (title.length() == l) break; l = title.length(); } Document theDoc; try { theDoc = new Document( location, mimeType, "UTF-8", null, null, title, "", // TODO: AUTHOR null, null, contents.toString().getBytes("UTF-8"), null, null); } catch (UnsupportedEncodingException e) { throw new ParserException("error in docParser, getBytes: " + e.getMessage(), location); } return theDoc; }
public Document parse(final yacyURL location, final String mimeType, final String charset, final InputStream source) throws ParserException, InterruptedException { final WordExtractor extractor; try { extractor = new WordExtractor(source); } catch (Exception e) { throw new ParserException("error in docParser, WordTextExtractorFactory: " + e.getMessage(), location); } StringBuilder contents = new StringBuilder(); try { contents.append(extractor.getText().trim()); contents.append(" "); contents.append(extractor.getHeaderText()); contents.append(" "); contents.append(extractor.getFooterText()); } catch (Exception e) { throw new ParserException("error in docParser, getText: " + e.getMessage(), location); } String title = (contents.length() > 240) ? contents.substring(0,240) : contents.toString().trim(); title.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\t"," ").trim(); if (title.length() > 80) title = title.substring(0, 80); int l = title.length(); while (true) { title = title.replaceAll(" ", " "); if (title.length() == l) break; l = title.length(); } Document theDoc; try { theDoc = new Document( location, mimeType, "UTF-8", null, null, title, "", // TODO: AUTHOR null, null, contents.toString().getBytes("UTF-8"), null, null); } catch (UnsupportedEncodingException e) { throw new ParserException("error in docParser, getBytes: " + e.getMessage(), location); } return theDoc; }
diff --git a/src/nl/b3p/viewer/util/LayerListHelper.java b/src/nl/b3p/viewer/util/LayerListHelper.java index e6cd4b504..d9ebd7d52 100644 --- a/src/nl/b3p/viewer/util/LayerListHelper.java +++ b/src/nl/b3p/viewer/util/LayerListHelper.java @@ -1,102 +1,105 @@ /* * Copyright (C) 2012 B3Partners B.V. * * 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 nl.b3p.viewer.util; import java.util.ArrayList; import java.util.List; import nl.b3p.viewer.config.app.ApplicationLayer; import nl.b3p.viewer.config.app.Level; import nl.b3p.viewer.config.services.ArcGISFeatureSource; import nl.b3p.viewer.config.services.ArcGISService; import nl.b3p.viewer.config.services.Layer; import nl.b3p.viewer.config.services.WMSService; /** * * @author Meine Toonen [email protected] */ public class LayerListHelper { /** * Get a list of Layers from the level and its subLevels * * @param level * @return A list of Layer objects */ public static List<ApplicationLayer> getLayers(Level level,Boolean filterable, Boolean bufferable, Boolean editable ,Boolean influence ,Boolean arc ,Boolean wfs ,Boolean attribute, Boolean hasConfiguredLayers, List<Long> possibleLayers) { List<ApplicationLayer> layers = new ArrayList<ApplicationLayer>(); //get all the layers of this level for (ApplicationLayer appLayer : level.getLayers()) { Layer l = appLayer.getService().getLayer(appLayer.getLayerName()); + if(l == null){ + continue; + } if(filterable) { // The value of l.isFilterable() for WMS layers is not meaningful // at the moment... Always assume a WMS layer is filterable if // the layer has a feature type. There is a checkbox for an admin // to specify manually if a layer supports SLD filtering for GetMap if(l.getService() instanceof WMSService) { if(l.getFeatureType() == null) { continue; } } else { if(!l.isFilterable()) { continue; } } } if(bufferable && !l.isBufferable() ) { continue; } if(filterable && l.getService() instanceof ArcGISService){ if(l.getFeatureType() == null ){ continue; }else if(! (l.getFeatureType().getFeatureSource() instanceof ArcGISFeatureSource )){ continue; } } if (editable && (l.getFeatureType() == null || !l.getFeatureType().isWriteable())) { continue; } if (influence && !appLayer.getDetails().containsKey("influenceradius")) { continue; } if (arc && !l.getService().getProtocol().startsWith("arc")) { continue; } if (wfs && (l.getFeatureType() == null || !l.getFeatureType().getFeatureSource().getProtocol().equals("wfs"))) { continue; } if (attribute && appLayer.getAttributes().isEmpty()) { continue; } if(hasConfiguredLayers && !possibleLayers.contains(appLayer.getId())){ continue; } layers.add(appLayer); } //get all the layers of the level children. for (Level childLevel : level.getChildren()) { layers.addAll(getLayers(childLevel, filterable, bufferable, editable, influence, arc, wfs, attribute,hasConfiguredLayers,possibleLayers)); } return layers; } }
true
true
public static List<ApplicationLayer> getLayers(Level level,Boolean filterable, Boolean bufferable, Boolean editable ,Boolean influence ,Boolean arc ,Boolean wfs ,Boolean attribute, Boolean hasConfiguredLayers, List<Long> possibleLayers) { List<ApplicationLayer> layers = new ArrayList<ApplicationLayer>(); //get all the layers of this level for (ApplicationLayer appLayer : level.getLayers()) { Layer l = appLayer.getService().getLayer(appLayer.getLayerName()); if(filterable) { // The value of l.isFilterable() for WMS layers is not meaningful // at the moment... Always assume a WMS layer is filterable if // the layer has a feature type. There is a checkbox for an admin // to specify manually if a layer supports SLD filtering for GetMap if(l.getService() instanceof WMSService) { if(l.getFeatureType() == null) { continue; } } else { if(!l.isFilterable()) { continue; } } } if(bufferable && !l.isBufferable() ) { continue; } if(filterable && l.getService() instanceof ArcGISService){ if(l.getFeatureType() == null ){ continue; }else if(! (l.getFeatureType().getFeatureSource() instanceof ArcGISFeatureSource )){ continue; } } if (editable && (l.getFeatureType() == null || !l.getFeatureType().isWriteable())) { continue; } if (influence && !appLayer.getDetails().containsKey("influenceradius")) { continue; } if (arc && !l.getService().getProtocol().startsWith("arc")) { continue; } if (wfs && (l.getFeatureType() == null || !l.getFeatureType().getFeatureSource().getProtocol().equals("wfs"))) { continue; } if (attribute && appLayer.getAttributes().isEmpty()) { continue; } if(hasConfiguredLayers && !possibleLayers.contains(appLayer.getId())){ continue; } layers.add(appLayer); } //get all the layers of the level children. for (Level childLevel : level.getChildren()) { layers.addAll(getLayers(childLevel, filterable, bufferable, editable, influence, arc, wfs, attribute,hasConfiguredLayers,possibleLayers)); } return layers; }
public static List<ApplicationLayer> getLayers(Level level,Boolean filterable, Boolean bufferable, Boolean editable ,Boolean influence ,Boolean arc ,Boolean wfs ,Boolean attribute, Boolean hasConfiguredLayers, List<Long> possibleLayers) { List<ApplicationLayer> layers = new ArrayList<ApplicationLayer>(); //get all the layers of this level for (ApplicationLayer appLayer : level.getLayers()) { Layer l = appLayer.getService().getLayer(appLayer.getLayerName()); if(l == null){ continue; } if(filterable) { // The value of l.isFilterable() for WMS layers is not meaningful // at the moment... Always assume a WMS layer is filterable if // the layer has a feature type. There is a checkbox for an admin // to specify manually if a layer supports SLD filtering for GetMap if(l.getService() instanceof WMSService) { if(l.getFeatureType() == null) { continue; } } else { if(!l.isFilterable()) { continue; } } } if(bufferable && !l.isBufferable() ) { continue; } if(filterable && l.getService() instanceof ArcGISService){ if(l.getFeatureType() == null ){ continue; }else if(! (l.getFeatureType().getFeatureSource() instanceof ArcGISFeatureSource )){ continue; } } if (editable && (l.getFeatureType() == null || !l.getFeatureType().isWriteable())) { continue; } if (influence && !appLayer.getDetails().containsKey("influenceradius")) { continue; } if (arc && !l.getService().getProtocol().startsWith("arc")) { continue; } if (wfs && (l.getFeatureType() == null || !l.getFeatureType().getFeatureSource().getProtocol().equals("wfs"))) { continue; } if (attribute && appLayer.getAttributes().isEmpty()) { continue; } if(hasConfiguredLayers && !possibleLayers.contains(appLayer.getId())){ continue; } layers.add(appLayer); } //get all the layers of the level children. for (Level childLevel : level.getChildren()) { layers.addAll(getLayers(childLevel, filterable, bufferable, editable, influence, arc, wfs, attribute,hasConfiguredLayers,possibleLayers)); } return layers; }
diff --git a/topcat/src/main/uk/ac/starlink/topcat/plot2/BlobPanel2.java b/topcat/src/main/uk/ac/starlink/topcat/plot2/BlobPanel2.java index a4bcc28ec..49811c5fe 100644 --- a/topcat/src/main/uk/ac/starlink/topcat/plot2/BlobPanel2.java +++ b/topcat/src/main/uk/ac/starlink/topcat/plot2/BlobPanel2.java @@ -1,283 +1,286 @@ package uk.ac.starlink.topcat.plot2; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.event.MouseInputListener; import uk.ac.starlink.topcat.ResourceIcon; /** * Component which allows the user to draw a blob using the mouse. * You drag the mouse around to cover patches of the component; * you can create several separate or overlapping blobs by doing * several click-drag sequences. If you drag off the window the * currently-dragged region will be ditched. Clicking with the right * button removes the most recently-added blob. Resizing the window * clears any existing blobs (since it's not obvious how or if to * resize the blobs). Try it, it's easy. * * @author Mark Taylor (Starlink) * @since 8 Jul 2004 */ public abstract class BlobPanel2 extends JComponent { private final BlobListener blobListener_; private List blobs_; private GeneralPath dragPath_; private Action blobAction_; private Color fillColor_ = new Color( 0, 0, 0, 64 ); private Color pathColor_ = new Color( 0, 0, 0, 128 ); private boolean isActive_; /** * Constructor. */ public BlobPanel2() { blobListener_ = new BlobListener(); addComponentListener( new ComponentAdapter() { public void componentResized( ComponentEvent evt ) { clear(); } } ); setOpaque( false ); /* Constructs an associated action which can be used to start * and stop blob drawing. */ blobAction_ = new AbstractAction() { public void actionPerformed( ActionEvent evt ) { if ( isActive() ) { if ( ! blobs_.isEmpty() ) { blobCompleted( getBlob() ); } + else { + setActive( false ); + } } else { setActive( true ); } } }; /* Initialise the action and this component. */ clear(); setActive( false ); } /** * Returns the currently-defined blob. * * @return shape drawn */ public Shape getBlob() { Area area = new Area(); for ( Iterator it = blobs_.iterator(); it.hasNext(); ) { area.add( new Area( (Shape) it.next() ) ); } return simplify( area ); } /** * Sets the currently-defined blob. * * @param blob shape to be displayed and played around with by the user */ public void setBlob( Shape blob ) { blobs_ = new ArrayList(); blobs_.add( blob ); repaint(); } /** * Resets the current blob to an empty shape. */ public void clear() { blobs_ = new ArrayList(); repaint(); } /** * Returns the action which is used to start and stop blob drawing. * Invoking the action toggles the activity status of this panel, * and when invoked for deactivation (that is after a blob has been * drawn) then {@link #blobCompleted} is called. * * @return activation toggle action */ public Action getBlobAction() { return blobAction_; } /** * Sets whether this panel is active (visible, accepting mouse gestures, * drawing shapes) or inactive (invisible). * * @param active true to select activeness */ public void setActive( boolean active ) { if ( active != isActive_ ) { clear(); } isActive_ = active; blobAction_.putValue( Action.NAME, active ? "Finish Drawing Region" : "Draw Subset Region" ); blobAction_.putValue( Action.SMALL_ICON, active ? ResourceIcon.BLOB_SUBSET_END : ResourceIcon.BLOB_SUBSET ); blobAction_.putValue( Action.SHORT_DESCRIPTION, active ? "Define susbset from currently-drawn " + "region" : "Draw a region on the plot to define " + "a new row subset" ); setListening( active ); setVisible( active ); } /** * Changes whether this component is listening to mouse gestures to * modify the shape. This method is called by <code>setActive</code>, * but may be called independently of it as well. * * @param isListening whether mouse gestures can affect current shape */ public void setListening( boolean isListening ) { if ( isListening ) { addMouseListener( blobListener_ ); addMouseMotionListener( blobListener_ ); } else { removeMouseListener( blobListener_ ); removeMouseMotionListener( blobListener_ ); } } /** * Indicates whether this blob is currently active. * * @return true iff this blob is active (visible and drawing) */ public boolean isActive() { return isActive_; } /** * Invoked when this component's action is invoked to terminate a * blob drawing session. Implementations of this method are expected * to clear up by calling <code>setActive(false)</code> when the * blob representation is no longer required. * * @param blob completed shape */ protected abstract void blobCompleted( Shape blob ); /** * Sets the colours which will be used for drawing the blob. * * @param fillColor colour which fills the blob area * @param pathColor colour which delineates the blob region */ public void setColors( Color fillColor, Color pathColor ) { fillColor_ = fillColor; pathColor_ = pathColor; } @Override protected void paintComponent( Graphics g ) { Color oldColor = g.getColor(); Graphics2D g2 = (Graphics2D) g; Area area = new Area(); for ( Iterator it = blobs_.iterator(); it.hasNext(); ) { area.add( new Area( (Shape) it.next() ) ); } if ( dragPath_ != null ) { area.add( new Area( dragPath_ ) ); g2.setColor( pathColor_ ); g2.draw( dragPath_ ); } g2.setColor( fillColor_ ); g2.fill( area ); g.setColor( oldColor ); } /** * Returns a simplified version of a given shape. * This may be important since the one drawn by the user could end up * having a lot of path components. */ private static Shape simplify( Shape shape ) { // Current implementation is a no-op. If we need to be cleverer, // probably want to look at java.awt.geom.FlatteningPathIterator? return shape; } /** * Mouse listener that uses mouse gestures to draw a blob. */ private class BlobListener implements MouseListener, MouseMotionListener { public void mouseEntered( MouseEvent evt ) { } public void mouseExited( MouseEvent evt ) { if ( dragPath_ != null ) { dragPath_ = null; repaint(); } } public void mouseClicked( MouseEvent evt ) { if ( evt.getButton() == MouseEvent.BUTTON3 ) { int nblob = blobs_.size(); if ( nblob > 0 ) { blobs_.remove( nblob - 1 ); } repaint(); } } public void mousePressed( MouseEvent evt ) { if ( evt.getButton() == MouseEvent.BUTTON1 ) { Point p = evt.getPoint(); dragPath_ = new GeneralPath(); dragPath_.moveTo( p.x, p.y ); } } public void mouseReleased( MouseEvent evt ) { if ( evt.getButton() == MouseEvent.BUTTON1 ) { if ( dragPath_ != null ) { blobs_.add( simplify( dragPath_ ) ); dragPath_ = null; repaint(); } } } public void mouseDragged( MouseEvent evt ) { if ( dragPath_ != null ) { Point p = evt.getPoint(); dragPath_.lineTo( p.x, p.y ); repaint(); } } public void mouseMoved( MouseEvent evt ) { } } }
true
true
public BlobPanel2() { blobListener_ = new BlobListener(); addComponentListener( new ComponentAdapter() { public void componentResized( ComponentEvent evt ) { clear(); } } ); setOpaque( false ); /* Constructs an associated action which can be used to start * and stop blob drawing. */ blobAction_ = new AbstractAction() { public void actionPerformed( ActionEvent evt ) { if ( isActive() ) { if ( ! blobs_.isEmpty() ) { blobCompleted( getBlob() ); } } else { setActive( true ); } } }; /* Initialise the action and this component. */ clear(); setActive( false ); }
public BlobPanel2() { blobListener_ = new BlobListener(); addComponentListener( new ComponentAdapter() { public void componentResized( ComponentEvent evt ) { clear(); } } ); setOpaque( false ); /* Constructs an associated action which can be used to start * and stop blob drawing. */ blobAction_ = new AbstractAction() { public void actionPerformed( ActionEvent evt ) { if ( isActive() ) { if ( ! blobs_.isEmpty() ) { blobCompleted( getBlob() ); } else { setActive( false ); } } else { setActive( true ); } } }; /* Initialise the action and this component. */ clear(); setActive( false ); }
diff --git a/src/logging/Logger.java b/src/logging/Logger.java index e9cc91f..b312d49 100644 --- a/src/logging/Logger.java +++ b/src/logging/Logger.java @@ -1,38 +1,38 @@ package logging; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; public class Logger { private static final String LOCATION = "Log"; private ArrayList<Message> messages= new ArrayList<Message>(); public void log(Message message){ System.out.println(message.getMessage()); messages.add(message); } public void writeMessages(){ try{ BufferedWriter bw = new BufferedWriter(new FileWriter(getLatestFileName(0))); for(Message m : messages) - bw.write(m.getMessage()+"\n"); + bw.write(m.getMessage()+"\r\n"); bw.flush(); bw.close(); } catch(Exception ex){ ex.printStackTrace(); log(new Message("Failed to write log", Message.Type.Error, ex)); } } private String getLatestFileName(int i){ File f = new File(Logger.LOCATION+i+".txt"); if(!f.exists()) return LOCATION+i+".txt"; return getLatestFileName(i+1); } }
true
true
public void writeMessages(){ try{ BufferedWriter bw = new BufferedWriter(new FileWriter(getLatestFileName(0))); for(Message m : messages) bw.write(m.getMessage()+"\n"); bw.flush(); bw.close(); } catch(Exception ex){ ex.printStackTrace(); log(new Message("Failed to write log", Message.Type.Error, ex)); } }
public void writeMessages(){ try{ BufferedWriter bw = new BufferedWriter(new FileWriter(getLatestFileName(0))); for(Message m : messages) bw.write(m.getMessage()+"\r\n"); bw.flush(); bw.close(); } catch(Exception ex){ ex.printStackTrace(); log(new Message("Failed to write log", Message.Type.Error, ex)); } }
diff --git a/src/fr/frozentux/craftguard2/config/ListLoader.java b/src/fr/frozentux/craftguard2/config/ListLoader.java index d0c097b..7260b43 100644 --- a/src/fr/frozentux/craftguard2/config/ListLoader.java +++ b/src/fr/frozentux/craftguard2/config/ListLoader.java @@ -1,134 +1,135 @@ package fr.frozentux.craftguard2.config; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import fr.frozentux.craftguard2.CraftGuardPlugin; import fr.frozentux.craftguard2.list.Id; import fr.frozentux.craftguard2.list.List; import fr.frozentux.craftguard2.list.ListManager; /** * Loads, writes and stores groups lists for CraftGuard * @author FrozenTux * */ public class ListLoader { private CraftGuardPlugin plugin; private File configurationFile; private FileConfiguration configuration; /** * Loads, writes and stores groups lists for CraftGuard * @author FrozenTux * */ public ListLoader(CraftGuardPlugin plugin, FileConfiguration fileConfiguration, File file){ this.plugin = plugin; this.configurationFile = file; this.configuration = fileConfiguration; } /** * Loads the list from the {@link FileConfiguration} specified in the constructor * @return A HashMap of the loaded groups */ public HashMap<String, List> load(){ //Initializing the groups list or clearing it HashMap<String, List> groupsLists = new HashMap<String, List>(); //If the file doesn't exist, write defaults if(!configurationFile.exists()){ plugin.getCraftGuardLogger().debug("ListFile not existing"); HashMap<Integer, Id> exampleMap = new HashMap<Integer, Id>(); exampleMap.put(5, new Id(5));//PLANKS exampleMap.put(35, new Id(35)); exampleMap.get(35).addMetadata(2);//Only purple WOOL List exampleList = new List("example", "samplepermission", exampleMap, null, plugin.getListManager()); configuration.addDefault(exampleList.getName() + ".list", exampleList.toStringList(false)); configuration.addDefault(exampleList.getName() + ".permission", exampleList.getPermission()); configuration.options().header("CraftGuard 2.X by FrozenTux").copyHeader(true).copyDefaults(true); try { configuration.save(configurationFile); } catch (IOException e) { e.printStackTrace(); } } //Load the file try { + configuration = new YamlConfiguration(); configuration.load(configurationFile); } catch (Exception e) { e.printStackTrace(); } Set<String> keys = configuration.getKeys(false); Iterator<String> it = keys.iterator(); while(it.hasNext()){ //This loop will be run for each list String name = it.next(); String permission = configuration.getString(name + ".permission"); String parentName = configuration.getString(name + ".parent"); groupsLists.put(name, new List(name, permission, configuration.getStringList(name + ".list"), parentName, plugin.getListManager())); } plugin.getCraftGuardLogger().info("Succesfully loaded " + groupsLists.size() + " lists"); return groupsLists; } public void writeAllLists(ListManager manager){ plugin.getCraftGuardLogger().info("Saving " + manager.getListsNames().size() + " lists..."); configurationFile.delete(); try{ configurationFile.createNewFile(); configuration = new YamlConfiguration(); System.out.println(configuration.contains("empty")); }catch (Exception e){ e.printStackTrace(); } configuration.options().header("CraftGuard 2.X by FrozenTux").copyHeader(true); Iterator<String> it = manager.getListsNames().iterator(); while(it.hasNext()){ writeList(manager.getList(it.next()), false); } try { configuration.save(configurationFile); } catch (IOException e) { e.printStackTrace(); } } public void writeList(List list, boolean save){ configuration.set(list.getName() + ".list", list.toStringList(false)); if(!list.getPermission().equals(list.getName()))configuration.set(list.getName() + ".permission", list.getPermission()); if(!(list.getParent() == null))configuration.set(list.getName() + ".parent", list.getParent().getName()); if(save){ try { configuration.save(configurationFile); } catch (IOException e) { e.printStackTrace(); } } } }
true
true
public HashMap<String, List> load(){ //Initializing the groups list or clearing it HashMap<String, List> groupsLists = new HashMap<String, List>(); //If the file doesn't exist, write defaults if(!configurationFile.exists()){ plugin.getCraftGuardLogger().debug("ListFile not existing"); HashMap<Integer, Id> exampleMap = new HashMap<Integer, Id>(); exampleMap.put(5, new Id(5));//PLANKS exampleMap.put(35, new Id(35)); exampleMap.get(35).addMetadata(2);//Only purple WOOL List exampleList = new List("example", "samplepermission", exampleMap, null, plugin.getListManager()); configuration.addDefault(exampleList.getName() + ".list", exampleList.toStringList(false)); configuration.addDefault(exampleList.getName() + ".permission", exampleList.getPermission()); configuration.options().header("CraftGuard 2.X by FrozenTux").copyHeader(true).copyDefaults(true); try { configuration.save(configurationFile); } catch (IOException e) { e.printStackTrace(); } } //Load the file try { configuration.load(configurationFile); } catch (Exception e) { e.printStackTrace(); } Set<String> keys = configuration.getKeys(false); Iterator<String> it = keys.iterator(); while(it.hasNext()){ //This loop will be run for each list String name = it.next(); String permission = configuration.getString(name + ".permission"); String parentName = configuration.getString(name + ".parent"); groupsLists.put(name, new List(name, permission, configuration.getStringList(name + ".list"), parentName, plugin.getListManager())); } plugin.getCraftGuardLogger().info("Succesfully loaded " + groupsLists.size() + " lists"); return groupsLists; }
public HashMap<String, List> load(){ //Initializing the groups list or clearing it HashMap<String, List> groupsLists = new HashMap<String, List>(); //If the file doesn't exist, write defaults if(!configurationFile.exists()){ plugin.getCraftGuardLogger().debug("ListFile not existing"); HashMap<Integer, Id> exampleMap = new HashMap<Integer, Id>(); exampleMap.put(5, new Id(5));//PLANKS exampleMap.put(35, new Id(35)); exampleMap.get(35).addMetadata(2);//Only purple WOOL List exampleList = new List("example", "samplepermission", exampleMap, null, plugin.getListManager()); configuration.addDefault(exampleList.getName() + ".list", exampleList.toStringList(false)); configuration.addDefault(exampleList.getName() + ".permission", exampleList.getPermission()); configuration.options().header("CraftGuard 2.X by FrozenTux").copyHeader(true).copyDefaults(true); try { configuration.save(configurationFile); } catch (IOException e) { e.printStackTrace(); } } //Load the file try { configuration = new YamlConfiguration(); configuration.load(configurationFile); } catch (Exception e) { e.printStackTrace(); } Set<String> keys = configuration.getKeys(false); Iterator<String> it = keys.iterator(); while(it.hasNext()){ //This loop will be run for each list String name = it.next(); String permission = configuration.getString(name + ".permission"); String parentName = configuration.getString(name + ".parent"); groupsLists.put(name, new List(name, permission, configuration.getStringList(name + ".list"), parentName, plugin.getListManager())); } plugin.getCraftGuardLogger().info("Succesfully loaded " + groupsLists.size() + " lists"); return groupsLists; }
diff --git a/nakp/src/main/de/nordakademie/nakp/persistence/MongoProductDAO.java b/nakp/src/main/de/nordakademie/nakp/persistence/MongoProductDAO.java index 8a74fc6..3063c3b 100644 --- a/nakp/src/main/de/nordakademie/nakp/persistence/MongoProductDAO.java +++ b/nakp/src/main/de/nordakademie/nakp/persistence/MongoProductDAO.java @@ -1,33 +1,33 @@ package main.de.nordakademie.nakp.persistence; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.mongodb.DBCursor; import com.mongodb.DBObject; import main.de.nordakademie.nakp.business.Product; import main.de.nordakademie.nakp.business.ProductDAO; @Repository public class MongoProductDAO implements ProductDAO { @Autowired private MongodbFactory mongodb; @Override public List<Product> findAll() { final List<Product> products = new ArrayList<>(); final DBCursor cursor = mongodb.getObject().getCollection("product") .find(); while (cursor.hasNext()) { final DBObject document = cursor.next(); - products.add(new Product((String) document.get("id"))); + products.add(new Product((String) document.get("_id"))); } return products; } }
true
true
public List<Product> findAll() { final List<Product> products = new ArrayList<>(); final DBCursor cursor = mongodb.getObject().getCollection("product") .find(); while (cursor.hasNext()) { final DBObject document = cursor.next(); products.add(new Product((String) document.get("id"))); } return products; }
public List<Product> findAll() { final List<Product> products = new ArrayList<>(); final DBCursor cursor = mongodb.getObject().getCollection("product") .find(); while (cursor.hasNext()) { final DBObject document = cursor.next(); products.add(new Product((String) document.get("_id"))); } return products; }
diff --git a/src/java/org/apache/hadoop/security/UnixUserGroupInformation.java b/src/java/org/apache/hadoop/security/UnixUserGroupInformation.java index 62cbb65986..dcb13b90ef 100644 --- a/src/java/org/apache/hadoop/security/UnixUserGroupInformation.java +++ b/src/java/org/apache/hadoop/security/UnixUserGroupInformation.java @@ -1,432 +1,434 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.security; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; import java.util.TreeSet; import javax.security.auth.login.LoginException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Shell; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableUtils; /** An implementation of UserGroupInformation in the Unix system */ public class UnixUserGroupInformation extends UserGroupInformation { public static final String DEFAULT_USERNAME = "DrWho"; public static final String DEFAULT_GROUP = "Tardis"; final static public String UGI_PROPERTY_NAME = "hadoop.job.ugi"; final static private HashMap<String, UnixUserGroupInformation> user2UGIMap = new HashMap<String, UnixUserGroupInformation>(); /** Create an immutable {@link UnixUserGroupInformation} object. */ public static UnixUserGroupInformation createImmutable(String[] ugi) { return new UnixUserGroupInformation(ugi) { public void readFields(DataInput in) throws IOException { throw new UnsupportedOperationException(); } }; } private String userName; private String[] groupNames; /** Default constructor */ public UnixUserGroupInformation() { } /** Constructor with parameters user name and its group names. * The first entry in the groups list is the default group. * * @param userName a user's name * @param groupNames groups list, first of which is the default group * @exception IllegalArgumentException if any argument is null */ public UnixUserGroupInformation(String userName, String[] groupNames) { setUserGroupNames(userName, groupNames); } /** Constructor with parameter user/group names * * @param ugi an array containing user/group names, the first * element of which is the user name, the second of * which is the default group name. * @exception IllegalArgumentException if the array size is less than 2 * or any element is null. */ public UnixUserGroupInformation(String[] ugi) { if (ugi==null || ugi.length < 2) { throw new IllegalArgumentException( "Parameter does contain at least "+ "one user name and one group name"); } String[] groupNames = new String[ugi.length-1]; System.arraycopy(ugi, 1, groupNames, 0, groupNames.length); setUserGroupNames(ugi[0], groupNames); } /* Set this object's user name and group names * * @param userName a user's name * @param groupNames groups list, the first of which is the default group * @exception IllegalArgumentException if any argument is null */ private void setUserGroupNames(String userName, String[] groupNames) { if (userName==null || userName.length()==0 || groupNames== null || groupNames.length==0) { throw new IllegalArgumentException( "Parameters should not be null or an empty string/array"); } for (int i=0; i<groupNames.length; i++) { if(groupNames[i] == null || groupNames[i].length() == 0) { throw new IllegalArgumentException("A null group name at index " + i); } } this.userName = userName; this.groupNames = groupNames; } /** Return an array of group names */ public String[] getGroupNames() { return groupNames; } /** Return the user's name */ public String getUserName() { return userName; } /* The following two methods implements Writable interface */ final private static String UGI_TECHNOLOGY = "STRING_UGI"; /** Deserialize this object * First check if this is a UGI in the string format. * If no, throw an IOException; otherwise * set this object's fields by reading them from the given data input * * @param in input stream * @exception IOException is thrown if encounter any error when reading */ public void readFields(DataInput in) throws IOException { // read UGI type first String ugiType = Text.readString(in); if (!UGI_TECHNOLOGY.equals(ugiType)) { throw new IOException("Expect UGI prefix: " + UGI_TECHNOLOGY + ", but receive a prefix: " + ugiType); } // read this object userName = Text.readString(in); int numOfGroups = WritableUtils.readVInt(in); groupNames = new String[numOfGroups]; for (int i = 0; i < numOfGroups; i++) { groupNames[i] = Text.readString(in); } } /** Serialize this object * First write a string marking that this is a UGI in the string format, * then write this object's serialized form to the given data output * * @param out output stream * @exception IOException if encounter any error during writing */ public void write(DataOutput out) throws IOException { // write a prefix indicating the type of UGI being written Text.writeString(out, UGI_TECHNOLOGY); // write this object Text.writeString(out, userName); WritableUtils.writeVInt(out, groupNames.length); for (String groupName : groupNames) { Text.writeString(out, groupName); } } /* The following two methods deal with transferring UGI through conf. * In this pass of implementation we store UGI as a string in conf. * Later we may change it to be a more general approach that stores * it as a byte array */ /** Store the given <code>ugi</code> as a comma separated string in * <code>conf</code> as a property <code>attr</code> * * The String starts with the user name followed by the default group names, * and other group names. * * @param conf configuration * @param attr property name * @param ugi a UnixUserGroupInformation */ public static void saveToConf(Configuration conf, String attr, UnixUserGroupInformation ugi ) { conf.set(attr, ugi.toString()); } /** Read a UGI from the given <code>conf</code> * * The object is expected to store with the property name <code>attr</code> * as a comma separated string that starts * with the user name followed by group names. * If the property name is not defined, return null. * It's assumed that there is only one UGI per user. If this user already * has a UGI in the ugi map, return the ugi in the map. * Otherwise, construct a UGI from the configuration, store it in the * ugi map and return it. * * @param conf configuration * @param attr property name * @return a UnixUGI * @throws LoginException if the stored string is ill-formatted. */ public static UnixUserGroupInformation readFromConf( Configuration conf, String attr) throws LoginException { String[] ugi = conf.getStrings(attr); if(ugi == null) { return null; } UnixUserGroupInformation currentUGI = null; if (ugi.length>0 ){ currentUGI = user2UGIMap.get(ugi[0]); } if (currentUGI == null) { try { currentUGI = new UnixUserGroupInformation(ugi); user2UGIMap.put(currentUGI.getUserName(), currentUGI); } catch (IllegalArgumentException e) { throw new LoginException("Login failed: "+e.getMessage()); } } return currentUGI; } /** * Get current user's name and the names of all its groups from Unix. * It's assumed that there is only one UGI per user. If this user already * has a UGI in the ugi map, return the ugi in the map. * Otherwise get the current user's information from Unix, store it * in the map, and return it. * * If the current user's UNIX username or groups are configured in such a way * to throw an Exception, for example if the user uses LDAP, then this method * will use a the {@link #DEFAULT_USERNAME} and {@link #DEFAULT_GROUP} * constants. */ public static UnixUserGroupInformation login() throws LoginException { try { String userName; // if an exception occurs, then uses the // default user try { userName = getUnixUserName(); } catch (Exception e) { + LOG.warn("Couldn't get unix username, using " + DEFAULT_USERNAME, e); userName = DEFAULT_USERNAME; } // check if this user already has a UGI object in the ugi map UnixUserGroupInformation ugi = user2UGIMap.get(userName); if (ugi != null) { return ugi; } /* get groups list from UNIX. * It's assumed that the first group is the default group. */ String[] groupNames; // if an exception occurs, then uses the // default group try { groupNames = getUnixGroups(); } catch (Exception e) { + LOG.warn("Couldn't get unix groups, using " + DEFAULT_GROUP, e); groupNames = new String[1]; groupNames[0] = DEFAULT_GROUP; } // construct a Unix UGI ugi = new UnixUserGroupInformation(userName, groupNames); user2UGIMap.put(ugi.getUserName(), ugi); return ugi; } catch (Exception e) { throw new LoginException("Login failed: "+e.getMessage()); } } /** Equivalent to login(conf, false). */ public static UnixUserGroupInformation login(Configuration conf) throws LoginException { return login(conf, false); } /** Get a user's name & its group names from the given configuration; * If it is not defined in the configuration, get the current user's * information from Unix. * If the user has a UGI in the ugi map, return the one in * the UGI map. * * @param conf either a job configuration or client's configuration * @param save saving it to conf? * @return UnixUserGroupInformation a user/group information * @exception LoginException if not able to get the user/group information */ public static UnixUserGroupInformation login(Configuration conf, boolean save ) throws LoginException { UnixUserGroupInformation ugi = readFromConf(conf, UGI_PROPERTY_NAME); if (ugi == null) { ugi = login(); LOG.debug("Unix Login: " + ugi); if (save) { saveToConf(conf, UGI_PROPERTY_NAME, ugi); } } return ugi; } /* Return a string representation of a string array. * Two strings are separated by a blank. */ private static String toString(String[] strArray) { if (strArray==null || strArray.length==0) { return ""; } StringBuilder buf = new StringBuilder(strArray[0]); for (int i=1; i<strArray.length; i++) { buf.append(' '); buf.append(strArray[i]); } return buf.toString(); } /** Get current user's name from Unix by running the command whoami. * * @return current user's name * @throws IOException if encounter any error while running the command */ static String getUnixUserName() throws IOException { String[] result = executeShellCommand( new String[]{Shell.USER_NAME_COMMAND}); if (result.length!=1) { throw new IOException("Expect one token as the result of " + Shell.USER_NAME_COMMAND + ": " + toString(result)); } return result[0]; } /** Get the current user's group list from Unix by running the command groups * * @return the groups list that the current user belongs to * @throws IOException if encounter any error when running the command */ private static String[] getUnixGroups() throws IOException { return executeShellCommand(Shell.getGROUPS_COMMAND()); } /* Execute a command and return the result as an array of Strings */ private static String[] executeShellCommand(String[] command) throws IOException { String groups = Shell.execCommand(command); StringTokenizer tokenizer = new StringTokenizer(groups); int numOfTokens = tokenizer.countTokens(); String[] tokens = new String[numOfTokens]; for (int i=0; tokenizer.hasMoreTokens(); i++) { tokens[i] = tokenizer.nextToken(); } return tokens; } /** Decide if two UGIs are the same * * @param other other object * @return true if they are the same; false otherwise. */ public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof UnixUserGroupInformation)) { return false; } UnixUserGroupInformation otherUGI = (UnixUserGroupInformation)other; // check userName if (userName == null) { if (otherUGI.getUserName() != null) { return false; } } else { if (!userName.equals(otherUGI.getUserName())) { return false; } } // checkGroupNames if (groupNames == otherUGI.groupNames) { return true; } if (groupNames.length != otherUGI.groupNames.length) { return false; } // check default group name if (groupNames.length>0 && !groupNames[0].equals(otherUGI.groupNames[0])) { return false; } // check all group names, ignoring the order return new TreeSet<String>(Arrays.asList(groupNames)).equals( new TreeSet<String>(Arrays.asList(otherUGI.groupNames))); } /** Returns a hash code for this UGI. * The hash code for a UGI is the hash code of its user name string. * * @return a hash code value for this UGI. */ public int hashCode() { return getUserName().hashCode(); } /** Convert this object to a string * * @return a comma separated string containing the user name and group names */ public String toString() { StringBuilder buf = new StringBuilder(); buf.append(userName); for (String groupName : groupNames) { buf.append(','); buf.append(groupName); } return buf.toString(); } @Override public String getName() { return toString(); } }
false
true
public static UnixUserGroupInformation login() throws LoginException { try { String userName; // if an exception occurs, then uses the // default user try { userName = getUnixUserName(); } catch (Exception e) { userName = DEFAULT_USERNAME; } // check if this user already has a UGI object in the ugi map UnixUserGroupInformation ugi = user2UGIMap.get(userName); if (ugi != null) { return ugi; } /* get groups list from UNIX. * It's assumed that the first group is the default group. */ String[] groupNames; // if an exception occurs, then uses the // default group try { groupNames = getUnixGroups(); } catch (Exception e) { groupNames = new String[1]; groupNames[0] = DEFAULT_GROUP; } // construct a Unix UGI ugi = new UnixUserGroupInformation(userName, groupNames); user2UGIMap.put(ugi.getUserName(), ugi); return ugi; } catch (Exception e) { throw new LoginException("Login failed: "+e.getMessage()); } }
public static UnixUserGroupInformation login() throws LoginException { try { String userName; // if an exception occurs, then uses the // default user try { userName = getUnixUserName(); } catch (Exception e) { LOG.warn("Couldn't get unix username, using " + DEFAULT_USERNAME, e); userName = DEFAULT_USERNAME; } // check if this user already has a UGI object in the ugi map UnixUserGroupInformation ugi = user2UGIMap.get(userName); if (ugi != null) { return ugi; } /* get groups list from UNIX. * It's assumed that the first group is the default group. */ String[] groupNames; // if an exception occurs, then uses the // default group try { groupNames = getUnixGroups(); } catch (Exception e) { LOG.warn("Couldn't get unix groups, using " + DEFAULT_GROUP, e); groupNames = new String[1]; groupNames[0] = DEFAULT_GROUP; } // construct a Unix UGI ugi = new UnixUserGroupInformation(userName, groupNames); user2UGIMap.put(ugi.getUserName(), ugi); return ugi; } catch (Exception e) { throw new LoginException("Login failed: "+e.getMessage()); } }
diff --git a/vlc-android/src/org/videolan/vlc/Util.java b/vlc-android/src/org/videolan/vlc/Util.java index 429d39bc..465d178d 100644 --- a/vlc-android/src/org/videolan/vlc/Util.java +++ b/vlc-android/src/org/videolan/vlc/Util.java @@ -1,354 +1,354 @@ /***************************************************************************** * Util.java ***************************************************************************** * Copyright © 2011-2012 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ package org.videolan.vlc; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.HashSet; import java.util.Locale; import java.util.Properties; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Toast; public class Util { public final static String TAG = "VLC/Util"; public final static boolean hasNavBar; /** A set of utility functions for the VLC application */ static { HashSet<String> devicesWithoutNavBar = new HashSet<String>(); devicesWithoutNavBar.add("HTC One V"); devicesWithoutNavBar.add("HTC One S"); devicesWithoutNavBar.add("HTC One X"); devicesWithoutNavBar.add("HTC One XL"); hasNavBar = isICSOrLater() && !devicesWithoutNavBar.contains(android.os.Build.MODEL); } /** Print an on-screen message to alert the user */ public static void toaster(Context context, int stringId, int duration) { Toast.makeText(context, stringId, duration).show(); } public static void toaster(Context context, int stringId) { toaster(context, stringId, Toast.LENGTH_SHORT); } public static File URItoFile(String URI) { return new File(Uri.decode(URI).replace("file://","")); } public static String URItoFileName(String URI) { int sep = URI.lastIndexOf('/'); int dot = URI.lastIndexOf('.'); String name = dot >= 0 ? URI.substring(sep + 1, dot) : URI; return Uri.decode(name); } public static String PathToURI(String path) { String URI; try { URI = LibVLC.getInstance().nativeToURI(path); } catch (LibVlcException e) { URI = ""; } return URI; } public static String stripTrailingSlash(String _s) { String s = _s; if( s.endsWith("/") && s.length() > 1 ) s = s.substring(0,s.length()-1); return s; } public static String readAsset(String assetName, String defaultS) { try { InputStream is = VLCApplication.getAppResources().getAssets().open(assetName); BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF8")); StringBuilder sb = new StringBuilder(); String line = r.readLine(); if(line != null) { sb.append(line); line = r.readLine(); while(line != null) { sb.append('\n'); sb.append(line); line = r.readLine(); } } return sb.toString(); } catch (IOException e) { return defaultS; } } /** * Convert time to a string * @param millis e.g.time/length from file * @return formated string (hh:)mm:ss */ public static String millisToString(long millis) { boolean negative = millis < 0; millis = java.lang.Math.abs(millis); millis /= 1000; int sec = (int) (millis % 60); millis /= 60; int min = (int) (millis % 60); millis /= 60; int hours = (int) millis; String time; DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(Locale.US); format.applyPattern("00"); if (millis > 0) { time = (negative ? "-" : "") + hours + ":" + format.format(min) + ":" + format.format(sec); } else { time = (negative ? "-" : "") + min + ":" + format.format(sec); } return time; } public static Bitmap scaleDownBitmap(Context context, Bitmap bitmap, int width) { if (bitmap != null) { final float densityMultiplier = context.getResources().getDisplayMetrics().density; int w = (int) (width * densityMultiplier); int h = (int) (w * bitmap.getHeight() / ((double) bitmap.getWidth())); bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); } return bitmap; } public static Bitmap cropBorders(Bitmap bitmap, int width, int height) { int top = 0; for (int i = 0; i < height / 2; i++) { int pixel1 = bitmap.getPixel(width / 2, i); int pixel2 = bitmap.getPixel(width / 2, height - i - 1); if ((pixel1 == 0 || pixel1 == -16777216) && (pixel2 == 0 || pixel2 == -16777216)) { top = i; } else { break; } } int left = 0; for (int i = 0; i < width / 2; i++) { int pixel1 = bitmap.getPixel(i, height / 2); int pixel2 = bitmap.getPixel(width - i - 1, height / 2); if ((pixel1 == 0 || pixel1 == -16777216) && (pixel2 == 0 || pixel2 == -16777216)) { left = i; } else { break; } } if (left >= width / 2 - 10 || top >= height / 2 - 10) return bitmap; // Cut off the transparency on the borders return Bitmap.createBitmap(bitmap, left, top, (width - (2 * left)), (height - (2 * top))); } public static String getValue(String string, int defaultId) { return (string != null && string.length() > 0) ? string : VLCApplication.getAppContext().getString(defaultId); } public static void setItemBackground(View v, int position) { v.setBackgroundResource(position % 2 == 0 ? R.drawable.background_item1 : R.drawable.background_item2); } public static int convertPxToDp(int px) { WindowManager wm = (WindowManager)VLCApplication.getAppContext(). getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics metrics = new DisplayMetrics(); display.getMetrics(metrics); float logicalDensity = metrics.density; int dp = Math.round(px / logicalDensity); return dp; } public static int convertDpToPx(int dp) { return Math.round( TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, VLCApplication.getAppResources().getDisplayMetrics()) ); } public static boolean isGingerbreadOrLater() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD; } public static boolean isHoneycombOrLater() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB; } public static boolean isICSOrLater() { return android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; } public static boolean hasNavBar() { return hasNavBar; } private static String errorMsg = null; private static boolean isCompatible = false; public static String getErrorMsg() { return errorMsg; } public static boolean hasCompatibleCPU() { // If already checked return cached result if(errorMsg != null) return isCompatible; Properties properties = new Properties(); try { properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8"))); } catch (IOException e) { // Shouldn't happen if done correctly e.printStackTrace(); errorMsg = "IOException whilst reading compile flags"; isCompatible = false; return false; } String ANDROID_ABI = properties.getProperty("ANDROID_ABI"); boolean NO_NEON = properties.getProperty("NO_NEON","0").equals("1"); boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1"); boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1"); boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false; boolean hasX86 = false; - if(android.os.Build.CPU_ABI.equals("armeabi-v7a") || + if(android.os.Build.CPU_ABI.equals("x86")) { + hasX86 = true; + } else if(android.os.Build.CPU_ABI.equals("armeabi-v7a") || android.os.Build.CPU_ABI2.equals("armeabi-v7a")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } else if(android.os.Build.CPU_ABI.equals("armeabi") || android.os.Build.CPU_ABI2.equals("armeabi")) { hasArmV6 = true; - } else if(android.os.Build.CPU_ABI.equals("x86")) { - hasX86 = true; } try { FileReader fileReader = new FileReader("/proc/cpuinfo"); BufferedReader br = new BufferedReader(fileReader); String line; while((line = br.readLine()) != null) { if(!hasArmV7 && line.contains("ARMv7")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6")) hasArmV6 = true; // "clflush size" is a x86-specific cpuinfo tag. // (see kernel sources arch/x86/kernel/cpu/proc.c) if(line.contains("clflush size")) hasX86 = true; // TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c if(!hasNeon && line.contains("neon")) hasNeon = true; if(!hasFpu && line.contains("vfp")) hasFpu = true; } fileReader.close(); } catch(IOException ex){ ex.printStackTrace(); errorMsg = "IOException whilst reading cpuinfo flags"; isCompatible = false; return false; } // Enforce proper architecture to prevent problems if(ANDROID_ABI.equals("x86") && !hasX86) { errorMsg = "x86 build on non-x86 device"; isCompatible = false; return false; } else if(hasX86 && ANDROID_ABI.contains("armeabi")) { errorMsg = "ARM build on x86 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) { errorMsg = "ARMv7 build on non-ARMv7 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi")) { if(!NO_ARMV6 && !hasArmV6) { errorMsg = "ARMv6 build on non-ARMv6 device"; isCompatible = false; return false; } else if(!NO_FPU && !hasFpu) { errorMsg = "FPU-enabled build on non-FPU device"; isCompatible = false; return false; } } if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) { if(!NO_NEON && !hasNeon) { errorMsg = "NEON build on non-NEON device"; isCompatible = false; return false; } } errorMsg = null; isCompatible = true; return true; } public static boolean isPhone(){ TelephonyManager manager = (TelephonyManager)VLCApplication.getAppContext().getSystemService(Context.TELEPHONY_SERVICE); if(manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE){ return false; }else{ return true; } } }
false
true
public static boolean hasCompatibleCPU() { // If already checked return cached result if(errorMsg != null) return isCompatible; Properties properties = new Properties(); try { properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8"))); } catch (IOException e) { // Shouldn't happen if done correctly e.printStackTrace(); errorMsg = "IOException whilst reading compile flags"; isCompatible = false; return false; } String ANDROID_ABI = properties.getProperty("ANDROID_ABI"); boolean NO_NEON = properties.getProperty("NO_NEON","0").equals("1"); boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1"); boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1"); boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false; boolean hasX86 = false; if(android.os.Build.CPU_ABI.equals("armeabi-v7a") || android.os.Build.CPU_ABI2.equals("armeabi-v7a")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } else if(android.os.Build.CPU_ABI.equals("armeabi") || android.os.Build.CPU_ABI2.equals("armeabi")) { hasArmV6 = true; } else if(android.os.Build.CPU_ABI.equals("x86")) { hasX86 = true; } try { FileReader fileReader = new FileReader("/proc/cpuinfo"); BufferedReader br = new BufferedReader(fileReader); String line; while((line = br.readLine()) != null) { if(!hasArmV7 && line.contains("ARMv7")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6")) hasArmV6 = true; // "clflush size" is a x86-specific cpuinfo tag. // (see kernel sources arch/x86/kernel/cpu/proc.c) if(line.contains("clflush size")) hasX86 = true; // TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c if(!hasNeon && line.contains("neon")) hasNeon = true; if(!hasFpu && line.contains("vfp")) hasFpu = true; } fileReader.close(); } catch(IOException ex){ ex.printStackTrace(); errorMsg = "IOException whilst reading cpuinfo flags"; isCompatible = false; return false; } // Enforce proper architecture to prevent problems if(ANDROID_ABI.equals("x86") && !hasX86) { errorMsg = "x86 build on non-x86 device"; isCompatible = false; return false; } else if(hasX86 && ANDROID_ABI.contains("armeabi")) { errorMsg = "ARM build on x86 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) { errorMsg = "ARMv7 build on non-ARMv7 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi")) { if(!NO_ARMV6 && !hasArmV6) { errorMsg = "ARMv6 build on non-ARMv6 device"; isCompatible = false; return false; } else if(!NO_FPU && !hasFpu) { errorMsg = "FPU-enabled build on non-FPU device"; isCompatible = false; return false; } } if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) { if(!NO_NEON && !hasNeon) { errorMsg = "NEON build on non-NEON device"; isCompatible = false; return false; } } errorMsg = null; isCompatible = true; return true; }
public static boolean hasCompatibleCPU() { // If already checked return cached result if(errorMsg != null) return isCompatible; Properties properties = new Properties(); try { properties.load(new ByteArrayInputStream(Util.readAsset("env.txt", "").getBytes("UTF-8"))); } catch (IOException e) { // Shouldn't happen if done correctly e.printStackTrace(); errorMsg = "IOException whilst reading compile flags"; isCompatible = false; return false; } String ANDROID_ABI = properties.getProperty("ANDROID_ABI"); boolean NO_NEON = properties.getProperty("NO_NEON","0").equals("1"); boolean NO_FPU = properties.getProperty("NO_FPU","0").equals("1"); boolean NO_ARMV6 = properties.getProperty("NO_ARMV6","0").equals("1"); boolean hasNeon = false, hasFpu = false, hasArmV6 = false, hasArmV7 = false; boolean hasX86 = false; if(android.os.Build.CPU_ABI.equals("x86")) { hasX86 = true; } else if(android.os.Build.CPU_ABI.equals("armeabi-v7a") || android.os.Build.CPU_ABI2.equals("armeabi-v7a")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } else if(android.os.Build.CPU_ABI.equals("armeabi") || android.os.Build.CPU_ABI2.equals("armeabi")) { hasArmV6 = true; } try { FileReader fileReader = new FileReader("/proc/cpuinfo"); BufferedReader br = new BufferedReader(fileReader); String line; while((line = br.readLine()) != null) { if(!hasArmV7 && line.contains("ARMv7")) { hasArmV7 = true; hasArmV6 = true; /* Armv7 is backwards compatible to < v6 */ } if(!hasArmV7 && !hasArmV6 && line.contains("ARMv6")) hasArmV6 = true; // "clflush size" is a x86-specific cpuinfo tag. // (see kernel sources arch/x86/kernel/cpu/proc.c) if(line.contains("clflush size")) hasX86 = true; // TODO: MIPS - "microsecond timers"; see arch/mips/kernel/proc.c if(!hasNeon && line.contains("neon")) hasNeon = true; if(!hasFpu && line.contains("vfp")) hasFpu = true; } fileReader.close(); } catch(IOException ex){ ex.printStackTrace(); errorMsg = "IOException whilst reading cpuinfo flags"; isCompatible = false; return false; } // Enforce proper architecture to prevent problems if(ANDROID_ABI.equals("x86") && !hasX86) { errorMsg = "x86 build on non-x86 device"; isCompatible = false; return false; } else if(hasX86 && ANDROID_ABI.contains("armeabi")) { errorMsg = "ARM build on x86 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi-v7a") && !hasArmV7) { errorMsg = "ARMv7 build on non-ARMv7 device"; isCompatible = false; return false; } if(ANDROID_ABI.equals("armeabi")) { if(!NO_ARMV6 && !hasArmV6) { errorMsg = "ARMv6 build on non-ARMv6 device"; isCompatible = false; return false; } else if(!NO_FPU && !hasFpu) { errorMsg = "FPU-enabled build on non-FPU device"; isCompatible = false; return false; } } if(ANDROID_ABI.equals("armeabi") || ANDROID_ABI.equals("armeabi-v7a")) { if(!NO_NEON && !hasNeon) { errorMsg = "NEON build on non-NEON device"; isCompatible = false; return false; } } errorMsg = null; isCompatible = true; return true; }
diff --git a/JKeyedBits/src/com/aqnichol/keyedbits/decode/FileDecodeStream.java b/JKeyedBits/src/com/aqnichol/keyedbits/decode/FileDecodeStream.java index 715ba9c..b8cf9db 100644 --- a/JKeyedBits/src/com/aqnichol/keyedbits/decode/FileDecodeStream.java +++ b/JKeyedBits/src/com/aqnichol/keyedbits/decode/FileDecodeStream.java @@ -1,42 +1,44 @@ package com.aqnichol.keyedbits.decode; import java.io.IOException; import java.io.InputStream; public class FileDecodeStream extends DecodeStream { private InputStream stream; public FileDecodeStream (InputStream stream) { this.stream = stream; } public InputStream getInputStream () { return stream; } public byte[] readBytes (int length) { byte[] bytes = new byte[length]; int hasBytes = 0; while (hasBytes < length) { int read = 0; try { read = stream.read(bytes, hasBytes, length - hasBytes); } catch (IOException e) { throw new DecodeStreamReadError("Failed to read from input stream.", e); } - if (read < 0) return null; + if (read < 0) { + throw new DecodeStreamReadError("Failed to read from input stream.", null); + } hasBytes += read; } return bytes; } public void closeStream() { try { stream.close(); } catch (IOException e) { throw new DecodeStreamReadError("Failed to close input stream.", e); } } }
true
true
public byte[] readBytes (int length) { byte[] bytes = new byte[length]; int hasBytes = 0; while (hasBytes < length) { int read = 0; try { read = stream.read(bytes, hasBytes, length - hasBytes); } catch (IOException e) { throw new DecodeStreamReadError("Failed to read from input stream.", e); } if (read < 0) return null; hasBytes += read; } return bytes; }
public byte[] readBytes (int length) { byte[] bytes = new byte[length]; int hasBytes = 0; while (hasBytes < length) { int read = 0; try { read = stream.read(bytes, hasBytes, length - hasBytes); } catch (IOException e) { throw new DecodeStreamReadError("Failed to read from input stream.", e); } if (read < 0) { throw new DecodeStreamReadError("Failed to read from input stream.", null); } hasBytes += read; } return bytes; }
diff --git a/java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java b/java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java index b554da162..897eb5728 100644 --- a/java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java +++ b/java/src/org/broadinstitute/sting/playground/fourbasecaller/FourBaseRecaller.java @@ -1,233 +1,233 @@ package org.broadinstitute.sting.playground.fourbasecaller; import java.io.File; import java.io.FilenameFilter; import java.io.FileFilter; import java.util.Vector; import java.lang.Math; import org.broadinstitute.sting.playground.illumina.FirecrestFileParser; import org.broadinstitute.sting.playground.illumina.FourIntensity; import cern.colt.matrix.linalg.Algebra; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleFactory1D; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.SAMFileWriter; import net.sf.samtools.SAMFileWriterFactory; import net.sf.samtools.SAMRecord; import edu.mit.broad.picard.illumina.BustardFileParser; import edu.mit.broad.picard.illumina.BustardReadData; import edu.mit.broad.picard.illumina.BustardFileParser_1_1; public class FourBaseRecaller { public static void main(String[] argv) { // Parse args File FIRECREST_DIR = new File(argv[0]); int LANE = Integer.valueOf(argv[1]); File SAM_OUT = new File(argv[2]); int CYCLE_START = Integer.valueOf(argv[3]); int CYCLE_STOP = Integer.valueOf(argv[4]); boolean isPaired = Boolean.valueOf(argv[5]); int readLength = (CYCLE_STOP - CYCLE_START); File BUSTARD_DIR = getBustardDirectory(FIRECREST_DIR); int limit = 1000000; NucleotideChannelMeans[] cmeans = new NucleotideChannelMeans[readLength]; NucleotideChannelCovariances[] ccov = new NucleotideChannelCovariances[readLength]; for (int i = 0; i < readLength; i++) { cmeans[i] = new NucleotideChannelMeans(); ccov[i] = new NucleotideChannelCovariances(); } // Loop through bustard data and compute signal means FirecrestFileParser ffp1 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp1 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp1.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for means."); } FourIntensity[] intensities = ffp1.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp1.next().getFirstReadSequence() : bfp1.next().getSecondReadSequence(); - for (int cycle = 0; cycle < intensities.length; cycle++) { + for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity sig = intensities[cycle]; if (rsq.charAt(cycle) == 'A') { cmeans[cycle].add(Nucleotide.A, sig); } else if (rsq.charAt(cycle) == 'C') { cmeans[cycle].add(Nucleotide.C, sig); } else if (rsq.charAt(cycle) == 'G') { cmeans[cycle].add(Nucleotide.G, sig); } else if (rsq.charAt(cycle) == 'T') { cmeans[cycle].add(Nucleotide.T, sig); } } } // Go through the data again and compute signal covariances FirecrestFileParser ffp2 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp2 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp2.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for covariances."); } FourIntensity[] intensities = ffp2.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp2.next().getFirstReadSequence() : bfp2.next().getSecondReadSequence(); - for (int cycle = 0; cycle < intensities.length; cycle++) { + for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity sig = intensities[cycle]; NucleotideChannelMeans mus = cmeans[cycle]; if (rsq.charAt(cycle) == 'A') { ccov[cycle].add(Nucleotide.A, sig, mus); } else if (rsq.charAt(cycle) == 'C') { ccov[cycle].add(Nucleotide.C, sig, mus); } else if (rsq.charAt(cycle) == 'G') { ccov[cycle].add(Nucleotide.G, sig, mus); } else if (rsq.charAt(cycle) == 'T') { ccov[cycle].add(Nucleotide.T, sig, mus); } } } // Now compute probabilities for the bases Algebra alg = new Algebra(); for (int cycle = 0; cycle < readLength; cycle++) { ccov[cycle].invert(); } FirecrestFileParser ffp3 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); SAMFileHeader sfh = new SAMFileHeader(); SAMFileWriter sfw = new SAMFileWriterFactory().makeSAMOrBAMWriter(sfh, false, SAM_OUT); for (int queryid = 0; ffp3.hasNext(); queryid++) { if (queryid % limit == 0) { System.err.println("Basecalled " + queryid + " reads."); } FourIntensity[] intensities = ffp3.next().getIntensities(); - byte[] asciiseq = new byte[intensities.length]; - byte[] bestqual = new byte[intensities.length]; - byte[] nextbestqual = new byte[intensities.length]; + byte[] asciiseq = new byte[readLength]; + byte[] bestqual = new byte[readLength]; + byte[] nextbestqual = new byte[readLength]; - for (int cycle = 0; cycle < intensities.length; cycle++) { + for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity fi = intensities[cycle]; double[] likes = new double[4]; double total = 0.0; for (Nucleotide nuc : Nucleotide.values()) { double norm = Math.sqrt(alg.det(ccov[cycle].channelCovariances(nuc)))/Math.pow(2.0*Math.PI, 2.0); DoubleMatrix1D sub = subtract(fi, cmeans[cycle].channelMeans(nuc)); DoubleMatrix1D Ax = alg.mult(ccov[cycle].channelCovariances(nuc), sub); double exparg = -0.5*alg.mult(sub, Ax); likes[nuc.ordinal()] = norm*Math.exp(exparg); total += likes[nuc.ordinal()]; } Nucleotide call1 = Nucleotide.A; double prob1 = likes[0]/total; for (int i = 1; i < 4; i++) { if (likes[i]/total > prob1) { prob1 = likes[i]/total; switch (i) { case 1: call1 = Nucleotide.C; break; case 2: call1 = Nucleotide.G; break; case 3: call1 = Nucleotide.T; break; } } } Nucleotide call2 = Nucleotide.A; double prob2 = 0.0; for (int i = 0; i < 4; i++) { if (i != call1.ordinal() && likes[i]/total > prob2 && likes[i]/total < prob1) { prob2 = likes[i]/total; switch (i) { case 0: call2 = Nucleotide.A; break; case 1: call2 = Nucleotide.C; break; case 2: call2 = Nucleotide.G; break; case 3: call2 = Nucleotide.T; break; } } } asciiseq[cycle] = (byte) call1.asChar(); bestqual[cycle] = toPhredScore(prob1); nextbestqual[cycle] = toCompressedQuality(call2, prob2); } SAMRecord sr = new SAMRecord(sfh); sr.setReadName(Integer.toString(queryid)); sr.setReadUmappedFlag(true); sr.setReadBases(asciiseq); sr.setBaseQualities(bestqual); sr.setAttribute("SQ", nextbestqual); sfw.addAlignment(sr); queryid++; } sfw.close(); System.err.println("Done."); } private static byte toPhredScore(double prob) { byte qual = (1.0 - prob < 0.00001) ? 40 : (byte) (-10*Math.log10(1.0 - prob)); //System.out.println("prob=" + prob + " qual=" + qual); return (qual > 40) ? 40 : qual; } private static DoubleMatrix1D subtract(FourIntensity a, FourIntensity b) { DoubleMatrix1D sub = (DoubleFactory1D.dense).make(4); for (int i = 0; i < 4; i++) { sub.set(i, a.getChannelIntensity(i) - b.getChannelIntensity(i)); } return sub; } private static byte toCompressedQuality(Nucleotide base, double prob) { byte compressedQual = (byte) base.ordinal(); byte cprob = (byte) (100.0*prob); byte qualmask = (byte) 252; compressedQual += ((cprob << 2) & qualmask); return compressedQual; } private static NucleotideSequence toNucleotideSequence(FourIntensity[] intensities) { NucleotideSequence ns = new NucleotideSequence(intensities.length); for (int cycle = 0; cycle < intensities.length; cycle++) { int brightestChannel = intensities[cycle].brightestChannel(); Nucleotide nt = Nucleotide.A; switch (brightestChannel) { case 0: nt = Nucleotide.A; break; case 1: nt = Nucleotide.C; break; case 2: nt = Nucleotide.G; break; case 3: nt = Nucleotide.T; break; } ns.set(cycle, nt); } return ns; } private static File getBustardDirectory(File firecrestDir) { FileFilter filter = new FileFilter() { public boolean accept(File file) { return (file.isDirectory() && file.getName().contains("Bustard")); } }; File[] bustardDirs = firecrestDir.listFiles(filter); return bustardDirs[0]; } }
false
true
public static void main(String[] argv) { // Parse args File FIRECREST_DIR = new File(argv[0]); int LANE = Integer.valueOf(argv[1]); File SAM_OUT = new File(argv[2]); int CYCLE_START = Integer.valueOf(argv[3]); int CYCLE_STOP = Integer.valueOf(argv[4]); boolean isPaired = Boolean.valueOf(argv[5]); int readLength = (CYCLE_STOP - CYCLE_START); File BUSTARD_DIR = getBustardDirectory(FIRECREST_DIR); int limit = 1000000; NucleotideChannelMeans[] cmeans = new NucleotideChannelMeans[readLength]; NucleotideChannelCovariances[] ccov = new NucleotideChannelCovariances[readLength]; for (int i = 0; i < readLength; i++) { cmeans[i] = new NucleotideChannelMeans(); ccov[i] = new NucleotideChannelCovariances(); } // Loop through bustard data and compute signal means FirecrestFileParser ffp1 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp1 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp1.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for means."); } FourIntensity[] intensities = ffp1.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp1.next().getFirstReadSequence() : bfp1.next().getSecondReadSequence(); for (int cycle = 0; cycle < intensities.length; cycle++) { FourIntensity sig = intensities[cycle]; if (rsq.charAt(cycle) == 'A') { cmeans[cycle].add(Nucleotide.A, sig); } else if (rsq.charAt(cycle) == 'C') { cmeans[cycle].add(Nucleotide.C, sig); } else if (rsq.charAt(cycle) == 'G') { cmeans[cycle].add(Nucleotide.G, sig); } else if (rsq.charAt(cycle) == 'T') { cmeans[cycle].add(Nucleotide.T, sig); } } } // Go through the data again and compute signal covariances FirecrestFileParser ffp2 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp2 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp2.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for covariances."); } FourIntensity[] intensities = ffp2.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp2.next().getFirstReadSequence() : bfp2.next().getSecondReadSequence(); for (int cycle = 0; cycle < intensities.length; cycle++) { FourIntensity sig = intensities[cycle]; NucleotideChannelMeans mus = cmeans[cycle]; if (rsq.charAt(cycle) == 'A') { ccov[cycle].add(Nucleotide.A, sig, mus); } else if (rsq.charAt(cycle) == 'C') { ccov[cycle].add(Nucleotide.C, sig, mus); } else if (rsq.charAt(cycle) == 'G') { ccov[cycle].add(Nucleotide.G, sig, mus); } else if (rsq.charAt(cycle) == 'T') { ccov[cycle].add(Nucleotide.T, sig, mus); } } } // Now compute probabilities for the bases Algebra alg = new Algebra(); for (int cycle = 0; cycle < readLength; cycle++) { ccov[cycle].invert(); } FirecrestFileParser ffp3 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); SAMFileHeader sfh = new SAMFileHeader(); SAMFileWriter sfw = new SAMFileWriterFactory().makeSAMOrBAMWriter(sfh, false, SAM_OUT); for (int queryid = 0; ffp3.hasNext(); queryid++) { if (queryid % limit == 0) { System.err.println("Basecalled " + queryid + " reads."); } FourIntensity[] intensities = ffp3.next().getIntensities(); byte[] asciiseq = new byte[intensities.length]; byte[] bestqual = new byte[intensities.length]; byte[] nextbestqual = new byte[intensities.length]; for (int cycle = 0; cycle < intensities.length; cycle++) { FourIntensity fi = intensities[cycle]; double[] likes = new double[4]; double total = 0.0; for (Nucleotide nuc : Nucleotide.values()) { double norm = Math.sqrt(alg.det(ccov[cycle].channelCovariances(nuc)))/Math.pow(2.0*Math.PI, 2.0); DoubleMatrix1D sub = subtract(fi, cmeans[cycle].channelMeans(nuc)); DoubleMatrix1D Ax = alg.mult(ccov[cycle].channelCovariances(nuc), sub); double exparg = -0.5*alg.mult(sub, Ax); likes[nuc.ordinal()] = norm*Math.exp(exparg); total += likes[nuc.ordinal()]; } Nucleotide call1 = Nucleotide.A; double prob1 = likes[0]/total; for (int i = 1; i < 4; i++) { if (likes[i]/total > prob1) { prob1 = likes[i]/total; switch (i) { case 1: call1 = Nucleotide.C; break; case 2: call1 = Nucleotide.G; break; case 3: call1 = Nucleotide.T; break; } } } Nucleotide call2 = Nucleotide.A; double prob2 = 0.0; for (int i = 0; i < 4; i++) { if (i != call1.ordinal() && likes[i]/total > prob2 && likes[i]/total < prob1) { prob2 = likes[i]/total; switch (i) { case 0: call2 = Nucleotide.A; break; case 1: call2 = Nucleotide.C; break; case 2: call2 = Nucleotide.G; break; case 3: call2 = Nucleotide.T; break; } } } asciiseq[cycle] = (byte) call1.asChar(); bestqual[cycle] = toPhredScore(prob1); nextbestqual[cycle] = toCompressedQuality(call2, prob2); } SAMRecord sr = new SAMRecord(sfh); sr.setReadName(Integer.toString(queryid)); sr.setReadUmappedFlag(true); sr.setReadBases(asciiseq); sr.setBaseQualities(bestqual); sr.setAttribute("SQ", nextbestqual); sfw.addAlignment(sr); queryid++; } sfw.close(); System.err.println("Done."); }
public static void main(String[] argv) { // Parse args File FIRECREST_DIR = new File(argv[0]); int LANE = Integer.valueOf(argv[1]); File SAM_OUT = new File(argv[2]); int CYCLE_START = Integer.valueOf(argv[3]); int CYCLE_STOP = Integer.valueOf(argv[4]); boolean isPaired = Boolean.valueOf(argv[5]); int readLength = (CYCLE_STOP - CYCLE_START); File BUSTARD_DIR = getBustardDirectory(FIRECREST_DIR); int limit = 1000000; NucleotideChannelMeans[] cmeans = new NucleotideChannelMeans[readLength]; NucleotideChannelCovariances[] ccov = new NucleotideChannelCovariances[readLength]; for (int i = 0; i < readLength; i++) { cmeans[i] = new NucleotideChannelMeans(); ccov[i] = new NucleotideChannelCovariances(); } // Loop through bustard data and compute signal means FirecrestFileParser ffp1 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp1 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp1.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for means."); } FourIntensity[] intensities = ffp1.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp1.next().getFirstReadSequence() : bfp1.next().getSecondReadSequence(); for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity sig = intensities[cycle]; if (rsq.charAt(cycle) == 'A') { cmeans[cycle].add(Nucleotide.A, sig); } else if (rsq.charAt(cycle) == 'C') { cmeans[cycle].add(Nucleotide.C, sig); } else if (rsq.charAt(cycle) == 'G') { cmeans[cycle].add(Nucleotide.G, sig); } else if (rsq.charAt(cycle) == 'T') { cmeans[cycle].add(Nucleotide.T, sig); } } } // Go through the data again and compute signal covariances FirecrestFileParser ffp2 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); BustardFileParser_1_1 bfp2 = new BustardFileParser_1_1(BUSTARD_DIR, LANE, isPaired, "BS"); for (int queryid = 0; queryid < limit && ffp2.hasNext(); queryid++) { if (queryid % (limit/10) == 0) { System.err.println("Processed " + queryid + " reads for covariances."); } FourIntensity[] intensities = ffp2.next().getIntensities(); String rsq = (CYCLE_START == 0) ? bfp2.next().getFirstReadSequence() : bfp2.next().getSecondReadSequence(); for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity sig = intensities[cycle]; NucleotideChannelMeans mus = cmeans[cycle]; if (rsq.charAt(cycle) == 'A') { ccov[cycle].add(Nucleotide.A, sig, mus); } else if (rsq.charAt(cycle) == 'C') { ccov[cycle].add(Nucleotide.C, sig, mus); } else if (rsq.charAt(cycle) == 'G') { ccov[cycle].add(Nucleotide.G, sig, mus); } else if (rsq.charAt(cycle) == 'T') { ccov[cycle].add(Nucleotide.T, sig, mus); } } } // Now compute probabilities for the bases Algebra alg = new Algebra(); for (int cycle = 0; cycle < readLength; cycle++) { ccov[cycle].invert(); } FirecrestFileParser ffp3 = new FirecrestFileParser(FIRECREST_DIR, LANE, CYCLE_START, CYCLE_STOP); SAMFileHeader sfh = new SAMFileHeader(); SAMFileWriter sfw = new SAMFileWriterFactory().makeSAMOrBAMWriter(sfh, false, SAM_OUT); for (int queryid = 0; ffp3.hasNext(); queryid++) { if (queryid % limit == 0) { System.err.println("Basecalled " + queryid + " reads."); } FourIntensity[] intensities = ffp3.next().getIntensities(); byte[] asciiseq = new byte[readLength]; byte[] bestqual = new byte[readLength]; byte[] nextbestqual = new byte[readLength]; for (int cycle = 0; cycle < readLength; cycle++) { FourIntensity fi = intensities[cycle]; double[] likes = new double[4]; double total = 0.0; for (Nucleotide nuc : Nucleotide.values()) { double norm = Math.sqrt(alg.det(ccov[cycle].channelCovariances(nuc)))/Math.pow(2.0*Math.PI, 2.0); DoubleMatrix1D sub = subtract(fi, cmeans[cycle].channelMeans(nuc)); DoubleMatrix1D Ax = alg.mult(ccov[cycle].channelCovariances(nuc), sub); double exparg = -0.5*alg.mult(sub, Ax); likes[nuc.ordinal()] = norm*Math.exp(exparg); total += likes[nuc.ordinal()]; } Nucleotide call1 = Nucleotide.A; double prob1 = likes[0]/total; for (int i = 1; i < 4; i++) { if (likes[i]/total > prob1) { prob1 = likes[i]/total; switch (i) { case 1: call1 = Nucleotide.C; break; case 2: call1 = Nucleotide.G; break; case 3: call1 = Nucleotide.T; break; } } } Nucleotide call2 = Nucleotide.A; double prob2 = 0.0; for (int i = 0; i < 4; i++) { if (i != call1.ordinal() && likes[i]/total > prob2 && likes[i]/total < prob1) { prob2 = likes[i]/total; switch (i) { case 0: call2 = Nucleotide.A; break; case 1: call2 = Nucleotide.C; break; case 2: call2 = Nucleotide.G; break; case 3: call2 = Nucleotide.T; break; } } } asciiseq[cycle] = (byte) call1.asChar(); bestqual[cycle] = toPhredScore(prob1); nextbestqual[cycle] = toCompressedQuality(call2, prob2); } SAMRecord sr = new SAMRecord(sfh); sr.setReadName(Integer.toString(queryid)); sr.setReadUmappedFlag(true); sr.setReadBases(asciiseq); sr.setBaseQualities(bestqual); sr.setAttribute("SQ", nextbestqual); sfw.addAlignment(sr); queryid++; } sfw.close(); System.err.println("Done."); }
diff --git a/src/org/tint/ui/preferences/SeekBarPreference.java b/src/org/tint/ui/preferences/SeekBarPreference.java index e642c69..67e8952 100644 --- a/src/org/tint/ui/preferences/SeekBarPreference.java +++ b/src/org/tint/ui/preferences/SeekBarPreference.java @@ -1,147 +1,147 @@ /* * Tint Browser for Android * * Copyright (C) 2012 - to infinity and beyond J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.tint.ui.preferences; import org.tint.R; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.SeekBar; import android.widget.TextView; public class SeekBarPreference extends Preference implements SeekBar.OnSeekBarChangeListener { private int mDefaultValue; private int mMinValue; private int mMaxValue; private int mStepValue; private String mSymbol; private TextView mTitle; private TextView mSummary; private TextView mValue; private SeekBar mSeekBar; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); mMinValue = a.getInt(R.styleable.SeekBarPreference_minValue, 0); mMaxValue = a.getInt(R.styleable.SeekBarPreference_maxValue, 10); mStepValue = a.getInt(R.styleable.SeekBarPreference_stepValue, 1); if (mMaxValue <= mMinValue) { mMaxValue = mMinValue + 1; } if (mDefaultValue < mMinValue) { mDefaultValue = mMinValue; } if (mStepValue <= 0) { mStepValue = 1; } mMinValue = Math.round(mMinValue / mStepValue); mMaxValue = Math.round(mMaxValue / mStepValue); - mDefaultValue = getBoundedValue(a.getInt(R.styleable.SeekBarPreference_android_defaultValue, 0)); + mDefaultValue = a.getInt(R.styleable.SeekBarPreference_android_defaultValue, 0); mSymbol = a.getString(R.styleable.SeekBarPreference_symbol); a.recycle(); } } @Override protected View onCreateView(ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.seekbar_preference, null); mTitle = (TextView) v.findViewById(R.id.SeekBarPreferenceTitle); mTitle.setText(getTitle()); mSummary = (TextView) v.findViewById(R.id.SeekBarPreferenceSummary); if (!TextUtils.isEmpty(getSummary())) { mSummary.setText(getSummary()); } else { mSummary.setVisibility(View.GONE); } mValue = (TextView) v.findViewById(R.id.SeekBarPreferenceValue); mSeekBar = (SeekBar) v.findViewById(R.id.SeekBarPreferenceSeekBar); mSeekBar.setMax(mMaxValue - mMinValue); int currentValue = getBoundedValue(PreferenceManager.getDefaultSharedPreferences(getContext()).getInt(getKey(), mDefaultValue)); currentValue = currentValue - mMinValue; mSeekBar.setProgress(currentValue); updateValue(currentValue, false); mSeekBar.setOnSeekBarChangeListener(this); return v; } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateValue(progress, true); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } private int getBoundedValue(int value) { value = Math.round(value / mStepValue); if (value < mMinValue) { value = mMinValue; } if (value > mMaxValue) { value = mMaxValue; } return value; } private void updateValue(int value, boolean save) { value = (value + mMinValue) * mStepValue; mValue.setText(String.format("%s" + mSymbol, value)); if (save) { PreferenceManager.getDefaultSharedPreferences(getContext()).edit().putInt(getKey(), value).commit(); } } }
true
true
public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); mMinValue = a.getInt(R.styleable.SeekBarPreference_minValue, 0); mMaxValue = a.getInt(R.styleable.SeekBarPreference_maxValue, 10); mStepValue = a.getInt(R.styleable.SeekBarPreference_stepValue, 1); if (mMaxValue <= mMinValue) { mMaxValue = mMinValue + 1; } if (mDefaultValue < mMinValue) { mDefaultValue = mMinValue; } if (mStepValue <= 0) { mStepValue = 1; } mMinValue = Math.round(mMinValue / mStepValue); mMaxValue = Math.round(mMaxValue / mStepValue); mDefaultValue = getBoundedValue(a.getInt(R.styleable.SeekBarPreference_android_defaultValue, 0)); mSymbol = a.getString(R.styleable.SeekBarPreference_symbol); a.recycle(); } }
public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); mMinValue = a.getInt(R.styleable.SeekBarPreference_minValue, 0); mMaxValue = a.getInt(R.styleable.SeekBarPreference_maxValue, 10); mStepValue = a.getInt(R.styleable.SeekBarPreference_stepValue, 1); if (mMaxValue <= mMinValue) { mMaxValue = mMinValue + 1; } if (mDefaultValue < mMinValue) { mDefaultValue = mMinValue; } if (mStepValue <= 0) { mStepValue = 1; } mMinValue = Math.round(mMinValue / mStepValue); mMaxValue = Math.round(mMaxValue / mStepValue); mDefaultValue = a.getInt(R.styleable.SeekBarPreference_android_defaultValue, 0); mSymbol = a.getString(R.styleable.SeekBarPreference_symbol); a.recycle(); } }
diff --git a/src/com/squareup/timessquare/sample/SupportTab.java b/src/com/squareup/timessquare/sample/SupportTab.java index a8415ec..2bc522b 100644 --- a/src/com/squareup/timessquare/sample/SupportTab.java +++ b/src/com/squareup/timessquare/sample/SupportTab.java @@ -1,61 +1,61 @@ package com.squareup.timessquare.sample; import com.squareup.timessquare.sample.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class SupportTab extends Activity{ ListView lv; String[] supportItems; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.support_tab_layout); lv = (ListView) findViewById(R.id.list); supportItems = getResources().getStringArray(R.array.supportItems); lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, supportItems)); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id){ //Contacts if(lv.getItemAtPosition(position) == supportItems[0]) { - Intent i = new Intent(getApplicationContext(), AndroidXMLParsingActivity.class); + Intent i = new Intent(getApplicationContext(), AllContactsActivity.class); startActivity(i); } //Learning Center if(lv.getItemAtPosition(position) == supportItems[1]){ Intent i = new Intent(getApplicationContext(), LearningCenter.class); startActivity(i); } //Videos if(lv.getItemAtPosition(position) == supportItems[2]){ Intent i = new Intent(getApplicationContext(), Videos.class); startActivity(i); } //Scholarships if(lv.getItemAtPosition(position) == supportItems[3]){ Intent i = new Intent(getApplicationContext(), Scholarships.class); startActivity(i); } } }); } }
true
true
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.support_tab_layout); lv = (ListView) findViewById(R.id.list); supportItems = getResources().getStringArray(R.array.supportItems); lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, supportItems)); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id){ //Contacts if(lv.getItemAtPosition(position) == supportItems[0]) { Intent i = new Intent(getApplicationContext(), AndroidXMLParsingActivity.class); startActivity(i); } //Learning Center if(lv.getItemAtPosition(position) == supportItems[1]){ Intent i = new Intent(getApplicationContext(), LearningCenter.class); startActivity(i); } //Videos if(lv.getItemAtPosition(position) == supportItems[2]){ Intent i = new Intent(getApplicationContext(), Videos.class); startActivity(i); } //Scholarships if(lv.getItemAtPosition(position) == supportItems[3]){ Intent i = new Intent(getApplicationContext(), Scholarships.class); startActivity(i); } } }); }
protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.support_tab_layout); lv = (ListView) findViewById(R.id.list); supportItems = getResources().getStringArray(R.array.supportItems); lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, supportItems)); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id){ //Contacts if(lv.getItemAtPosition(position) == supportItems[0]) { Intent i = new Intent(getApplicationContext(), AllContactsActivity.class); startActivity(i); } //Learning Center if(lv.getItemAtPosition(position) == supportItems[1]){ Intent i = new Intent(getApplicationContext(), LearningCenter.class); startActivity(i); } //Videos if(lv.getItemAtPosition(position) == supportItems[2]){ Intent i = new Intent(getApplicationContext(), Videos.class); startActivity(i); } //Scholarships if(lv.getItemAtPosition(position) == supportItems[3]){ Intent i = new Intent(getApplicationContext(), Scholarships.class); startActivity(i); } } }); }
diff --git a/FetchingObjects/Aggregates/src/main/java/cbe/fetching/Aggregates.java b/FetchingObjects/Aggregates/src/main/java/cbe/fetching/Aggregates.java index 3eaeef2..a20cf53 100644 --- a/FetchingObjects/Aggregates/src/main/java/cbe/fetching/Aggregates.java +++ b/FetchingObjects/Aggregates/src/main/java/cbe/fetching/Aggregates.java @@ -1,68 +1,68 @@ package cbe.fetching; import java.math.BigDecimal; import org.apache.cayenne.access.DataContext; import org.apache.cayenne.exp.ExpressionFactory; import org.apache.cayenne.query.SelectQuery; import cbe.fetching.model.Book; import cbe.fetching.utilities.AggregatesUtil; import cbe.fetching.utilities.Populator; /** * Cayenne By Example - https://github.com/mrg/cbe * * @author mrg */ public class Aggregates { public static void main(String[] arguments) { // Populate the database. Populator.populateDatabase(); // Create a new DataContext for the queries. DataContext dataContext = DataContext.createDataContext(); // Create a Query for Book records. SelectQuery query = new SelectQuery(Book.class); // Run the aggregate queries. BigDecimal min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); BigDecimal max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); BigDecimal sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); BigDecimal avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); long count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum Book Price: " + min); System.out.println("Maximum Book Price: " + max); System.out.println("Sum of Book Prices: " + sum); System.out.println("Average Book Price: " + avg); System.out.println("Number of Books: " + count); // Add a qualifier for Author names starting with "J". query.setQualifier(ExpressionFactory.likeIgnoreCaseExp(Book.AUTHOR_PROPERTY, "J%")); // Run the aggregate queries. min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum 'J' Author Book Price: " + min); System.out.println("Maximum 'J' Author Book Price: " + max); System.out.println("Sum of 'J' Author Book Prices: " + sum); System.out.println("Average 'J' Author Book Price: " + avg); System.out.println("Number of 'J' Author Books: " + count); // Make the query use DISTINCT and get a distinct count of authors whose // name begins with "J" by counting on the Book's Author property. query.setDistinct(true); count = AggregatesUtil.count(dataContext, query, Book.AUTHOR_PROPERTY); - System.out.println("Number of 'J' Author Books: " + count); + System.out.println("Number of 'J' Authors: " + count); } }
true
true
public static void main(String[] arguments) { // Populate the database. Populator.populateDatabase(); // Create a new DataContext for the queries. DataContext dataContext = DataContext.createDataContext(); // Create a Query for Book records. SelectQuery query = new SelectQuery(Book.class); // Run the aggregate queries. BigDecimal min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); BigDecimal max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); BigDecimal sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); BigDecimal avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); long count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum Book Price: " + min); System.out.println("Maximum Book Price: " + max); System.out.println("Sum of Book Prices: " + sum); System.out.println("Average Book Price: " + avg); System.out.println("Number of Books: " + count); // Add a qualifier for Author names starting with "J". query.setQualifier(ExpressionFactory.likeIgnoreCaseExp(Book.AUTHOR_PROPERTY, "J%")); // Run the aggregate queries. min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum 'J' Author Book Price: " + min); System.out.println("Maximum 'J' Author Book Price: " + max); System.out.println("Sum of 'J' Author Book Prices: " + sum); System.out.println("Average 'J' Author Book Price: " + avg); System.out.println("Number of 'J' Author Books: " + count); // Make the query use DISTINCT and get a distinct count of authors whose // name begins with "J" by counting on the Book's Author property. query.setDistinct(true); count = AggregatesUtil.count(dataContext, query, Book.AUTHOR_PROPERTY); System.out.println("Number of 'J' Author Books: " + count); }
public static void main(String[] arguments) { // Populate the database. Populator.populateDatabase(); // Create a new DataContext for the queries. DataContext dataContext = DataContext.createDataContext(); // Create a Query for Book records. SelectQuery query = new SelectQuery(Book.class); // Run the aggregate queries. BigDecimal min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); BigDecimal max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); BigDecimal sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); BigDecimal avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); long count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum Book Price: " + min); System.out.println("Maximum Book Price: " + max); System.out.println("Sum of Book Prices: " + sum); System.out.println("Average Book Price: " + avg); System.out.println("Number of Books: " + count); // Add a qualifier for Author names starting with "J". query.setQualifier(ExpressionFactory.likeIgnoreCaseExp(Book.AUTHOR_PROPERTY, "J%")); // Run the aggregate queries. min = AggregatesUtil.min(dataContext, query, Book.PRICE_PROPERTY); max = AggregatesUtil.max(dataContext, query, Book.PRICE_PROPERTY); sum = AggregatesUtil.sum(dataContext, query, Book.PRICE_PROPERTY); avg = AggregatesUtil.avg(dataContext, query, Book.PRICE_PROPERTY); count = AggregatesUtil.count(dataContext, query); // Print the results. System.out.println("Minimum 'J' Author Book Price: " + min); System.out.println("Maximum 'J' Author Book Price: " + max); System.out.println("Sum of 'J' Author Book Prices: " + sum); System.out.println("Average 'J' Author Book Price: " + avg); System.out.println("Number of 'J' Author Books: " + count); // Make the query use DISTINCT and get a distinct count of authors whose // name begins with "J" by counting on the Book's Author property. query.setDistinct(true); count = AggregatesUtil.count(dataContext, query, Book.AUTHOR_PROPERTY); System.out.println("Number of 'J' Authors: " + count); }
diff --git a/TestApp/src/com/artsoft/wifilapper/BluetoothGPS.java b/TestApp/src/com/artsoft/wifilapper/BluetoothGPS.java index 9adf842..66e23cd 100644 --- a/TestApp/src/com/artsoft/wifilapper/BluetoothGPS.java +++ b/TestApp/src/com/artsoft/wifilapper/BluetoothGPS.java @@ -1,435 +1,441 @@ // Copyright 2011-2012, Art Hare // This file is part of WifiLapper. //WifiLapper 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. //WifiLapper 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 WifiLapper. If not, see <http://www.gnu.org/licenses/>. package com.artsoft.wifilapper; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Set; import java.util.UUID; import java.util.Vector; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Handler; import android.os.Message; import android.util.Log; public class BluetoothGPS { public static final String NO_VTG_FOUND = "com.artsoft.BluetoothGPS.NoVTG"; DeviceRecvThread m_thd; public BluetoothGPS(BluetoothDevice dev, LocationListener listener) { m_thd = new DeviceRecvThread(dev, listener); m_thd.start(); } public BluetoothGPS(String strDeviceName, LocationListener listener) { BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); if(ba.isEnabled()) { Set<BluetoothDevice> lstDevices = ba.getBondedDevices(); Iterator<BluetoothDevice> i = lstDevices.iterator(); while(i.hasNext()) { BluetoothDevice bd = i.next(); if(strDeviceName.equals(bd.getName())) { // found our device m_thd = new DeviceRecvThread(bd, listener); m_thd.start(); break; } } } } public boolean IsValid() { return m_thd != null; } public void Shutdown() { if(m_thd != null) { m_thd.Shutdown(); m_thd = null; } } private static class DeviceRecvThread extends Thread implements Runnable, Handler.Callback { BluetoothDevice m_dev; LocationListener m_listener; boolean m_shutdown; Handler m_handler; Vector<Location> m_lstLocs; // must be accessed inside DeviceRecvThread's lock final int MSG_SENDLOCS = 101; final int MSG_LOSTGPS = 102; final int MSG_NOGPSDEVICE = 103; final int MSG_NOVTG = 104; // whether we're in "no VTG mode". Since we can't assume that all our users will figure out the right thing to do wrt qstarz setup, // we should handle the case where it is missing boolean fNoVTGMode = false; long tmLastVTGSeen = 0; // when we last saw a VTG. Starts equal to the current time (since maybe one flew by just before the thread started) double dLastLat = 361; double dLastLong = 361; long lLastTime = -1; float dLastSpeed = 0; public DeviceRecvThread(BluetoothDevice dev, LocationListener listener) { m_lstLocs = new Vector<Location>(); m_dev = dev; m_listener = listener; m_handler = new Handler(this); } public synchronized void Shutdown() { m_shutdown = true; } public static boolean ValidateNMEA(String nmea) { nmea = nmea.replace("\r\n", ""); if(nmea.charAt(0) == '$') { final int ixAst = nmea.lastIndexOf("*"); if(ixAst >= 0 && ixAst < nmea.length()) { final int ixLen = Math.min(ixAst+3, nmea.length()); String strHex = nmea.substring(ixAst+1,ixLen); if(strHex.length() >= 1 && strHex.length() <= 2) { try { int iValue = Integer.parseInt(strHex, 16); byte bXORed = 0; for(int x = 1;x < ixAst; x++) { byte bValue = (byte)nmea.charAt(x); bXORed ^= bValue; } if(bXORed == iValue) { return true; } } catch(NumberFormatException e) { // just fall through and we'll return false below... } } } } return false; } private String ParseAndSendNMEA(String strNMEA) { String strLastLeftover = ""; int ixCur = strNMEA.indexOf("$GPGGA"); while(ixCur != -1) { int ixNext = strNMEA.indexOf("$", ixCur+1); int ixVTG = strNMEA.indexOf("$GPVTG",ixCur+1); // finds the next command + //int ixVTG = -1; int ixNextAfterVTG = strNMEA.indexOf("$",ixVTG+1); if(ixNextAfterVTG == -1) ixNextAfterVTG = strNMEA.length(); if(ixNext == -1) { strLastLeftover = strNMEA.substring(ixCur,strNMEA.length()); break; } else if(ixVTG == -1) { - // we found a GPGGA, but failed to find a GPVTG. This means the user isn't getting accurate velocity readings. + // we found a GPGGA, but failed to find a GPVTG. This means the user isn't getting accurate velocity readings. // what we're going to do is fail for 10 seconds in case one is coming, and then switch to "no VTG mode" long tmNow = System.currentTimeMillis(); if(!fNoVTGMode && (tmNow - this.tmLastVTGSeen < 10000)) { // we're still waiting for that damn VTG to show up. break; } else { // it's been at least 10 seconds, or we're already in no-VTG mode. From now on (until we see a VTG), we're operating in no-VTG mode if(tmNow - tmLastVTGSeen > 10000) { // 10 seconds since our last warning to the user about the hazards of no-VTG mode. m_handler.sendEmptyMessage(MSG_NOVTG); tmLastVTGSeen = tmNow + 100000; // we want the warning to repeat, but not too frequently } fNoVTGMode = true; } } else { tmLastVTGSeen = System.currentTimeMillis(); fNoVTGMode = false; } strLastLeftover = ""; String strGGACommand = strNMEA.substring(ixCur,ixNext); String strGGABits[] = strGGACommand.split(","); String strVTGCommand = null; String strVTGBits[] = null; if(!fNoVTGMode) { strVTGCommand = strNMEA.substring(ixVTG,ixNextAfterVTG); strVTGBits = strVTGCommand.split(","); } if(strGGABits.length >= 6 && ValidateNMEA(strGGACommand) && (fNoVTGMode || (ValidateNMEA(strVTGCommand) && strVTGBits.length >= 8))) { /* 1 = UTC of Position (hhmmss.mmmm) 2 = Latitude 3 = N or S 4 = Longitude 5 = E or W 6 = GPS quality indicator (0=invalid; 1=GPS fix; 2=Diff. GPS fix) 7 = Number of satellites in use [not those in view] 8 = Horizontal dilution of position 9 = Antenna altitude above/below mean sea level (geoid) 10 = Meters (Antenna height unit) 11 = Geoidal separation (Diff. between WGS-84 earth ellipsoid and mean sea level. -=geoid is below WGS-84 ellipsoid) 12 = Meters (Units of geoidal separation) 13 = Age in seconds since last update from diff. reference station 14 = Diff. reference station ID# 15 = Checksum */ String strUTC = strGGABits[1]; String strLat = strGGABits[2]; String strNS = strGGABits[3]; String strLong = strGGABits[4]; String strEW = strGGABits[5]; String strSpeed = null; if(!fNoVTGMode) { strSpeed = strVTGBits[7]; } if(strUTC.length() > 0 && strLat.length() > 0 && strLong.length() > 0 && strNS.length() >= 1 && strEW.length() >= 1) { try { int iLatBase = Integer.parseInt(strLat.substring(0,2)); int iLatFraction = Integer.parseInt(strLat.substring(2,4)); double dLatFinal = Double.parseDouble(strLat.substring(4,strLat.length())); int iLongBase = Integer.parseInt(strLong.substring(0,3)); int iLongFraction = Integer.parseInt(strLong.substring(3,5)); double dLongFinal = Double.parseDouble(strLong.substring(5,strLong.length())); double dLat = iLatBase + ((double)iLatFraction+dLatFinal)/60.0; double dLong = iLongBase + ((double)iLongFraction+dLongFinal)/60.0; if(strNS.charAt(0) == 'S') dLat = -dLat; if(strEW.charAt(0) == 'W') dLong = -dLong; String strMinutes = strUTC.substring(2,4); String strSeconds = strUTC.substring(4,strUTC.length()); int cMinutes = Integer.parseInt(strMinutes); double cSeconds = Double.parseDouble(strSeconds); int cMs = (int)((cSeconds - (int)cSeconds) * 1000); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.MINUTE, cMinutes); cal.set(Calendar.SECOND, (int)cSeconds); cal.set(Calendar.MILLISECOND, cMs); long lTime = cal.getTimeInMillis(); float dSpeed = 0; if(fNoVTGMode) { // we're not getting VTG data, so let's get speed data from differences between lat/long coords float flDistance[] = new float[1]; if(dLastLat <= 360 && dLastLong <= 360 && lLastTime > 0) { Location.distanceBetween(dLastLat, dLastLong, dLat, dLong, flDistance); float dTimeGap = (lTime - lLastTime) / 1000.0f; dSpeed = 0.3f*((flDistance[0] / dTimeGap) * 3.6f) + 0.7f * dLastSpeed; + if(dSpeed > 200 || dSpeed < 0) + { + // for whatever reason our speed is messed up. Don't even bother reporting this. 720km/h should be plenty fast for our users + break; + } } else { // we don't have a last latitude or longitude, so give up now lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; break; } } else { dSpeed = (float)Double.parseDouble(strSpeed); } lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; dLastSpeed = dSpeed; Location l = new Location("ArtBT"); l.setLatitude(dLat); l.setLongitude(dLong); l.setTime(lTime); l.setSpeed(dSpeed/3.6f); synchronized(this) { m_lstLocs.add(l); m_handler.sendEmptyMessage(MSG_SENDLOCS); } } catch(Exception e) { // if it fails to parse the lat long, game over break; } } ixCur = strNMEA.indexOf("$GPGGA",ixCur+1); } else { break; } strLastLeftover = ""; } return strLastLeftover; } public void run() { Thread.currentThread().setName("BT GPS thread"); while(!m_shutdown) { InputStream in = null; BluetoothSocket bs = null; boolean fDeviceGood = true; // assume it's good to begin with... try { bs = m_dev.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")); bs.connect(); in = bs.getInputStream(); fDeviceGood = true; // if we got this far without an exception, the device is good } catch(IOException e) { m_handler.sendEmptyMessage(MSG_NOGPSDEVICE); fDeviceGood = false; } String strLastLeftover = ""; tmLastVTGSeen = System.currentTimeMillis(); while(fDeviceGood && !m_shutdown) { // 1. read buffer // 2. convert to string // 3. find last GPGGA // 4. decode and send int cbRead = 0; byte rgBuffer[] = new byte[10000]; try { cbRead = in.read(rgBuffer,0,rgBuffer.length); } catch (IOException e) { fDeviceGood = false; // we may need to re-acquire the BT device... m_handler.sendEmptyMessage(MSG_LOSTGPS); break; } if(cbRead > 0) { String str = strLastLeftover + new String(rgBuffer); strLastLeftover = ParseAndSendNMEA(str); } } if(in != null) { try{in.close(); } catch(IOException e2) {} } if(bs != null) { try{bs.close(); } catch(IOException e2) {} } try{Thread.sleep(1000);} catch(Exception e) {} // give the lost device some time to re-acquire } } private boolean fLostGPS = true; @Override public boolean handleMessage(Message msg) { if(msg.what == MSG_SENDLOCS) { synchronized(this) { if(fLostGPS) { m_listener.onStatusChanged(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null); fLostGPS = false; } for(int x = 0;x < m_lstLocs.size(); x++) { m_listener.onLocationChanged(m_lstLocs.get(x)); } m_lstLocs.clear(); } } else if(msg.what == MSG_LOSTGPS) { synchronized(this) { m_listener.onStatusChanged(LocationManager.GPS_PROVIDER, LocationProvider.TEMPORARILY_UNAVAILABLE, null); fLostGPS = true; } } else if(msg.what == MSG_NOGPSDEVICE) { synchronized(this) { m_listener.onStatusChanged(LocationManager.GPS_PROVIDER, LocationProvider.OUT_OF_SERVICE, null); fLostGPS = true; } } else if(msg.what == MSG_NOVTG) { synchronized(this) { m_listener.onStatusChanged(BluetoothGPS.NO_VTG_FOUND, 0, null); } } return false; } } }
false
true
private String ParseAndSendNMEA(String strNMEA) { String strLastLeftover = ""; int ixCur = strNMEA.indexOf("$GPGGA"); while(ixCur != -1) { int ixNext = strNMEA.indexOf("$", ixCur+1); int ixVTG = strNMEA.indexOf("$GPVTG",ixCur+1); // finds the next command int ixNextAfterVTG = strNMEA.indexOf("$",ixVTG+1); if(ixNextAfterVTG == -1) ixNextAfterVTG = strNMEA.length(); if(ixNext == -1) { strLastLeftover = strNMEA.substring(ixCur,strNMEA.length()); break; } else if(ixVTG == -1) { // we found a GPGGA, but failed to find a GPVTG. This means the user isn't getting accurate velocity readings. // what we're going to do is fail for 10 seconds in case one is coming, and then switch to "no VTG mode" long tmNow = System.currentTimeMillis(); if(!fNoVTGMode && (tmNow - this.tmLastVTGSeen < 10000)) { // we're still waiting for that damn VTG to show up. break; } else { // it's been at least 10 seconds, or we're already in no-VTG mode. From now on (until we see a VTG), we're operating in no-VTG mode if(tmNow - tmLastVTGSeen > 10000) { // 10 seconds since our last warning to the user about the hazards of no-VTG mode. m_handler.sendEmptyMessage(MSG_NOVTG); tmLastVTGSeen = tmNow + 100000; // we want the warning to repeat, but not too frequently } fNoVTGMode = true; } } else { tmLastVTGSeen = System.currentTimeMillis(); fNoVTGMode = false; } strLastLeftover = ""; String strGGACommand = strNMEA.substring(ixCur,ixNext); String strGGABits[] = strGGACommand.split(","); String strVTGCommand = null; String strVTGBits[] = null; if(!fNoVTGMode) { strVTGCommand = strNMEA.substring(ixVTG,ixNextAfterVTG); strVTGBits = strVTGCommand.split(","); } if(strGGABits.length >= 6 && ValidateNMEA(strGGACommand) && (fNoVTGMode || (ValidateNMEA(strVTGCommand) && strVTGBits.length >= 8))) { /* 1 = UTC of Position (hhmmss.mmmm) 2 = Latitude 3 = N or S 4 = Longitude 5 = E or W 6 = GPS quality indicator (0=invalid; 1=GPS fix; 2=Diff. GPS fix) 7 = Number of satellites in use [not those in view] 8 = Horizontal dilution of position 9 = Antenna altitude above/below mean sea level (geoid) 10 = Meters (Antenna height unit) 11 = Geoidal separation (Diff. between WGS-84 earth ellipsoid and mean sea level. -=geoid is below WGS-84 ellipsoid) 12 = Meters (Units of geoidal separation) 13 = Age in seconds since last update from diff. reference station 14 = Diff. reference station ID# 15 = Checksum */ String strUTC = strGGABits[1]; String strLat = strGGABits[2]; String strNS = strGGABits[3]; String strLong = strGGABits[4]; String strEW = strGGABits[5]; String strSpeed = null; if(!fNoVTGMode) { strSpeed = strVTGBits[7]; } if(strUTC.length() > 0 && strLat.length() > 0 && strLong.length() > 0 && strNS.length() >= 1 && strEW.length() >= 1) { try { int iLatBase = Integer.parseInt(strLat.substring(0,2)); int iLatFraction = Integer.parseInt(strLat.substring(2,4)); double dLatFinal = Double.parseDouble(strLat.substring(4,strLat.length())); int iLongBase = Integer.parseInt(strLong.substring(0,3)); int iLongFraction = Integer.parseInt(strLong.substring(3,5)); double dLongFinal = Double.parseDouble(strLong.substring(5,strLong.length())); double dLat = iLatBase + ((double)iLatFraction+dLatFinal)/60.0; double dLong = iLongBase + ((double)iLongFraction+dLongFinal)/60.0; if(strNS.charAt(0) == 'S') dLat = -dLat; if(strEW.charAt(0) == 'W') dLong = -dLong; String strMinutes = strUTC.substring(2,4); String strSeconds = strUTC.substring(4,strUTC.length()); int cMinutes = Integer.parseInt(strMinutes); double cSeconds = Double.parseDouble(strSeconds); int cMs = (int)((cSeconds - (int)cSeconds) * 1000); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.MINUTE, cMinutes); cal.set(Calendar.SECOND, (int)cSeconds); cal.set(Calendar.MILLISECOND, cMs); long lTime = cal.getTimeInMillis(); float dSpeed = 0; if(fNoVTGMode) { // we're not getting VTG data, so let's get speed data from differences between lat/long coords float flDistance[] = new float[1]; if(dLastLat <= 360 && dLastLong <= 360 && lLastTime > 0) { Location.distanceBetween(dLastLat, dLastLong, dLat, dLong, flDistance); float dTimeGap = (lTime - lLastTime) / 1000.0f; dSpeed = 0.3f*((flDistance[0] / dTimeGap) * 3.6f) + 0.7f * dLastSpeed; } else { // we don't have a last latitude or longitude, so give up now lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; break; } } else { dSpeed = (float)Double.parseDouble(strSpeed); } lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; dLastSpeed = dSpeed; Location l = new Location("ArtBT"); l.setLatitude(dLat); l.setLongitude(dLong); l.setTime(lTime); l.setSpeed(dSpeed/3.6f); synchronized(this) { m_lstLocs.add(l); m_handler.sendEmptyMessage(MSG_SENDLOCS); } } catch(Exception e) { // if it fails to parse the lat long, game over break; } } ixCur = strNMEA.indexOf("$GPGGA",ixCur+1); } else { break; } strLastLeftover = ""; } return strLastLeftover; }
private String ParseAndSendNMEA(String strNMEA) { String strLastLeftover = ""; int ixCur = strNMEA.indexOf("$GPGGA"); while(ixCur != -1) { int ixNext = strNMEA.indexOf("$", ixCur+1); int ixVTG = strNMEA.indexOf("$GPVTG",ixCur+1); // finds the next command //int ixVTG = -1; int ixNextAfterVTG = strNMEA.indexOf("$",ixVTG+1); if(ixNextAfterVTG == -1) ixNextAfterVTG = strNMEA.length(); if(ixNext == -1) { strLastLeftover = strNMEA.substring(ixCur,strNMEA.length()); break; } else if(ixVTG == -1) { // we found a GPGGA, but failed to find a GPVTG. This means the user isn't getting accurate velocity readings. // what we're going to do is fail for 10 seconds in case one is coming, and then switch to "no VTG mode" long tmNow = System.currentTimeMillis(); if(!fNoVTGMode && (tmNow - this.tmLastVTGSeen < 10000)) { // we're still waiting for that damn VTG to show up. break; } else { // it's been at least 10 seconds, or we're already in no-VTG mode. From now on (until we see a VTG), we're operating in no-VTG mode if(tmNow - tmLastVTGSeen > 10000) { // 10 seconds since our last warning to the user about the hazards of no-VTG mode. m_handler.sendEmptyMessage(MSG_NOVTG); tmLastVTGSeen = tmNow + 100000; // we want the warning to repeat, but not too frequently } fNoVTGMode = true; } } else { tmLastVTGSeen = System.currentTimeMillis(); fNoVTGMode = false; } strLastLeftover = ""; String strGGACommand = strNMEA.substring(ixCur,ixNext); String strGGABits[] = strGGACommand.split(","); String strVTGCommand = null; String strVTGBits[] = null; if(!fNoVTGMode) { strVTGCommand = strNMEA.substring(ixVTG,ixNextAfterVTG); strVTGBits = strVTGCommand.split(","); } if(strGGABits.length >= 6 && ValidateNMEA(strGGACommand) && (fNoVTGMode || (ValidateNMEA(strVTGCommand) && strVTGBits.length >= 8))) { /* 1 = UTC of Position (hhmmss.mmmm) 2 = Latitude 3 = N or S 4 = Longitude 5 = E or W 6 = GPS quality indicator (0=invalid; 1=GPS fix; 2=Diff. GPS fix) 7 = Number of satellites in use [not those in view] 8 = Horizontal dilution of position 9 = Antenna altitude above/below mean sea level (geoid) 10 = Meters (Antenna height unit) 11 = Geoidal separation (Diff. between WGS-84 earth ellipsoid and mean sea level. -=geoid is below WGS-84 ellipsoid) 12 = Meters (Units of geoidal separation) 13 = Age in seconds since last update from diff. reference station 14 = Diff. reference station ID# 15 = Checksum */ String strUTC = strGGABits[1]; String strLat = strGGABits[2]; String strNS = strGGABits[3]; String strLong = strGGABits[4]; String strEW = strGGABits[5]; String strSpeed = null; if(!fNoVTGMode) { strSpeed = strVTGBits[7]; } if(strUTC.length() > 0 && strLat.length() > 0 && strLong.length() > 0 && strNS.length() >= 1 && strEW.length() >= 1) { try { int iLatBase = Integer.parseInt(strLat.substring(0,2)); int iLatFraction = Integer.parseInt(strLat.substring(2,4)); double dLatFinal = Double.parseDouble(strLat.substring(4,strLat.length())); int iLongBase = Integer.parseInt(strLong.substring(0,3)); int iLongFraction = Integer.parseInt(strLong.substring(3,5)); double dLongFinal = Double.parseDouble(strLong.substring(5,strLong.length())); double dLat = iLatBase + ((double)iLatFraction+dLatFinal)/60.0; double dLong = iLongBase + ((double)iLongFraction+dLongFinal)/60.0; if(strNS.charAt(0) == 'S') dLat = -dLat; if(strEW.charAt(0) == 'W') dLong = -dLong; String strMinutes = strUTC.substring(2,4); String strSeconds = strUTC.substring(4,strUTC.length()); int cMinutes = Integer.parseInt(strMinutes); double cSeconds = Double.parseDouble(strSeconds); int cMs = (int)((cSeconds - (int)cSeconds) * 1000); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.MINUTE, cMinutes); cal.set(Calendar.SECOND, (int)cSeconds); cal.set(Calendar.MILLISECOND, cMs); long lTime = cal.getTimeInMillis(); float dSpeed = 0; if(fNoVTGMode) { // we're not getting VTG data, so let's get speed data from differences between lat/long coords float flDistance[] = new float[1]; if(dLastLat <= 360 && dLastLong <= 360 && lLastTime > 0) { Location.distanceBetween(dLastLat, dLastLong, dLat, dLong, flDistance); float dTimeGap = (lTime - lLastTime) / 1000.0f; dSpeed = 0.3f*((flDistance[0] / dTimeGap) * 3.6f) + 0.7f * dLastSpeed; if(dSpeed > 200 || dSpeed < 0) { // for whatever reason our speed is messed up. Don't even bother reporting this. 720km/h should be plenty fast for our users break; } } else { // we don't have a last latitude or longitude, so give up now lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; break; } } else { dSpeed = (float)Double.parseDouble(strSpeed); } lLastTime = lTime; dLastLat = dLat; dLastLong = dLong; dLastSpeed = dSpeed; Location l = new Location("ArtBT"); l.setLatitude(dLat); l.setLongitude(dLong); l.setTime(lTime); l.setSpeed(dSpeed/3.6f); synchronized(this) { m_lstLocs.add(l); m_handler.sendEmptyMessage(MSG_SENDLOCS); } } catch(Exception e) { // if it fails to parse the lat long, game over break; } } ixCur = strNMEA.indexOf("$GPGGA",ixCur+1); } else { break; } strLastLeftover = ""; } return strLastLeftover; }
diff --git a/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java b/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java index 47fdb6428..169b4b65b 100644 --- a/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java +++ b/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java @@ -1,91 +1,91 @@ /* 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.commons; import groovy.lang.GroovyResourceLoader; import org.springframework.core.io.Resource; import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; /** * A GroovyResourceLoader that loads groovy files using Spring's IO abstraction * * @author Graeme Rocher * @since 22-Feb-2006 */ public class GrailsResourceLoader implements GroovyResourceLoader { private Resource[] resources; private List loadedResources = new ArrayList(); private Map classToResource = new HashMap(); public GrailsResourceLoader(Resource[] resources) { this.resources = resources; } public List getLoadedResources() { return loadedResources; } public void setResources(Resource[] resources) { this.resources = resources; } public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { - throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please check remove one to avoid duplicates."); + throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns the Grails resource for the given class or null if it is not a Grails resource * * @param theClass The class * @return The Resource or null */ public Resource getResourceForClass(Class theClass) { return (Resource)classToResource.get(theClass.getName()); } }
true
true
public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please check remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } }
public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/src/main/java/me/smecsia/smartfox/tools/service/AuthService.java b/src/main/java/me/smecsia/smartfox/tools/service/AuthService.java index 2478ef4..2ca4441 100644 --- a/src/main/java/me/smecsia/smartfox/tools/service/AuthService.java +++ b/src/main/java/me/smecsia/smartfox/tools/service/AuthService.java @@ -1,49 +1,49 @@ package me.smecsia.smartfox.tools.service; import com.smartfoxserver.v2.entities.User; import me.smecsia.smartfox.tools.annotations.Security; import me.smecsia.smartfox.tools.common.BasicHandler; import me.smecsia.smartfox.tools.common.BasicService; import me.smecsia.smartfox.tools.error.MetadataException; import me.smecsia.smartfox.tools.error.UnauthorizedException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * * @author Ilya Sadykov * Date: 13.10.12 * Time: 17:15 */ public class AuthService extends BasicService { private static class AuthStrategy { public AuthService service; public Boolean authRequired; } private static final Map<Class<? extends BasicHandler>, AuthStrategy> authCache = new ConcurrentHashMap<Class<? extends BasicHandler>, AuthStrategy>(); public static void checkAuthIfRequired(BasicHandler handler, User user) { if (!authCache.containsKey(handler.getClass())) { Security security = handler.getClass().getAnnotation(Security.class); AuthStrategy authStrategy = new AuthStrategy(); try { - authStrategy.service = security.authService().newInstance(); - authStrategy.authRequired = security.authRequired(); + authStrategy.service = (security != null) ? security.authService().newInstance() : new AuthService(); + authStrategy.authRequired = (security != null) && security.authRequired(); authCache.put(handler.getClass(), authStrategy); } catch (Exception e) { throw new MetadataException(e); } } if (authCache.containsKey(handler.getClass()) && authCache.get(handler.getClass()).authRequired) { authCache.get(handler.getClass()).service.check(user); } } public void check(User user) throws UnauthorizedException { // Override me } }
true
true
public static void checkAuthIfRequired(BasicHandler handler, User user) { if (!authCache.containsKey(handler.getClass())) { Security security = handler.getClass().getAnnotation(Security.class); AuthStrategy authStrategy = new AuthStrategy(); try { authStrategy.service = security.authService().newInstance(); authStrategy.authRequired = security.authRequired(); authCache.put(handler.getClass(), authStrategy); } catch (Exception e) { throw new MetadataException(e); } } if (authCache.containsKey(handler.getClass()) && authCache.get(handler.getClass()).authRequired) { authCache.get(handler.getClass()).service.check(user); } }
public static void checkAuthIfRequired(BasicHandler handler, User user) { if (!authCache.containsKey(handler.getClass())) { Security security = handler.getClass().getAnnotation(Security.class); AuthStrategy authStrategy = new AuthStrategy(); try { authStrategy.service = (security != null) ? security.authService().newInstance() : new AuthService(); authStrategy.authRequired = (security != null) && security.authRequired(); authCache.put(handler.getClass(), authStrategy); } catch (Exception e) { throw new MetadataException(e); } } if (authCache.containsKey(handler.getClass()) && authCache.get(handler.getClass()).authRequired) { authCache.get(handler.getClass()).service.check(user); } }
diff --git a/src/main/java/ee/ignorance/transformiceapi/protocol/server/TribePlayerResponse.java b/src/main/java/ee/ignorance/transformiceapi/protocol/server/TribePlayerResponse.java index c81f124..ef48704 100644 --- a/src/main/java/ee/ignorance/transformiceapi/protocol/server/TribePlayerResponse.java +++ b/src/main/java/ee/ignorance/transformiceapi/protocol/server/TribePlayerResponse.java @@ -1,43 +1,43 @@ package ee.ignorance.transformiceapi.protocol.server; import java.util.List; import ee.ignorance.transformiceapi.processors.AbstractProcessor; import ee.ignorance.transformiceapi.processors.TribePlayerProcessor; import ee.ignorance.transformiceapi.titles.TribeRank; public final class TribePlayerResponse implements Processable { private String playerName; private TribeRank rank; private int type; public TribePlayerResponse(List<String> rawMessage) { if (rawMessage.size() > 1) { type = Integer.parseInt(rawMessage.get(1)); } if (rawMessage.size() > 2) { playerName = rawMessage.get(2); } - if (rawMessage.size() > 3) { + if (getType() == 12) { // Not sure if it's good to place it here rank = TribeRank.getRank(Integer.parseInt(rawMessage.get(3))); } } public String getPlayerName() { return playerName; } public TribeRank getRank() { return rank; } public int getType() { return type; } @Override public AbstractProcessor getProcessor() { return new TribePlayerProcessor(); } }
true
true
public TribePlayerResponse(List<String> rawMessage) { if (rawMessage.size() > 1) { type = Integer.parseInt(rawMessage.get(1)); } if (rawMessage.size() > 2) { playerName = rawMessage.get(2); } if (rawMessage.size() > 3) { rank = TribeRank.getRank(Integer.parseInt(rawMessage.get(3))); } }
public TribePlayerResponse(List<String> rawMessage) { if (rawMessage.size() > 1) { type = Integer.parseInt(rawMessage.get(1)); } if (rawMessage.size() > 2) { playerName = rawMessage.get(2); } if (getType() == 12) { // Not sure if it's good to place it here rank = TribeRank.getRank(Integer.parseInt(rawMessage.get(3))); } }
diff --git a/src/dk/itu/big_red/model/import_export/ReactionRuleXMLExport.java b/src/dk/itu/big_red/model/import_export/ReactionRuleXMLExport.java index 8ba35f45..54207070 100644 --- a/src/dk/itu/big_red/model/import_export/ReactionRuleXMLExport.java +++ b/src/dk/itu/big_red/model/import_export/ReactionRuleXMLExport.java @@ -1,177 +1,179 @@ package dk.itu.big_red.model.import_export; import org.w3c.dom.Element; import dk.itu.big_red.import_export.ExportFailedException; import dk.itu.big_red.import_export.XMLExport; import dk.itu.big_red.model.Bigraph; import dk.itu.big_red.model.Colourable; import dk.itu.big_red.model.Container; import dk.itu.big_red.model.Edge; import dk.itu.big_red.model.InnerName; import dk.itu.big_red.model.Layoutable; import dk.itu.big_red.model.Link; import dk.itu.big_red.model.Node; import dk.itu.big_red.model.OuterName; import dk.itu.big_red.model.Point; import dk.itu.big_red.model.Port; import dk.itu.big_red.model.ReactionRule; import dk.itu.big_red.model.Root; import dk.itu.big_red.model.Site; import dk.itu.big_red.model.changes.Change; import dk.itu.big_red.model.changes.ChangeGroup; import dk.itu.big_red.model.changes.ChangeRejectedException; import dk.itu.big_red.util.DOM; public class ReactionRuleXMLExport extends XMLExport<ReactionRule> { @Override public void exportObject() throws ExportFailedException { setDocument(DOM.createDocument(XMLNS.RULE, "rule:rule")); processRule(getDocumentElement(), getModel()); finish(); } public Element processRule(Element e, ReactionRule rr) throws ExportFailedException { DOM.appendChildIfNotNull(e, processRedex(newElement(XMLNS.RULE, "rule:redex"), rr.getRedex())); try { getModel().getReactum().tryApplyChange( getModel().getChanges().inverse()); } catch (ChangeRejectedException ex) { throw new ExportFailedException(ex); } DOM.appendChildIfNotNull(e, processChanges(newElement(XMLNS.RULE, "rule:changes"), rr.getChanges())); return e; } private Element processRedex(Element e, Bigraph redex) throws ExportFailedException { DOM.applyAttributes(e, "xmlns:bigraph", XMLNS.BIGRAPH); BigraphXMLExport ex = new BigraphXMLExport(); ex.setModel(redex); ex.setDocument(getDocument()); return ex.processBigraph(e, ex.getModel()); } @SuppressWarnings("unchecked") private static <T, V> T ac(V i) { return (T)i; } private static void hurl() throws ExportFailedException { throw new ExportFailedException("Aieee!"); } private Element processChanges(Element e, ChangeGroup changes) throws ExportFailedException { DOM.applyAttributes(e, "xmlns:change", XMLNS.CHANGE); return _processChanges(e, changes); } private Element _processChanges(Element e, ChangeGroup changes) throws ExportFailedException { for (Change i_ : changes) { Element f = null; if (i_ instanceof Colourable.ChangeFillColour || i_ instanceof Colourable.ChangeOutlineColour || i_ instanceof Layoutable.ChangeLayout) { /* do nothing */; } else if (i_ instanceof ChangeGroup) { _processChanges(e, (ChangeGroup)i_); } else if (i_ instanceof Container.ChangeAddChild) { Container.ChangeAddChild i = ac(i_); if (i.child instanceof Root) { f = newElement(XMLNS.CHANGE, "change:add-root"); } else if (i.child instanceof Edge) { f = newElement(XMLNS.CHANGE, "change:add-edge"); } else if (i.child instanceof OuterName) { f = newElement(XMLNS.CHANGE, "change:add-outer-name"); } else if (i.child instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:add-inner-name"); } else if (i.child instanceof Node) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-root"), + "control", ((Node)i.child).getControl().getLongName(), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-node"), + "control", ((Node)i.child).getControl().getLongName(), "parent", i.getCreator().getName()); } else hurl(); } else if (i.child instanceof Site) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-root"), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-node"), "parent", i.getCreator().getName()); } else hurl(); } else hurl(); DOM.applyAttributes(f, "name", i.name); } else if (i_ instanceof Layoutable.ChangeName) { Layoutable.ChangeName i = ac(i_); if (i.getCreator() instanceof Root) { f = newElement(XMLNS.CHANGE, "change:rename-root"); } else if (i.getCreator() instanceof Node) { f = newElement(XMLNS.CHANGE, "change:rename-node"); } else if (i.getCreator() instanceof Site) { f = newElement(XMLNS.CHANGE, "change:rename-site"); } else if (i.getCreator() instanceof Link) { f = newElement(XMLNS.CHANGE, "change:rename-link"); } else if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:rename-inner-name"); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "new-name", i.newName); } else if (i_ instanceof Point.ChangeConnect) { Point.ChangeConnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:connect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:connect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "link", i.link.getName()); } else if (i_ instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:disconnect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:disconnect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName()); } else hurl(); /** * Don't try to do anything with ChangeGroups - their Changes are * individually dealt with. */ if (!(i_ instanceof ChangeGroup)) { DOM.appendChildIfNotNull(e, f); try { getModel().getReactum().tryApplyChange(i_); } catch (ChangeRejectedException ex) { throw new ExportFailedException(ex); } } } return e; } }
false
true
private Element _processChanges(Element e, ChangeGroup changes) throws ExportFailedException { for (Change i_ : changes) { Element f = null; if (i_ instanceof Colourable.ChangeFillColour || i_ instanceof Colourable.ChangeOutlineColour || i_ instanceof Layoutable.ChangeLayout) { /* do nothing */; } else if (i_ instanceof ChangeGroup) { _processChanges(e, (ChangeGroup)i_); } else if (i_ instanceof Container.ChangeAddChild) { Container.ChangeAddChild i = ac(i_); if (i.child instanceof Root) { f = newElement(XMLNS.CHANGE, "change:add-root"); } else if (i.child instanceof Edge) { f = newElement(XMLNS.CHANGE, "change:add-edge"); } else if (i.child instanceof OuterName) { f = newElement(XMLNS.CHANGE, "change:add-outer-name"); } else if (i.child instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:add-inner-name"); } else if (i.child instanceof Node) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-root"), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-node"), "parent", i.getCreator().getName()); } else hurl(); } else if (i.child instanceof Site) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-root"), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-node"), "parent", i.getCreator().getName()); } else hurl(); } else hurl(); DOM.applyAttributes(f, "name", i.name); } else if (i_ instanceof Layoutable.ChangeName) { Layoutable.ChangeName i = ac(i_); if (i.getCreator() instanceof Root) { f = newElement(XMLNS.CHANGE, "change:rename-root"); } else if (i.getCreator() instanceof Node) { f = newElement(XMLNS.CHANGE, "change:rename-node"); } else if (i.getCreator() instanceof Site) { f = newElement(XMLNS.CHANGE, "change:rename-site"); } else if (i.getCreator() instanceof Link) { f = newElement(XMLNS.CHANGE, "change:rename-link"); } else if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:rename-inner-name"); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "new-name", i.newName); } else if (i_ instanceof Point.ChangeConnect) { Point.ChangeConnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:connect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:connect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "link", i.link.getName()); } else if (i_ instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:disconnect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:disconnect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName()); } else hurl(); /** * Don't try to do anything with ChangeGroups - their Changes are * individually dealt with. */ if (!(i_ instanceof ChangeGroup)) { DOM.appendChildIfNotNull(e, f); try { getModel().getReactum().tryApplyChange(i_); } catch (ChangeRejectedException ex) { throw new ExportFailedException(ex); } } } return e; }
private Element _processChanges(Element e, ChangeGroup changes) throws ExportFailedException { for (Change i_ : changes) { Element f = null; if (i_ instanceof Colourable.ChangeFillColour || i_ instanceof Colourable.ChangeOutlineColour || i_ instanceof Layoutable.ChangeLayout) { /* do nothing */; } else if (i_ instanceof ChangeGroup) { _processChanges(e, (ChangeGroup)i_); } else if (i_ instanceof Container.ChangeAddChild) { Container.ChangeAddChild i = ac(i_); if (i.child instanceof Root) { f = newElement(XMLNS.CHANGE, "change:add-root"); } else if (i.child instanceof Edge) { f = newElement(XMLNS.CHANGE, "change:add-edge"); } else if (i.child instanceof OuterName) { f = newElement(XMLNS.CHANGE, "change:add-outer-name"); } else if (i.child instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:add-inner-name"); } else if (i.child instanceof Node) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-root"), "control", ((Node)i.child).getControl().getLongName(), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-node-to-node"), "control", ((Node)i.child).getControl().getLongName(), "parent", i.getCreator().getName()); } else hurl(); } else if (i.child instanceof Site) { if (i.getCreator() instanceof Root) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-root"), "parent", i.getCreator().getName()); } else if (i.getCreator() instanceof Node) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:add-site-to-node"), "parent", i.getCreator().getName()); } else hurl(); } else hurl(); DOM.applyAttributes(f, "name", i.name); } else if (i_ instanceof Layoutable.ChangeName) { Layoutable.ChangeName i = ac(i_); if (i.getCreator() instanceof Root) { f = newElement(XMLNS.CHANGE, "change:rename-root"); } else if (i.getCreator() instanceof Node) { f = newElement(XMLNS.CHANGE, "change:rename-node"); } else if (i.getCreator() instanceof Site) { f = newElement(XMLNS.CHANGE, "change:rename-site"); } else if (i.getCreator() instanceof Link) { f = newElement(XMLNS.CHANGE, "change:rename-link"); } else if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:rename-inner-name"); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "new-name", i.newName); } else if (i_ instanceof Point.ChangeConnect) { Point.ChangeConnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:connect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:connect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName(), "link", i.link.getName()); } else if (i_ instanceof Point.ChangeDisconnect) { Point.ChangeDisconnect i = ac(i_); if (i.getCreator() instanceof InnerName) { f = newElement(XMLNS.CHANGE, "change:disconnect-inner-name"); } else if (i.getCreator() instanceof Port) { f = DOM.applyAttributes( newElement(XMLNS.CHANGE, "change:disconnect-port"), "node", i.getCreator().getParent().getName()); } else hurl(); DOM.applyAttributes(f, "name", i.getCreator().getName()); } else hurl(); /** * Don't try to do anything with ChangeGroups - their Changes are * individually dealt with. */ if (!(i_ instanceof ChangeGroup)) { DOM.appendChildIfNotNull(e, f); try { getModel().getReactum().tryApplyChange(i_); } catch (ChangeRejectedException ex) { throw new ExportFailedException(ex); } } } return e; }
diff --git a/projects/samskivert/src/java/com/samskivert/xml/SetNextFieldRule.java b/projects/samskivert/src/java/com/samskivert/xml/SetNextFieldRule.java index f013e64a..37560a35 100644 --- a/projects/samskivert/src/java/com/samskivert/xml/SetNextFieldRule.java +++ b/projects/samskivert/src/java/com/samskivert/xml/SetNextFieldRule.java @@ -1,73 +1,73 @@ // // $Id: SetNextFieldRule.java,v 1.3 2004/02/25 13:16:32 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2001 Walter Korman // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.xml; import java.lang.reflect.Field; import org.apache.commons.digester.Rule; /** * Like the <code>SetNextRule</code> except that the object on the top of * the stack is placed into a field of the penultimate object. */ public class SetNextFieldRule extends Rule { /** * Constructs a set field rule for the specified field. */ public SetNextFieldRule (String fieldName) { // keep this for later _fieldName = fieldName; } public void end (String namespace, String name) throws Exception { // identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); Class pclass = parent.getClass(); if (digester.getLogger().isDebugEnabled()) { - digester.getLogger().debug("Set " + pclass.getName() + "." + _fieldName + - " = " + child); + digester.getLogger().debug("Set " + pclass.getName() + "." + + _fieldName + " = " + child); } // stuff the child object into the field of the parent Field field = pclass.getField(_fieldName); field.set(parent, child); } /** * Render a printable version of this rule. */ public String toString () { StringBuffer sb = new StringBuffer("SetNextFieldRule["); sb.append("fieldName="); sb.append(_fieldName); sb.append("]"); return (sb.toString()); } protected String _fieldName; }
true
true
public void end (String namespace, String name) throws Exception { // identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); Class pclass = parent.getClass(); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug("Set " + pclass.getName() + "." + _fieldName + " = " + child); } // stuff the child object into the field of the parent Field field = pclass.getField(_fieldName); field.set(parent, child); }
public void end (String namespace, String name) throws Exception { // identify the objects to be used Object child = digester.peek(0); Object parent = digester.peek(1); Class pclass = parent.getClass(); if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug("Set " + pclass.getName() + "." + _fieldName + " = " + child); } // stuff the child object into the field of the parent Field field = pclass.getField(_fieldName); field.set(parent, child); }
diff --git a/src/core/src/main/java/org/geogit/repository/RepositoryConnectionException.java b/src/core/src/main/java/org/geogit/repository/RepositoryConnectionException.java index 720c12bf..534bf3ad 100644 --- a/src/core/src/main/java/org/geogit/repository/RepositoryConnectionException.java +++ b/src/core/src/main/java/org/geogit/repository/RepositoryConnectionException.java @@ -1,59 +1,59 @@ /* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.repository; import org.geogit.storage.ConfigDatabase; import com.google.common.base.Optional; public class RepositoryConnectionException extends RuntimeException { public RepositoryConnectionException(String message) { super(message); } public static enum StorageType { GRAPH("graph"), OBJECT("objects"), REF("refs"), STAGING("staging"); private StorageType(String key) { this.key = key; } public final String key; public void configure(ConfigDatabase configDB, String formatName, String version) { Optional<String> storageName = configDB.get("storage." + key); Optional<String> storageVersion = configDB.get(formatName + ".version"); if (storageName.isPresent()) { throw new RepositoryConnectionException("Initializing already " + "initialized graph database"); } if (storageVersion.isPresent() && !version.equals(storageVersion.get())) { throw new RepositoryConnectionException("Initializing already " + "initialized graph database"); } configDB.put("storage." + key, formatName); configDB.put(formatName + ".version", version); } public void verify(ConfigDatabase configDB, String formatName, String version) { Optional<String> storageName = configDB.get("storage." + key); Optional<String> storageVersion = configDB.get(formatName + ".version"); boolean unset = !(storageName.isPresent() || storageVersion.isPresent()); boolean valid = - storageName.isPresent() && key.equals(storageName.get()) && + storageName.isPresent() && formatName.equals(storageName.get()) && storageVersion.isPresent() && version.equals(storageVersion.get()); if (!(unset || valid)) { throw new RepositoryConnectionException( - "Cannot open " + key + "database with format: " + key + " and version: " + version + ", found format: " + "Cannot open " + key + " database with format: " + formatName + " and version: " + version + ", found format: " + storageName.orNull() + ", version: " + storageVersion.orNull()); } } } }
false
true
public void verify(ConfigDatabase configDB, String formatName, String version) { Optional<String> storageName = configDB.get("storage." + key); Optional<String> storageVersion = configDB.get(formatName + ".version"); boolean unset = !(storageName.isPresent() || storageVersion.isPresent()); boolean valid = storageName.isPresent() && key.equals(storageName.get()) && storageVersion.isPresent() && version.equals(storageVersion.get()); if (!(unset || valid)) { throw new RepositoryConnectionException( "Cannot open " + key + "database with format: " + key + " and version: " + version + ", found format: " + storageName.orNull() + ", version: " + storageVersion.orNull()); } }
public void verify(ConfigDatabase configDB, String formatName, String version) { Optional<String> storageName = configDB.get("storage." + key); Optional<String> storageVersion = configDB.get(formatName + ".version"); boolean unset = !(storageName.isPresent() || storageVersion.isPresent()); boolean valid = storageName.isPresent() && formatName.equals(storageName.get()) && storageVersion.isPresent() && version.equals(storageVersion.get()); if (!(unset || valid)) { throw new RepositoryConnectionException( "Cannot open " + key + " database with format: " + formatName + " and version: " + version + ", found format: " + storageName.orNull() + ", version: " + storageVersion.orNull()); } }
diff --git a/com/ggvaidya/TaxonDNA/DNA/formats/TNTFile.java b/com/ggvaidya/TaxonDNA/DNA/formats/TNTFile.java index 0e47fc8..18b6c21 100644 --- a/com/ggvaidya/TaxonDNA/DNA/formats/TNTFile.java +++ b/com/ggvaidya/TaxonDNA/DNA/formats/TNTFile.java @@ -1,1220 +1,1220 @@ /** * TNTFile allows you to read and write TNT files. I'm going to be * guesstimating the format from, of all things, my own TNT exporter. * I'm also going to be using TNT's own (fairly limited) * documentation. * * This module really is pretty messed up, since I made the insanely * great design decision of writing the square-bracket-handling code * in here (thereby practically inverting an entire function) instead * of just rewriting Sequence to handle it. Stupid, stupid, stupid, * and a great example of why I shouldn't code when sleepy or * writer's-blocked. * * TODO: Okay, 'nstates 32' will work out well enough, BUT all * bases will then have to be converted into fully written out * format (which, as an interesting aside, converts it into * BaseSequence ...), i.e. W to [AC] or whatever. Then, everything * will be Just Fine. */ /* TaxonDNA Copyright (C) 2006-07, 2010 Gaurav Vaidya This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.ggvaidya.TaxonDNA.DNA.formats; import java.io.*; import java.util.*; import com.ggvaidya.TaxonDNA.Common.*; import com.ggvaidya.TaxonDNA.DNA.*; public class TNTFile extends BaseFormatHandler { public static final int MAX_TAXON_LENGTH = 31; // TNT truncates at 32 characters, but it gives a warning at 32 // I don't like warnings private static final int INTERLEAVE_AT = 80; // default interleave length // group constants private static final int GROUP_CHARSET = 1; private static final int GROUP_TAXONSET = 2; /** Returns the extension. We'll go with '.fas' as our semi-official DOS-compat extension */ public String getExtension() { return "tnt"; } /** * Returns a valid OTU (Operation Taxonomic Unit); that is, a taxon name. */ public String getTNTName(String name) { // Rule #1: the name must start with '[A-Za-z0-9\-\+\.]' char first = name.charAt(0); if( (first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z') || (first >= '0' && first <= '9') || (first == '_') ) { // it's all good! } else { name = "_" + name; } // Rule #2: strange characters we'll turn into '_' name = name.replaceAll("[^a-zA-Z0-9\\-\\+\\.\\_\\*\\:\\(\\)\\|\\\\\\/]", "_"); // Rule #3: spaces we'll turn into '_' name = name.replace(' ', '_'); // Rule #4: truncate to 'len' return name; } /** * Returns the short name of this file format. */ public String getShortName() { return "TNT"; } /** * Returns the full name of this file format handler. E.g. "Nexus file format v2 and below". * You ought to put in something about what versions of the software you support. * But not too long: think about whether you could display it in a list. */ public String getFullName() { return "TNT/Hennig86 support"; } /** * Read this file into the specified SequenceList. This will read all the files straight into * this sequence list, in the correct order. * * @throws IOException if there was an error doing I/O * @throws SequenceException if a Sequence is malformed - incorrect bases, etc. * @throws FormatException if there was an error in the format of the file. * @throws DelayAbortedException if the DelayCallback was aborted by the user. */ public SequenceList readFile(File file, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { SequenceList sl = new SequenceList(); sl.lock(); // retarded. appendFromFile(sl, file, delay); sl.unlock(); return sl; } /** * Append this file to the specified SequenceList. This will read in all the sequences from * the file and append them directly onto the end of this SequenceList. * * @throws IOException if there was an error doing I/O * @throws SequenceException if a Sequence is malformed - incorrect bases, etc. * @throws FormatException if there was an error in the format of the file. * @throws DelayAbortedException if the DelayCallback was aborted by the user. */ public void appendFromFile(SequenceList appendTo, File fileFrom, DelayCallback delay) throws IOException, SequenceException, FormatException, DelayAbortedException { FormatHandlerEvent evt = new FormatHandlerEvent(fileFrom, this, appendTo); // set up the delay if(delay != null) delay.begin(); appendTo.lock(); try { BufferedReader reader = new BufferedReader(new FileReader(fileFrom)); // count lines int count_lines = 0; int count_data = 0; long file_length = fileFrom.length(); while(reader.ready()) { if(delay != null) delay.delay((int)((float)count_data/file_length * 100), 1000); // note that we're really going from 0% to 10%. This will // make the user less confused when we jump from 10% to 0% and // start over. count_data += reader.readLine().length(); count_lines++; } // let's go! reader = new BufferedReader(new FileReader(fileFrom)); StreamTokenizer tok = new StreamTokenizer(reader); // okay, here's how it's going to work: // 1. we will ONLY handle xread for now. i.e. NO other commands will be // processed at ALL. If we see any other command, we will just quietly // wait for the terminating semicolon. // 2. well, okay - we will also handle nstates. But only to check for // 'nstates dna'. Anything else, and we barf with extreme prejudice. // 3. we will also handled comments 'perfectly' ... err, assuming that // anything in single quotes is a comment. Which we can't really // assume. Ah well. // 4. A LOT of the naming rules are just being imported in en toto from // NEXUS. This is probably a stupid idea, but I hate giving up on the // rigid flexibility they allowed. If any of these rules do NOT work // in TNT, lemme know. tok.ordinaryChar('/'); // this is the default StringTokenizer comment char, so we need to set it back to nothingness tok.wordChars('@', '@'); // this is a special command we look out for in the title // turn off parseNumbers() tok.ordinaryChar('.'); tok.ordinaryChar('-'); tok.ordinaryChars('0','9'); tok.wordChars('.','.'); tok.wordChars('-','-'); tok.wordChars('0','9'); tok.wordChars('|','|'); // this is officially allowed in Nexus, and pretty convenient for us tok.wordChars('_', '_'); // we need to replace this manually. they form one 'word' in NEXUS. tok.ordinaryChar('\''); // We need this to be an 'ordinary' so that we can use it to discriminate comments tok.ordinaryChar(';'); // We need this to be an 'ordinary' so that we can use it to distinguish commands // states int commentLevel = 0; boolean newCommand = true; // WARNING: newCommand is reset at the BOTTOM of the while loop // Only use 'continue' if you've slurped up an ENTIRE // command (including the ';') while(true) { /* Before anything else, do the delay */ if(delay != null) delay.delay(tok.lineno(), count_lines); /* Now ... to business! */ int type = tok.nextToken(); // break at end of file if(type == StreamTokenizer.TT_EOF) break; // is it a comment? if(type == '\'') { if(commentLevel == 0) commentLevel = 1; else commentLevel = 0; continue; } // if we're in a comment, skip normal stuff if(commentLevel > 0) continue; // semi-colons indicate end of line. // some commands use this to determine the end of command if(type == ';') { newCommand = true; continue; } // Words in here are guaranteed to be a 'command' if(newCommand && type == StreamTokenizer.TT_WORD) { String str = tok.sval; // nstates {we only understand 'nstates tnt'} if(str.equalsIgnoreCase("nstates")) { int token = tok.nextToken(); if( (token == StreamTokenizer.TT_WORD) && (tok.sval.equalsIgnoreCase("dna")) ) { // nstates dna! we can handle this ... } else { // well, okay we can baseSequence it, UNLESS: if(tok.sval.equalsIgnoreCase("cont")) throw formatException(tok, "This program can currently only load files which contain discrete sequences. This file does not (it contains continuous data, as indicated by 'nstates " + tok.sval + "')."); } } // xread {okay, we need to actually read the matrix itself} else if(str.equalsIgnoreCase("xread")) { xreadBlock(appendTo, tok, evt, delay, count_lines); newCommand = true; continue; } // xgroup/agroup // {xgroup: character sets} // {agroup: taxonsets} // since the format is essentially identical, we'll use the // same function to handle them else if(str.equalsIgnoreCase("xgroup")) { groupCommand(GROUP_CHARSET, appendTo, tok, evt, delay, count_lines); newCommand = true; continue; } else if(str.equalsIgnoreCase("agroup")) { groupCommand(GROUP_TAXONSET, appendTo, tok, evt, delay, count_lines); newCommand = true; continue; } else { // okay, we're 'in' a command // but thanks to newCommand, we can just ignore // all the crap; the program will just loop // around until it sees the ';', newCommand // is activated, and we look for the next // block. } } else { // strange symbol (or ';') found // since we're probably in a 'strange' block, we can just // ignore this. } newCommand = false; // this will be reset at the end of the line -- i.e, by ';' } } finally { if(delay != null) delay.end(); appendTo.unlock(); } appendTo.setFile(fileFrom); appendTo.setFormatHandler(this); } public FormatException formatException(StreamTokenizer tok, String message) { return new FormatException("Error on line " + tok.lineno() + ": " + message); } /** * Parses an 'xread' command. This is going to be a pretty simple interpretation, all * things considered: we'll ignore amperstands, * and we'll barf quickly and early if we think we're going in over our head. Pretty * much, we are just targeting trying to be able to open files we spit out. Can't be * _that_ hard, can it? * * Implementation note: the string '[]' in the sequence will be converted into a single '-' */ public void xreadBlock(SequenceList appendTo, StreamTokenizer tok, FormatHandlerEvent evt, DelayCallback delay, int count_lines) throws FormatException, DelayAbortedException, IOException { Interleaver interleaver = new Interleaver(); int seq_names_count = 0; int begin_at = tok.lineno(); // which line did this xreadBlock start at char missingChar = '?'; char gapChar = '-'; // there is no standard definition of which characters // TNT uses for these, nor can I figure out how to // determine these values. So I'm just going with our // own defaults, to be tweaked as required. tok.wordChars(gapChar,gapChar); tok.wordChars(missingChar,missingChar); tok.wordChars('[', '['); // for [ACTG] -> N type stuff tok.wordChars(']', ']'); Hashtable hash_names = new Hashtable(); // String name -> Sequence String name = null; // '.', '(' and ')' should be read as part of sequence names. tok.wordChars('.', '.'); tok.wordChars('(', ')'); tok.wordChars(')', ')'); // okay, 'xread' has started. if(tok.ttype == StreamTokenizer.TT_WORD && tok.sval.equalsIgnoreCase("xread")) ; // we've already got xread on the stream, do nothing else tok.nextToken(); // this token IS 'xread' // now, move on to the token after 'xread' tok.nextToken(); // first, we get the title StringBuffer title = null; if(tok.ttype == '\'') { title = new StringBuffer(); while(true) { if(delay != null) delay.delay(tok.lineno(), count_lines); int type = tok.nextToken(); if(type == '\'') break; // comment commands (our hacks, basically) if(type == StreamTokenizer.TT_WORD) { if(tok.sval.length() > 0 && tok.sval.charAt(0) == '@') { // special command! if(tok.sval.equalsIgnoreCase("@xgroup")) { groupCommand(GROUP_CHARSET, appendTo, tok, evt, delay, count_lines); } else if(tok.sval.equalsIgnoreCase("@agroup")) { groupCommand(GROUP_TAXONSET, appendTo, tok, evt, delay, count_lines); } else { // oops ... not a command! (that we recognize, anyway) } } else { title.append(tok.sval); } } else title.append(type); if(type == StreamTokenizer.TT_EOF) throw formatException(tok, "The title doesn't seem to have been closed properly. Are you sure the final quote character is present?"); } } else { // err, no title? tok.pushBack(); } // finished (or, err, not) the (optional) title // but we NEED two numbers now // number of characters int nChars = 0; tok.nextToken(); if(tok.ttype != StreamTokenizer.TT_WORD) throw formatException(tok, "Couldn't find the number of characters. I found '" + (char)tok.ttype + "' instead!"); try { nChars = Integer.parseInt(tok.sval); } catch(NumberFormatException e) { throw formatException(tok, "Couldn't convert this file's character count (which is \"" + tok.sval + "\") into a number. Are you sure it's really a number?"); } // number of taxa int nTax = 0; tok.nextToken(); if(tok.ttype != StreamTokenizer.TT_WORD) throw formatException(tok, "Couldn't find the number of taxa. I found '" + (char)tok.ttype + "' instead!"); try { nTax = Integer.parseInt(tok.sval); } catch(NumberFormatException e) { throw formatException(tok, "Couldn't convert this file's taxon count (which is \"" + tok.sval + "\") into a number. Are you sure it's really a number?"); } // okay, all done ... sigh. // now we can fingally go into the big loop // In the big loop, '.'s are part of th string. tok.wordChars('.', '.'); int lineno = tok.lineno(); while(true) { int type = tok.nextToken(); if(delay != null) delay.delay(lineno, count_lines); if(type == StreamTokenizer.TT_EOF) { // wtf?! throw formatException(tok, "I've reached the end of the file, but the 'xread' beginning at line " + begin_at + " was never terminated."); } if(type == ';') // it's over. Go back home, etc. break; // okay, i'm commenting out this comment handling // code IN CASE it's ever needed again. /* if(type == '[' || type == ']') { if(type == '[') commentLevel++; if(type == ']') commentLevel--; continue; } if(commentLevel > 0) continue; */ if(type == StreamTokenizer.TT_WORD) { // word! String word = tok.sval; // now, there are some 'special' // words: specifically, [dna], [num] // [prot] and [cont]. We just // ignore those: the BaseSequence // system will figure its own // thing out eventually. if( word.equalsIgnoreCase("[dna]") || word.equalsIgnoreCase("[prot]") || word.equalsIgnoreCase("[num]") ) { // ignore! continue; } if(word.equalsIgnoreCase("[cont]")) { throw formatException(tok, "This program can currently only load files which contain discrete sequences. This file does not (it contains continuous data, as indicated by '[cont]')."); } if(word.matches("^\\[.*\\]$")) { throw formatException(tok, "Unrecognized data type: " + word); } // get the sequence name String seq_name = new String(word); // otherwise, technically, both word and seq // would point to tok.sval. seq_name = seq_name.replace('_', ' '); // get the sequence itself int tmp_type = tok.nextToken(); if(tmp_type != StreamTokenizer.TT_WORD) { throw formatException(tok, "I recognize sequence name '" + seq_name + "', but instead of the sequence, I find '" + (char)tok.ttype + "'. What's going on?"); } String sequence = tok.sval; seq_names_count++; // add the sequence to the interleaver try { interleaver.appendSequence(seq_name, sequence); } catch(SequenceException e) { throw formatException(tok, "Sequence '" + name + "' contains invalid characters. The exact error encountered was: " + e); } } else if(type == '&') { // indicates TNT interleaving // ignore! } else { throw formatException(tok, "I found '" + (char)type + "' rather unexpectedly in the xread block! Are you sure it's supposed to be here?"); } } // Okay, done with this. Back to ordinaryChar with you! tok.ordinaryChar('.'); // now, let's 'unwind' the interleaver and // check that the numbers we get match up with // the numbers specified in the file itself. Iterator i = interleaver.getSequenceNamesIterator(); int count = 0; while(i.hasNext()) { if(delay != null) delay.delay(count, seq_names_count); count++; String seqName = (String) i.next(); Sequence seq = interleaver.getSequence(seqName); if(seq.getLength() != nChars) { throw new FormatException("The number of characters specified in the file (" + nChars + ") do not match with the number of characters is sequence '" + seqName + "' (" + seq.getLength() + ")."); } appendTo.add(seq); } if(count != nTax) throw new FormatException("The number of sequences specified in the file (" + nTax + ") does not match the number of sequences present in the file (" + count + ")."); // only important in the xread section tok.ordinaryChar(gapChar); tok.ordinaryChar(missingChar); tok.ordinaryChar('.'); tok.ordinaryChar('('); tok.ordinaryChar(')'); } int last_group_id_used = 10000; /** * Parses a 'group' command. Group commands are relatively easy to work with; they go like this: * (=\d+ (\(\w+\))* (\d+)*)* * ^ ^ ^ * | | \---------- one or more char/taxon numbers * | \------------------- the name of this group (if any) * \-------------------------- the number of this group (not important to us, except that /=\d+/ * indicates a new taxongroup starting * In this function, I'll use ?group or _group to indicate, err, well, /[ax]group/. */ public void groupCommand(int which_group, SequenceList appendTo, StreamTokenizer tok, FormatHandlerEvent evt, DelayCallback delay, int count_lines) throws FormatException, DelayAbortedException, IOException { int begin_at = tok.lineno(); // which line did this group start at String current_command_name = ""; if(which_group == GROUP_CHARSET) current_command_name = "xgroup"; else current_command_name = "agroup"; System.err.println("Beginning: " + current_command_name); // okay, we're assuming that '?group' has already started. // since fullstops can be used in ranges, we NEED them to be wordChars, // so that they turn up as a word (i.e., '23.26' is returned as '23.26', // not '23' '.' '26') tok.wordChars('.', '.'); // brackets are word chars in xread. We need them to be non-word chars // here. tok.ordinaryChar('('); tok.ordinaryChar(')'); // okay, we pop into the loop. we're looking for: // ';' -> exit // '=' -> start new group (slurp group id) // '(' -> set title for last group (slurp until terminating ')') // word -> ought to be either: // \d+ -> one single unit to be added to the group // \d+\.\d+ -> a range to be added. note that some programs // like spewing ranges out as consecutive numbers. // we ought to track this, watch for a line, and // then ... oh, never MIND. // // this effectively means that you can pull crazy shit like: // xgroup (ha ha!) =1 34.24 (this is weird, innit?) 13 54 (multiple titles wtf?) 24.52 =2 13 // and so on. But hey, well formed files will work just fine. // Hashtable hash_group_ids = new Hashtable(); // String id -> Sequence String currentName = ""; int sequence_begin = -1; int sequence_end = -1; while(true) { int type = tok.nextToken(); if(delay != null) delay.delay(tok.lineno(), count_lines); if(type == StreamTokenizer.TT_EOF) { // wtf?! throw formatException(tok, "I've reached the end of the file, but the '" + current_command_name + "' beginning at line " + begin_at + " was never terminated."); } if(type == ';') // it's over. Go back home, etc. break; if(type == '=') { // we've got a new sequence // BUT, first, we need to ensure that the last sequence is terminated // fire the last if(sequence_begin == -1 || sequence_end == -1) { // no sequences have begun yet. booyah. } else { if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multi-character sequence [2]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, the next token ought to be a unique group id String group_id; if(tok.nextToken() != StreamTokenizer.TT_WORD) { tok.pushBack(); // throw formatException(tok, "Expecting the group id, but found '" + (char)tok.ttype + "' instead!"); group_id = new Integer(++last_group_id_used).toString(); } else { group_id = tok.sval; } if(hash_group_ids.get(group_id) != null) throw formatException(tok, "Duplicate group id '" + group_id + "' found!"); // okay, set the new group id! hash_group_ids.put(group_id, new Integer(0)); currentName = "Group #" + group_id; continue; } else if(type == '(') { // okay, now we basically read until the closing ')' // and store it in currentName StringBuffer buff_name = new StringBuffer(); int title_began = tok.lineno(); while(tok.nextToken() != ')') { if(delay != null) delay.delay(tok.lineno(), count_lines); if(tok.ttype == StreamTokenizer.TT_EOF) throw formatException(tok, "The title which began in " + current_command_name + " on line " + title_began + " is not terminated! (I can't find the ')' which would end it)."); else if(tok.ttype == StreamTokenizer.TT_WORD) buff_name.append(tok.sval); else buff_name.append((char) tok.ttype); } currentName = buff_name.toString(); // But wait! Some names are extra-special. // Note that we discard the charset name // at this point: any positional data is // collected together and used while // resplitting the entire file. String originalName = currentName; - if (currentName.matches("^.*_posN$")) { + if (currentName.matches("^.*_posN$") || currentName.equals("posN")) { currentName = ":0"; } - if (currentName.matches("^.*_pos1$")) { + if (currentName.matches("^.*_pos1$") || currentName.equals("pos1")) { currentName = ":1"; } - if (currentName.matches("^.*_pos2$")) { + if (currentName.matches("^.*_pos2$") || currentName.equals("pos2")) { currentName = ":2"; } - if (currentName.matches("^.*_pos3$")) { + if (currentName.matches("^.*_pos3$") || currentName.equals("pos3")) { currentName = ":3"; } // System.err.println("Converted '" + originalName + "' -> '" + currentName + "'"); // Now the rest of this method will keep // adding these positions into the special // codonsets. HAHA BRILLIANT. continue; } else if(type == StreamTokenizer.TT_WORD) { // word! String word = tok.sval; // now, this is either: // 1. \d+ -> a number! submit straightaway, get on with life // 2. \d+. -> a range, from number to LENGTH_OF_SET. submit, etc. // 3. .\d+ -> a range, from 0 to number. submit, etc. // 4. \d+.\d+ -> a range, from num1 to num2. submit, etc. // // the trick is figuring out which one is which. // if(word.indexOf('.') == -1) { // We've got a single number. int locus = atoi(word, tok); if(sequence_begin == -1) { sequence_begin = locus; } if(sequence_end == -1 || sequence_end == locus - 1) { // if sequence_end is pointing at the LAST locus, sequence_end = locus; // move it to the current position // the sequence continues, so we do NOT fire now } else { // the sequence ends here! // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= (sequence_end + 1); d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [6]: " + currentName + " from " + d + " to " + d); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1)); //System.err.println("New multicharacter sequence [3]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = locus; sequence_end = locus; } continue; } else { // okay, there's a fullstop here ... // sigh. // // you have to wonder why you bother, sometimes. // one question: do we have an unfired sequence? // if we do, fire it first! // fire the last if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [1]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, now we can fire this next bugger int from = 0; int to = 0; if(word.charAt(0) == '.') { // it's a '.\d+' or a '.' if(word.length() == 1) { // it's a '.' from = 0; to = appendTo.getMaxLength(); } else { // it's a '.\d+' from = 0; to = atoi(word.substring(1), tok); } } else if(word.charAt(word.length() - 1) == '.') { // it's at the end from = atoi(word.substring(0, word.length() - 1), tok); to = appendTo.getMaxLength(); } else { // it's in the middle int indexOf = word.indexOf('.'); from = atoi(word.substring(0, indexOf - 1), tok); to = atoi(word.substring(indexOf + 1), tok); } if(which_group == GROUP_CHARSET) { from++; // convert from TNT loci (0-based) to normal loci (1-based) to++; // Multi-character blocks are POISON for situations where // the sequences are supposed to move in thirds (i.e. ':1', // ':2' and ':3'. This is because the algorithm for figuring // out position information is designed to work with fireEvent(evt.makeCharacterSetFoundEvent( currentName, from, to)); //System.err.println("New multi-character block [4]: " + currentName + " from " + from + " to " + to); } continue; } } else { throw formatException(tok, "I found '" + (char)type + "' rather unexpectedly in the " + current_command_name + " command beginning on line " + begin_at + "! Are you sure it's supposed to be here?"); } } // do we have an incomplete sequence? if(sequence_begin != -1 && sequence_end != -1) { // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= sequence_end + 1; d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [7]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [5]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } } // Restore '.' to its usual position as a character. tok.ordinaryChar('.'); // Restore brackets to their magical significance in the xread. tok.wordChars('(', ')'); tok.wordChars(')', ')'); } private int atoi(String word, StreamTokenizer tok) throws FormatException { try { return Integer.parseInt(word); } catch(NumberFormatException e) { throw formatException(tok, "Could not convert word '" + word + "' to a number: " + e); } } /** * Writes the content of this sequence list into a file. The file is * overwritten. The order of the sequences written into the file is * guaranteed to be the same as in the list. * * @throws IOException if there was a problem creating/writing to the file. * @throws DelayAbortedException if the DelayCallback was aborted by the user. */ public void writeFile(File file, SequenceList set, DelayCallback delay) throws IOException, DelayAbortedException { writeTNTFile(file, set, 0, "", delay); } /** * A species TNTFile-only method to have a bit more control over how * the Nexus file gets written. * * @param interleaveAt Specifies where you want to interleave. Note that TNTFile.INTERLEAVE_AT will be entirely ignored here, and that if the sequence is less than interleaveAt, it will not be interleaved at all. '-1' turns off all interleaving (flatline), although you can obviously use a huge value (999999) to get basically the same thing. * @param otherBlocks We put this into the file at the very bottom. It should be one or more proper 'BLOCK's, unless you really know what you're doing. */ public void writeTNTFile(File file, SequenceList set, int interleaveAt, String otherBlocks, DelayCallback delay) throws IOException, DelayAbortedException { boolean interleaved = false; if(interleaveAt > 0 && interleaveAt < set.getMaxLength()) interleaved = true; set.lock(); // it has begun ... if(delay != null) delay.begin(); // write out a 'preamble' PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); writer.println("nstates 32;"); // give our data the best possible chance writer.println("xread"); // begin sequence output writer.println("'Written by TaxonDNA " + Versions.getTaxonDNA() + " on " + new Date() + "'"); // commented string // write the maxlength/sequence count writer.println(set.getMaxLength() + " " + set.count()); writer.println(""); // leave a blank line for the prettyness /* * The following piece of code has to: * 1. Figure out VALID, UNIQUE names to output. * 2. Without hitting up against PAUP* and MacClade's specs (we'll * assume 32 chars for now - see MAX_TAXON_LENGTH - and work * around things when we need to). * * Interleaving will be handled later. */ Hashtable names = new Hashtable(); // Hashtable(Strings) -> Sequence // hash of all the names currently in use Vector vec_names = new Vector(); // Vector(String) Iterator i = set.iterator(); while(i.hasNext()) { Sequence seq = (Sequence) i.next(); String name = getTNTName(seq.getFullName()); //seq.getFullName(MAX_TAXON_LENGTH), MAX_TAXON_LENGTH); // TODO: This is a bad idea when we're generating custom // sets or whatever. In SequenceMatrix, though, this is // perfectly fine. name = name.replace(' ', '_'); // we do NOT support ' '. Pfft. /* int no = 2; while(names.get(name) != null) { int digits = 5; if(no > 0 && no < 10) digits = 1; if(no >= 10 && no < 100) digits = 2; if(no >= 100 && no < 1000) digits = 3; if(no >= 1000 && no < 10000) digits = 4; name = getTNTName(seq.getFullName(MAX_TAXON_LENGTH - digits - 1), MAX_TAXON_LENGTH - digits - 1); name = name.replace(' ', '_'); // we do NOT support '. Pfft. name += "_" + no; no++; if(no == 10000) { // this has gone on long enough! throw new IOException("There are 9999 sequences named '" + seq.getFullName(MAX_TAXON_LENGTH) + "', which is the most I can handle. Sorry. This is an arbitary limit: please let us know if you think we set it too low."); } } */ //System.err.println("In TNTFile export: replaced '" + seq.getFullName() + "' with '" + name + "'"); names.put(name, seq); vec_names.add(name); } if(!interleaved) { Iterator i_names = vec_names.iterator(); int x = 0; while(i_names.hasNext()) { // report the delay if(delay != null) { try { delay.delay(x, vec_names.size()); } catch(DelayAbortedException e) { writer.close(); set.unlock(); throw e; } } String name = (String) i_names.next(); Sequence seq = (Sequence) names.get(name); writer.println(name + " " + seq.getSequence()); x++; } } else { // go over all the 'segments' for(int x = 0; x < set.getMaxLength(); x+= interleaveAt) { Iterator i_names = vec_names.iterator(); // report the delay if(delay != null) try { delay.delay(x, set.getMaxLength()); } catch(DelayAbortedException e) { writer.close(); set.unlock(); throw e; } // before each segment, we *ought* to enter the type of the next 'chunk'. // as far as i know, we have four 'options': // 1. [cont]inous: nope. // 2. [pro]tein: we can't distinguish this now, anyway. // 3. [dna]: yes, if it's class is Sequence // 4. [num]: err, maybe, if it's class is BaseSequence. // // // With nstates=32, we can use upto 32 states: 0-9 and A-V. // So we should probably check for W,X,Y,Z, and produce an // error. // TODO writer.println("&"); // the TNT standard (ha!) requires an '&' in between blocks. // go over all the taxa while(i_names.hasNext()) { String name = (String) i_names.next(); Sequence seq = (Sequence) names.get(name); Sequence subseq = null; int until = 0; try { until = x + interleaveAt; // thanks to the loop, we *will* walk off the end of this if(until > seq.getLength()) { until = seq.getLength(); } subseq = seq.getSubsequence(x + 1, until); } catch(SequenceException e) { delay.end(); throw new IOException("Could not get subsequence (" + (x + 1) + ", " + until + ") from sequence " + seq + ". This is most likely a programming error."); } if( subseq.getSequence().indexOf('Z') != -1 || subseq.getSequence().indexOf('z') != -1 ) delay.addWarning("Sequence '" + subseq.getFullName() + "' contains the letter 'Z'. This letter might not work in TNT."); writer.println(name + " " + subseq.getSequence()); } //writer.println("&"); // the TNT standard (ha!) requires an '&' in between blocks. } } writer.println(";"); // the semicolon ends the 'xread' command. // Put in the CODONPOSSETs, off by themselves. // This may conflict with otherBlocks, but ... hopefully, not. // Time to do character sets! // Here's the thing: each sequence has its own positional // information, which (we assume) is consistent within a // column (which is a pretty safe assumption from now, // as we only accept positional data from Nexus and TNT, // neither of which support per-sequence positional data). // Unfortunately, we'd like to produce only a single set // of positional data for the entire dataset. To simplify // things, we create three strings, gradually build them // up, and then combine them at the end. // Note (this being an important point): we only use the // FIRST taxon in the table to determine CODONPOSSET // information to be emitted. // This is very likely indeed to work! StringBuffer[] array_strbuff_positions = new StringBuffer[4]; array_strbuff_positions[0] = new StringBuffer(); array_strbuff_positions[1] = new StringBuffer(); array_strbuff_positions[2] = new StringBuffer(); array_strbuff_positions[3] = new StringBuffer(); Iterator iter = set.iterator(); while(iter.hasNext()) { // get the first sequence Sequence seq = (Sequence) iter.next(); // Note: if you change this x = 0, you'll get 'N' as // well. Since we don't want this right now, we're // turning it off. Turn it on whenever. for(int x = 1; x <= 3; x++) { Vector v = (Vector) seq.getProperty("position_" + x); if(v != null) { Iterator i_v = v.iterator(); while(i_v.hasNext()) { FromToPair ftp = (FromToPair) i_v.next(); // buff_nexus_positions.append("[" + horzOffset + "] (" + ftp.from + ") - (" + ftp.to + ")" + str_end); int increment_by = 1; if(x == 1 || x == 2 || x == 3) increment_by = 3; // Note those -1s! They're to change our 1-index based calculations // into 0-based TNT coordinates. if(ftp.from == ftp.to) { array_strbuff_positions[x].append( (ftp.from - 1) + " " ); } else { // Iterate, iterate. for(int y = (ftp.from); y <= (ftp.to); y += increment_by) { array_strbuff_positions[x].append((y-1) + " "); } } } } } } // Let's see if we can't calculate the nexus positions. StringBuffer buff_tnt_positions = new StringBuffer(); // buff_tnt_positions.append("'*** The following is positional information for this dataset. ***\n"); buff_tnt_positions.append("xgroup\n"); // Change zero-length strings to null. for(int x = 0; x <= 3; x++) { if(array_strbuff_positions[x].length() == 0) array_strbuff_positions[x] = null; } String position_names[] = { "N", "1", "2", "3" }; boolean flag_display_tnt_positions = false; // Store the positional information into the first three xgroups. // Then let everything else fall below them. int colid = 0; for(int x = 1; x <= 3; x++) { if(array_strbuff_positions[x] != null) { buff_tnt_positions.append("=" + colid + " (pos" + position_names[x] + ") " + array_strbuff_positions[x] + "\n"); flag_display_tnt_positions = true; colid++; } } if(flag_display_tnt_positions) writer.println(buff_tnt_positions.toString() + "\n;\n\n"); // put in any other blocks if(otherBlocks != null) writer.println(otherBlocks); writer.close(); // it's over ... if(delay != null) delay.end(); set.unlock(); } /** * Checks to see if this file *might* be of this format. Good for internal loops. * * No exceptions: implementors, please swallow them all up. If the file does not * exist, it's not very likely to be of this format, is it? */ public boolean mightBe(File file) { try { BufferedReader buff = new BufferedReader(new FileReader(file)); while(buff.ready()) { String str = buff.readLine().trim(); if(str.equals("")) continue; if(str.toLowerCase().indexOf("xread") != -1) { // we find xread! // we don't know if its parseable, but ... well. // *shrugs* // </irresponsibility> // // TODO Make this actually work, etc. return true; } } return false; } catch(IOException e) { return false; } } private String fixColumnName(String columnName) { columnName = columnName.replaceAll("\\.nex", ""); columnName = columnName.replaceAll("\\.tnt", ""); columnName = columnName.replace('.', '_'); columnName = columnName.replace(' ', '_'); columnName = columnName.replace('-', '_'); columnName = columnName.replace('\\', '_'); columnName = columnName.replace('/', '_'); return columnName; } }
false
true
public void groupCommand(int which_group, SequenceList appendTo, StreamTokenizer tok, FormatHandlerEvent evt, DelayCallback delay, int count_lines) throws FormatException, DelayAbortedException, IOException { int begin_at = tok.lineno(); // which line did this group start at String current_command_name = ""; if(which_group == GROUP_CHARSET) current_command_name = "xgroup"; else current_command_name = "agroup"; System.err.println("Beginning: " + current_command_name); // okay, we're assuming that '?group' has already started. // since fullstops can be used in ranges, we NEED them to be wordChars, // so that they turn up as a word (i.e., '23.26' is returned as '23.26', // not '23' '.' '26') tok.wordChars('.', '.'); // brackets are word chars in xread. We need them to be non-word chars // here. tok.ordinaryChar('('); tok.ordinaryChar(')'); // okay, we pop into the loop. we're looking for: // ';' -> exit // '=' -> start new group (slurp group id) // '(' -> set title for last group (slurp until terminating ')') // word -> ought to be either: // \d+ -> one single unit to be added to the group // \d+\.\d+ -> a range to be added. note that some programs // like spewing ranges out as consecutive numbers. // we ought to track this, watch for a line, and // then ... oh, never MIND. // // this effectively means that you can pull crazy shit like: // xgroup (ha ha!) =1 34.24 (this is weird, innit?) 13 54 (multiple titles wtf?) 24.52 =2 13 // and so on. But hey, well formed files will work just fine. // Hashtable hash_group_ids = new Hashtable(); // String id -> Sequence String currentName = ""; int sequence_begin = -1; int sequence_end = -1; while(true) { int type = tok.nextToken(); if(delay != null) delay.delay(tok.lineno(), count_lines); if(type == StreamTokenizer.TT_EOF) { // wtf?! throw formatException(tok, "I've reached the end of the file, but the '" + current_command_name + "' beginning at line " + begin_at + " was never terminated."); } if(type == ';') // it's over. Go back home, etc. break; if(type == '=') { // we've got a new sequence // BUT, first, we need to ensure that the last sequence is terminated // fire the last if(sequence_begin == -1 || sequence_end == -1) { // no sequences have begun yet. booyah. } else { if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multi-character sequence [2]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, the next token ought to be a unique group id String group_id; if(tok.nextToken() != StreamTokenizer.TT_WORD) { tok.pushBack(); // throw formatException(tok, "Expecting the group id, but found '" + (char)tok.ttype + "' instead!"); group_id = new Integer(++last_group_id_used).toString(); } else { group_id = tok.sval; } if(hash_group_ids.get(group_id) != null) throw formatException(tok, "Duplicate group id '" + group_id + "' found!"); // okay, set the new group id! hash_group_ids.put(group_id, new Integer(0)); currentName = "Group #" + group_id; continue; } else if(type == '(') { // okay, now we basically read until the closing ')' // and store it in currentName StringBuffer buff_name = new StringBuffer(); int title_began = tok.lineno(); while(tok.nextToken() != ')') { if(delay != null) delay.delay(tok.lineno(), count_lines); if(tok.ttype == StreamTokenizer.TT_EOF) throw formatException(tok, "The title which began in " + current_command_name + " on line " + title_began + " is not terminated! (I can't find the ')' which would end it)."); else if(tok.ttype == StreamTokenizer.TT_WORD) buff_name.append(tok.sval); else buff_name.append((char) tok.ttype); } currentName = buff_name.toString(); // But wait! Some names are extra-special. // Note that we discard the charset name // at this point: any positional data is // collected together and used while // resplitting the entire file. String originalName = currentName; if (currentName.matches("^.*_posN$")) { currentName = ":0"; } if (currentName.matches("^.*_pos1$")) { currentName = ":1"; } if (currentName.matches("^.*_pos2$")) { currentName = ":2"; } if (currentName.matches("^.*_pos3$")) { currentName = ":3"; } // System.err.println("Converted '" + originalName + "' -> '" + currentName + "'"); // Now the rest of this method will keep // adding these positions into the special // codonsets. HAHA BRILLIANT. continue; } else if(type == StreamTokenizer.TT_WORD) { // word! String word = tok.sval; // now, this is either: // 1. \d+ -> a number! submit straightaway, get on with life // 2. \d+. -> a range, from number to LENGTH_OF_SET. submit, etc. // 3. .\d+ -> a range, from 0 to number. submit, etc. // 4. \d+.\d+ -> a range, from num1 to num2. submit, etc. // // the trick is figuring out which one is which. // if(word.indexOf('.') == -1) { // We've got a single number. int locus = atoi(word, tok); if(sequence_begin == -1) { sequence_begin = locus; } if(sequence_end == -1 || sequence_end == locus - 1) { // if sequence_end is pointing at the LAST locus, sequence_end = locus; // move it to the current position // the sequence continues, so we do NOT fire now } else { // the sequence ends here! // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= (sequence_end + 1); d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [6]: " + currentName + " from " + d + " to " + d); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1)); //System.err.println("New multicharacter sequence [3]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = locus; sequence_end = locus; } continue; } else { // okay, there's a fullstop here ... // sigh. // // you have to wonder why you bother, sometimes. // one question: do we have an unfired sequence? // if we do, fire it first! // fire the last if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [1]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, now we can fire this next bugger int from = 0; int to = 0; if(word.charAt(0) == '.') { // it's a '.\d+' or a '.' if(word.length() == 1) { // it's a '.' from = 0; to = appendTo.getMaxLength(); } else { // it's a '.\d+' from = 0; to = atoi(word.substring(1), tok); } } else if(word.charAt(word.length() - 1) == '.') { // it's at the end from = atoi(word.substring(0, word.length() - 1), tok); to = appendTo.getMaxLength(); } else { // it's in the middle int indexOf = word.indexOf('.'); from = atoi(word.substring(0, indexOf - 1), tok); to = atoi(word.substring(indexOf + 1), tok); } if(which_group == GROUP_CHARSET) { from++; // convert from TNT loci (0-based) to normal loci (1-based) to++; // Multi-character blocks are POISON for situations where // the sequences are supposed to move in thirds (i.e. ':1', // ':2' and ':3'. This is because the algorithm for figuring // out position information is designed to work with fireEvent(evt.makeCharacterSetFoundEvent( currentName, from, to)); //System.err.println("New multi-character block [4]: " + currentName + " from " + from + " to " + to); } continue; } } else { throw formatException(tok, "I found '" + (char)type + "' rather unexpectedly in the " + current_command_name + " command beginning on line " + begin_at + "! Are you sure it's supposed to be here?"); } } // do we have an incomplete sequence? if(sequence_begin != -1 && sequence_end != -1) { // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= sequence_end + 1; d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [7]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [5]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } } // Restore '.' to its usual position as a character. tok.ordinaryChar('.'); // Restore brackets to their magical significance in the xread. tok.wordChars('(', ')'); tok.wordChars(')', ')'); }
public void groupCommand(int which_group, SequenceList appendTo, StreamTokenizer tok, FormatHandlerEvent evt, DelayCallback delay, int count_lines) throws FormatException, DelayAbortedException, IOException { int begin_at = tok.lineno(); // which line did this group start at String current_command_name = ""; if(which_group == GROUP_CHARSET) current_command_name = "xgroup"; else current_command_name = "agroup"; System.err.println("Beginning: " + current_command_name); // okay, we're assuming that '?group' has already started. // since fullstops can be used in ranges, we NEED them to be wordChars, // so that they turn up as a word (i.e., '23.26' is returned as '23.26', // not '23' '.' '26') tok.wordChars('.', '.'); // brackets are word chars in xread. We need them to be non-word chars // here. tok.ordinaryChar('('); tok.ordinaryChar(')'); // okay, we pop into the loop. we're looking for: // ';' -> exit // '=' -> start new group (slurp group id) // '(' -> set title for last group (slurp until terminating ')') // word -> ought to be either: // \d+ -> one single unit to be added to the group // \d+\.\d+ -> a range to be added. note that some programs // like spewing ranges out as consecutive numbers. // we ought to track this, watch for a line, and // then ... oh, never MIND. // // this effectively means that you can pull crazy shit like: // xgroup (ha ha!) =1 34.24 (this is weird, innit?) 13 54 (multiple titles wtf?) 24.52 =2 13 // and so on. But hey, well formed files will work just fine. // Hashtable hash_group_ids = new Hashtable(); // String id -> Sequence String currentName = ""; int sequence_begin = -1; int sequence_end = -1; while(true) { int type = tok.nextToken(); if(delay != null) delay.delay(tok.lineno(), count_lines); if(type == StreamTokenizer.TT_EOF) { // wtf?! throw formatException(tok, "I've reached the end of the file, but the '" + current_command_name + "' beginning at line " + begin_at + " was never terminated."); } if(type == ';') // it's over. Go back home, etc. break; if(type == '=') { // we've got a new sequence // BUT, first, we need to ensure that the last sequence is terminated // fire the last if(sequence_begin == -1 || sequence_end == -1) { // no sequences have begun yet. booyah. } else { if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multi-character sequence [2]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, the next token ought to be a unique group id String group_id; if(tok.nextToken() != StreamTokenizer.TT_WORD) { tok.pushBack(); // throw formatException(tok, "Expecting the group id, but found '" + (char)tok.ttype + "' instead!"); group_id = new Integer(++last_group_id_used).toString(); } else { group_id = tok.sval; } if(hash_group_ids.get(group_id) != null) throw formatException(tok, "Duplicate group id '" + group_id + "' found!"); // okay, set the new group id! hash_group_ids.put(group_id, new Integer(0)); currentName = "Group #" + group_id; continue; } else if(type == '(') { // okay, now we basically read until the closing ')' // and store it in currentName StringBuffer buff_name = new StringBuffer(); int title_began = tok.lineno(); while(tok.nextToken() != ')') { if(delay != null) delay.delay(tok.lineno(), count_lines); if(tok.ttype == StreamTokenizer.TT_EOF) throw formatException(tok, "The title which began in " + current_command_name + " on line " + title_began + " is not terminated! (I can't find the ')' which would end it)."); else if(tok.ttype == StreamTokenizer.TT_WORD) buff_name.append(tok.sval); else buff_name.append((char) tok.ttype); } currentName = buff_name.toString(); // But wait! Some names are extra-special. // Note that we discard the charset name // at this point: any positional data is // collected together and used while // resplitting the entire file. String originalName = currentName; if (currentName.matches("^.*_posN$") || currentName.equals("posN")) { currentName = ":0"; } if (currentName.matches("^.*_pos1$") || currentName.equals("pos1")) { currentName = ":1"; } if (currentName.matches("^.*_pos2$") || currentName.equals("pos2")) { currentName = ":2"; } if (currentName.matches("^.*_pos3$") || currentName.equals("pos3")) { currentName = ":3"; } // System.err.println("Converted '" + originalName + "' -> '" + currentName + "'"); // Now the rest of this method will keep // adding these positions into the special // codonsets. HAHA BRILLIANT. continue; } else if(type == StreamTokenizer.TT_WORD) { // word! String word = tok.sval; // now, this is either: // 1. \d+ -> a number! submit straightaway, get on with life // 2. \d+. -> a range, from number to LENGTH_OF_SET. submit, etc. // 3. .\d+ -> a range, from 0 to number. submit, etc. // 4. \d+.\d+ -> a range, from num1 to num2. submit, etc. // // the trick is figuring out which one is which. // if(word.indexOf('.') == -1) { // We've got a single number. int locus = atoi(word, tok); if(sequence_begin == -1) { sequence_begin = locus; } if(sequence_end == -1 || sequence_end == locus - 1) { // if sequence_end is pointing at the LAST locus, sequence_end = locus; // move it to the current position // the sequence continues, so we do NOT fire now } else { // the sequence ends here! // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= (sequence_end + 1); d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [6]: " + currentName + " from " + d + " to " + d); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1)); //System.err.println("New multicharacter sequence [3]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } // then set up the next one sequence_begin = locus; sequence_end = locus; } continue; } else { // okay, there's a fullstop here ... // sigh. // // you have to wonder why you bother, sometimes. // one question: do we have an unfired sequence? // if we do, fire it first! // fire the last if(which_group == GROUP_CHARSET) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [1]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } // then set up the next one sequence_begin = -1; sequence_end = -1; // okay, now we can fire this next bugger int from = 0; int to = 0; if(word.charAt(0) == '.') { // it's a '.\d+' or a '.' if(word.length() == 1) { // it's a '.' from = 0; to = appendTo.getMaxLength(); } else { // it's a '.\d+' from = 0; to = atoi(word.substring(1), tok); } } else if(word.charAt(word.length() - 1) == '.') { // it's at the end from = atoi(word.substring(0, word.length() - 1), tok); to = appendTo.getMaxLength(); } else { // it's in the middle int indexOf = word.indexOf('.'); from = atoi(word.substring(0, indexOf - 1), tok); to = atoi(word.substring(indexOf + 1), tok); } if(which_group == GROUP_CHARSET) { from++; // convert from TNT loci (0-based) to normal loci (1-based) to++; // Multi-character blocks are POISON for situations where // the sequences are supposed to move in thirds (i.e. ':1', // ':2' and ':3'. This is because the algorithm for figuring // out position information is designed to work with fireEvent(evt.makeCharacterSetFoundEvent( currentName, from, to)); //System.err.println("New multi-character block [4]: " + currentName + " from " + from + " to " + to); } continue; } } else { throw formatException(tok, "I found '" + (char)type + "' rather unexpectedly in the " + current_command_name + " command beginning on line " + begin_at + "! Are you sure it's supposed to be here?"); } } // do we have an incomplete sequence? if(sequence_begin != -1 && sequence_end != -1) { // fire the last if(which_group == GROUP_CHARSET) { if(currentName.charAt(0) == ':') { for(int d = sequence_begin + 1; d <= sequence_end + 1; d++) { fireEvent(evt.makeCharacterSetFoundEvent( currentName, d, d) ); //System.err.println("New multicharacter sequence [7]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } else { fireEvent(evt.makeCharacterSetFoundEvent( currentName, sequence_begin + 1, sequence_end + 1) ); //System.err.println("New multicharacter sequence [5]: " + currentName + " from " + sequence_begin + " to " + sequence_end); } } } // Restore '.' to its usual position as a character. tok.ordinaryChar('.'); // Restore brackets to their magical significance in the xread. tok.wordChars('(', ')'); tok.wordChars(')', ')'); }
diff --git a/demos/seq/db/CreateIndex.java b/demos/seq/db/CreateIndex.java index 66ec29c85..b3d891308 100755 --- a/demos/seq/db/CreateIndex.java +++ b/demos/seq/db/CreateIndex.java @@ -1,94 +1,94 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package seq.db; import java.io.*; import java.util.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.io.*; import org.biojava.bio.seq.db.*; /** * This demo file is a simple implementation of an index file generator. * * @author Matthew Pocock * @author Thomas Down */ public class CreateIndex { public static void main(String[] args) { try { if(args.length != 3) { throw new Exception("Use: indexName format alphabet"); } String indexName = args[0]; File indexFile = new File(indexName); File indexList = new File(indexName + ".list"); String formatName = args[1]; String alphaName = args[2]; Alphabet alpha = resolveAlphabet(alphaName); - SymbolParser sParser = alpha.getParser("token"); + SymbolTokenization sParser = alpha.getTokenization("token"); SequenceFormat sFormat = null; SequenceBuilderFactory sFact = null; if(formatName.equals("fasta")) { sFormat = new FastaFormat(); sFact = new FastaDescriptionLineParser.Factory(SimpleSequenceBuilder.FACTORY); } else if(formatName.equals("embl")) { sFormat = new EmblLikeFormat(); sFact = new EmblProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else if (formatName.equals("swissprot")) { sFormat = new EmblLikeFormat(); sFact = new SwissprotProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else { throw new Exception("Format must be one of {embl, fasta, swissprot}"); } TabIndexStore tis = new TabIndexStore( indexFile, indexList, indexName, sFormat, sFact, sParser ); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } } private static Alphabet resolveAlphabet(String alphaName) throws IllegalArgumentException { alphaName = alphaName.toLowerCase(); if(alphaName.equals("dna")) { return DNATools.getDNA(); } else if(alphaName.equals("protein")) { return ProteinTools.getAlphabet(); } else { throw new IllegalArgumentException("Could not find alphabet for " + alphaName); } } }
true
true
public static void main(String[] args) { try { if(args.length != 3) { throw new Exception("Use: indexName format alphabet"); } String indexName = args[0]; File indexFile = new File(indexName); File indexList = new File(indexName + ".list"); String formatName = args[1]; String alphaName = args[2]; Alphabet alpha = resolveAlphabet(alphaName); SymbolParser sParser = alpha.getParser("token"); SequenceFormat sFormat = null; SequenceBuilderFactory sFact = null; if(formatName.equals("fasta")) { sFormat = new FastaFormat(); sFact = new FastaDescriptionLineParser.Factory(SimpleSequenceBuilder.FACTORY); } else if(formatName.equals("embl")) { sFormat = new EmblLikeFormat(); sFact = new EmblProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else if (formatName.equals("swissprot")) { sFormat = new EmblLikeFormat(); sFact = new SwissprotProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else { throw new Exception("Format must be one of {embl, fasta, swissprot}"); } TabIndexStore tis = new TabIndexStore( indexFile, indexList, indexName, sFormat, sFact, sParser ); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
public static void main(String[] args) { try { if(args.length != 3) { throw new Exception("Use: indexName format alphabet"); } String indexName = args[0]; File indexFile = new File(indexName); File indexList = new File(indexName + ".list"); String formatName = args[1]; String alphaName = args[2]; Alphabet alpha = resolveAlphabet(alphaName); SymbolTokenization sParser = alpha.getTokenization("token"); SequenceFormat sFormat = null; SequenceBuilderFactory sFact = null; if(formatName.equals("fasta")) { sFormat = new FastaFormat(); sFact = new FastaDescriptionLineParser.Factory(SimpleSequenceBuilder.FACTORY); } else if(formatName.equals("embl")) { sFormat = new EmblLikeFormat(); sFact = new EmblProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else if (formatName.equals("swissprot")) { sFormat = new EmblLikeFormat(); sFact = new SwissprotProcessor.Factory(SimpleSequenceBuilder.FACTORY); } else { throw new Exception("Format must be one of {embl, fasta, swissprot}"); } TabIndexStore tis = new TabIndexStore( indexFile, indexList, indexName, sFormat, sFact, sParser ); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } }
diff --git a/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQEndpointWorker.java b/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQEndpointWorker.java index 416033258..69a7b04dd 100755 --- a/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQEndpointWorker.java +++ b/activemq-ra/src/main/java/org/apache/activemq/ra/ActiveMQEndpointWorker.java @@ -1,316 +1,316 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.ra; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicBoolean; import javax.jms.Connection; import javax.jms.ConnectionConsumer; import javax.jms.ExceptionListener; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.Session; import javax.jms.Topic; import javax.resource.ResourceException; import javax.resource.spi.endpoint.MessageEndpointFactory; import javax.resource.spi.work.Work; import javax.resource.spi.work.WorkException; import javax.resource.spi.work.WorkManager; import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * $Date$ */ public class ActiveMQEndpointWorker { public static final Method ON_MESSAGE_METHOD; private static final Logger LOG = LoggerFactory.getLogger(ActiveMQEndpointWorker.class); private static final long INITIAL_RECONNECT_DELAY = 1000; // 1 second. private static final long MAX_RECONNECT_DELAY = 1000 * 30; // 30 seconds. private static final ThreadLocal<Session> THREAD_LOCAL = new ThreadLocal<Session>(); static { try { ON_MESSAGE_METHOD = MessageListener.class.getMethod("onMessage", new Class[] { Message.class }); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } protected final ActiveMQEndpointActivationKey endpointActivationKey; protected final MessageEndpointFactory endpointFactory; protected final WorkManager workManager; protected final boolean transacted; private final ActiveMQDestination dest; private final Work connectWork; private final AtomicBoolean connecting = new AtomicBoolean(false); private final Object shutdownMutex = new String("shutdownMutex"); private ActiveMQConnection connection; private ConnectionConsumer consumer; private ServerSessionPoolImpl serverSessionPool; private boolean running; protected ActiveMQEndpointWorker(final MessageResourceAdapter adapter, ActiveMQEndpointActivationKey key) throws ResourceException { this.endpointActivationKey = key; this.endpointFactory = endpointActivationKey.getMessageEndpointFactory(); this.workManager = adapter.getBootstrapContext().getWorkManager(); try { this.transacted = endpointFactory.isDeliveryTransacted(ON_MESSAGE_METHOD); } catch (NoSuchMethodException e) { throw new ResourceException("Endpoint does not implement the onMessage method."); } connectWork = new Work() { long currentReconnectDelay = INITIAL_RECONNECT_DELAY; public void release() { // } - public synchronized void run() { + public void run() { currentReconnectDelay = INITIAL_RECONNECT_DELAY; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ( LOG.isInfoEnabled() ) { LOG.info("Establishing connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } while ( connecting.get() && running ) { try { connection = adapter.makeConnection(activationSpec); connection.setExceptionListener(new ExceptionListener() { public void onException(JMSException error) { if (!serverSessionPool.isClosing()) { // initiate reconnection only once, i.e. on initial exception // and only if not already trying to connect LOG.error("Connection to broker failed: " + error.getMessage(), error); if ( connecting.compareAndSet(false, true) ) { synchronized ( connectWork ) { disconnect(); serverSessionPool.closeIdleSessions(); connect(); } } else { // connection attempt has already been initiated LOG.info("Connection attempt already in progress, ignoring connection exception"); } } } }); connection.start(); int prefetchSize = activationSpec.getMaxMessagesPerSessionsIntValue() * activationSpec.getMaxSessionsIntValue(); if (activationSpec.isDurableSubscription()) { consumer = connection.createDurableConnectionConsumer( (Topic) dest, activationSpec.getSubscriptionName(), emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } else { consumer = connection.createConnectionConsumer( dest, emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } if ( connecting.compareAndSet(true, false) ) { if ( LOG.isInfoEnabled() ) { LOG.info("Successfully established connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } } else { LOG.error("Could not release connection lock"); } } catch (JMSException error) { if ( LOG.isDebugEnabled() ) { LOG.debug("Failed to connect: " + error.getMessage(), error); } disconnect(); pause(error); } } } private void pause(JMSException error) { if (currentReconnectDelay == MAX_RECONNECT_DELAY) { LOG.error("Failed to connect to broker [" + adapter.getInfo().getServerUrl() + "]: " + error.getMessage(), error); LOG.error("Endpoint will try to reconnect to the JMS broker in " + (MAX_RECONNECT_DELAY / 1000) + " seconds"); } try { synchronized ( shutdownMutex ) { // shutdownMutex will be notified by stop() method in // order to accelerate shutdown of endpoint shutdownMutex.wait(currentReconnectDelay); } } catch ( InterruptedException e ) { Thread.interrupted(); } currentReconnectDelay *= 2; if (currentReconnectDelay > MAX_RECONNECT_DELAY) { currentReconnectDelay = MAX_RECONNECT_DELAY; } } }; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ("javax.jms.Queue".equals(activationSpec.getDestinationType())) { dest = new ActiveMQQueue(activationSpec.getDestination()); } else if ("javax.jms.Topic".equals(activationSpec.getDestinationType())) { dest = new ActiveMQTopic(activationSpec.getDestination()); } else { throw new ResourceException("Unknown destination type: " + activationSpec.getDestinationType()); } } /** * @param c */ public static void safeClose(Connection c) { try { if (c != null) { LOG.debug("Closing connection to broker"); c.close(); } } catch (JMSException e) { // } } /** * @param cc */ public static void safeClose(ConnectionConsumer cc) { try { if (cc != null) { LOG.debug("Closing ConnectionConsumer"); cc.close(); } } catch (JMSException e) { // } } /** * */ public void start() throws ResourceException { synchronized (connectWork) { if (running) return; running = true; if ( connecting.compareAndSet(false, true) ) { LOG.info("Starting"); serverSessionPool = new ServerSessionPoolImpl(this, endpointActivationKey.getActivationSpec().getMaxSessionsIntValue()); connect(); } else { LOG.warn("Ignoring start command, EndpointWorker is already trying to connect"); } } } /** * */ public void stop() throws InterruptedException { synchronized (shutdownMutex) { if (!running) return; running = false; LOG.info("Stopping"); // wake up pausing reconnect attempt shutdownMutex.notifyAll(); serverSessionPool.close(); } disconnect(); } private boolean isRunning() { return running; } private void connect() { synchronized ( connectWork ) { if (!running) { return; } try { workManager.scheduleWork(connectWork, WorkManager.INDEFINITE, null, null); } catch (WorkException e) { running = false; LOG.error("Work Manager did not accept work: ", e); } } } /** * */ private void disconnect() { synchronized ( connectWork ) { safeClose(consumer); consumer = null; safeClose(connection); connection = null; } } protected void registerThreadSession(Session session) { THREAD_LOCAL.set(session); } protected void unregisterThreadSession(Session session) { THREAD_LOCAL.set(null); } protected ActiveMQConnection getConnection() { // make sure we only return a working connection // in particular make sure that we do not return null // after the resource adapter got disconnected from // the broker via the disconnect() method synchronized ( connectWork ) { return connection; } } private String emptyToNull(String value) { if (value == null || value.length() == 0) { return null; } return value; } }
true
true
protected ActiveMQEndpointWorker(final MessageResourceAdapter adapter, ActiveMQEndpointActivationKey key) throws ResourceException { this.endpointActivationKey = key; this.endpointFactory = endpointActivationKey.getMessageEndpointFactory(); this.workManager = adapter.getBootstrapContext().getWorkManager(); try { this.transacted = endpointFactory.isDeliveryTransacted(ON_MESSAGE_METHOD); } catch (NoSuchMethodException e) { throw new ResourceException("Endpoint does not implement the onMessage method."); } connectWork = new Work() { long currentReconnectDelay = INITIAL_RECONNECT_DELAY; public void release() { // } public synchronized void run() { currentReconnectDelay = INITIAL_RECONNECT_DELAY; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ( LOG.isInfoEnabled() ) { LOG.info("Establishing connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } while ( connecting.get() && running ) { try { connection = adapter.makeConnection(activationSpec); connection.setExceptionListener(new ExceptionListener() { public void onException(JMSException error) { if (!serverSessionPool.isClosing()) { // initiate reconnection only once, i.e. on initial exception // and only if not already trying to connect LOG.error("Connection to broker failed: " + error.getMessage(), error); if ( connecting.compareAndSet(false, true) ) { synchronized ( connectWork ) { disconnect(); serverSessionPool.closeIdleSessions(); connect(); } } else { // connection attempt has already been initiated LOG.info("Connection attempt already in progress, ignoring connection exception"); } } } }); connection.start(); int prefetchSize = activationSpec.getMaxMessagesPerSessionsIntValue() * activationSpec.getMaxSessionsIntValue(); if (activationSpec.isDurableSubscription()) { consumer = connection.createDurableConnectionConsumer( (Topic) dest, activationSpec.getSubscriptionName(), emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } else { consumer = connection.createConnectionConsumer( dest, emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } if ( connecting.compareAndSet(true, false) ) { if ( LOG.isInfoEnabled() ) { LOG.info("Successfully established connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } } else { LOG.error("Could not release connection lock"); } } catch (JMSException error) { if ( LOG.isDebugEnabled() ) { LOG.debug("Failed to connect: " + error.getMessage(), error); } disconnect(); pause(error); } } } private void pause(JMSException error) { if (currentReconnectDelay == MAX_RECONNECT_DELAY) { LOG.error("Failed to connect to broker [" + adapter.getInfo().getServerUrl() + "]: " + error.getMessage(), error); LOG.error("Endpoint will try to reconnect to the JMS broker in " + (MAX_RECONNECT_DELAY / 1000) + " seconds"); } try { synchronized ( shutdownMutex ) { // shutdownMutex will be notified by stop() method in // order to accelerate shutdown of endpoint shutdownMutex.wait(currentReconnectDelay); } } catch ( InterruptedException e ) { Thread.interrupted(); } currentReconnectDelay *= 2; if (currentReconnectDelay > MAX_RECONNECT_DELAY) { currentReconnectDelay = MAX_RECONNECT_DELAY; } } }; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ("javax.jms.Queue".equals(activationSpec.getDestinationType())) { dest = new ActiveMQQueue(activationSpec.getDestination()); } else if ("javax.jms.Topic".equals(activationSpec.getDestinationType())) { dest = new ActiveMQTopic(activationSpec.getDestination()); } else { throw new ResourceException("Unknown destination type: " + activationSpec.getDestinationType()); } }
protected ActiveMQEndpointWorker(final MessageResourceAdapter adapter, ActiveMQEndpointActivationKey key) throws ResourceException { this.endpointActivationKey = key; this.endpointFactory = endpointActivationKey.getMessageEndpointFactory(); this.workManager = adapter.getBootstrapContext().getWorkManager(); try { this.transacted = endpointFactory.isDeliveryTransacted(ON_MESSAGE_METHOD); } catch (NoSuchMethodException e) { throw new ResourceException("Endpoint does not implement the onMessage method."); } connectWork = new Work() { long currentReconnectDelay = INITIAL_RECONNECT_DELAY; public void release() { // } public void run() { currentReconnectDelay = INITIAL_RECONNECT_DELAY; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ( LOG.isInfoEnabled() ) { LOG.info("Establishing connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } while ( connecting.get() && running ) { try { connection = adapter.makeConnection(activationSpec); connection.setExceptionListener(new ExceptionListener() { public void onException(JMSException error) { if (!serverSessionPool.isClosing()) { // initiate reconnection only once, i.e. on initial exception // and only if not already trying to connect LOG.error("Connection to broker failed: " + error.getMessage(), error); if ( connecting.compareAndSet(false, true) ) { synchronized ( connectWork ) { disconnect(); serverSessionPool.closeIdleSessions(); connect(); } } else { // connection attempt has already been initiated LOG.info("Connection attempt already in progress, ignoring connection exception"); } } } }); connection.start(); int prefetchSize = activationSpec.getMaxMessagesPerSessionsIntValue() * activationSpec.getMaxSessionsIntValue(); if (activationSpec.isDurableSubscription()) { consumer = connection.createDurableConnectionConsumer( (Topic) dest, activationSpec.getSubscriptionName(), emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } else { consumer = connection.createConnectionConsumer( dest, emptyToNull(activationSpec.getMessageSelector()), serverSessionPool, prefetchSize, activationSpec.getNoLocalBooleanValue()); } if ( connecting.compareAndSet(true, false) ) { if ( LOG.isInfoEnabled() ) { LOG.info("Successfully established connection to broker [" + adapter.getInfo().getServerUrl() + "]"); } } else { LOG.error("Could not release connection lock"); } } catch (JMSException error) { if ( LOG.isDebugEnabled() ) { LOG.debug("Failed to connect: " + error.getMessage(), error); } disconnect(); pause(error); } } } private void pause(JMSException error) { if (currentReconnectDelay == MAX_RECONNECT_DELAY) { LOG.error("Failed to connect to broker [" + adapter.getInfo().getServerUrl() + "]: " + error.getMessage(), error); LOG.error("Endpoint will try to reconnect to the JMS broker in " + (MAX_RECONNECT_DELAY / 1000) + " seconds"); } try { synchronized ( shutdownMutex ) { // shutdownMutex will be notified by stop() method in // order to accelerate shutdown of endpoint shutdownMutex.wait(currentReconnectDelay); } } catch ( InterruptedException e ) { Thread.interrupted(); } currentReconnectDelay *= 2; if (currentReconnectDelay > MAX_RECONNECT_DELAY) { currentReconnectDelay = MAX_RECONNECT_DELAY; } } }; MessageActivationSpec activationSpec = endpointActivationKey.getActivationSpec(); if ("javax.jms.Queue".equals(activationSpec.getDestinationType())) { dest = new ActiveMQQueue(activationSpec.getDestination()); } else if ("javax.jms.Topic".equals(activationSpec.getDestinationType())) { dest = new ActiveMQTopic(activationSpec.getDestination()); } else { throw new ResourceException("Unknown destination type: " + activationSpec.getDestinationType()); } }
diff --git a/src/bode/moritz/footfinger/MainMenuLayer.java b/src/bode/moritz/footfinger/MainMenuLayer.java index a591d18..5d9dcfa 100644 --- a/src/bode/moritz/footfinger/MainMenuLayer.java +++ b/src/bode/moritz/footfinger/MainMenuLayer.java @@ -1,63 +1,66 @@ package bode.moritz.footfinger; import org.cocos2d.layers.CCColorLayer; import org.cocos2d.layers.CCLayer; import org.cocos2d.layers.CCScene; import org.cocos2d.menus.CCMenu; import org.cocos2d.menus.CCMenuItem; import org.cocos2d.menus.CCMenuItemImage; import org.cocos2d.nodes.CCDirector; import org.cocos2d.nodes.CCSprite; import org.cocos2d.types.CGPoint; import org.cocos2d.types.CGSize; import org.cocos2d.types.ccColor4B; public class MainMenuLayer extends CCColorLayer { protected MainMenuLayer(ccColor4B color) { super(color); this.setIsTouchEnabled(true); CCSprite background = CCSprite.sprite("intro/intro_bg.png"); float winSize = (float) (CCDirector.sharedDirector().displaySize().getWidth()/960.0); background.setScale(winSize); background.setAnchorPoint(CGPoint.ccp(0f, 0f)); + addChild(background); CCSprite text = CCSprite.sprite("selection/text.png"); - text.setScale(0.5f); - text.setAnchorPoint(CGPoint.ccp(0f, 0f)); + text.setScale(winSize); + text.setAnchorPoint(CGPoint.ccp(CCDirector.sharedDirector().displaySize().getWidth()/2, 60.0f)); + addChild(text); CCMenuItem keeperItem = CCMenuItemImage.item("selection/keeper_btn.png", "selection/keeper_btn_p.png", this, "keeperClick"); CCMenuItem shooterItem = CCMenuItemImage.item("selection/shooter_btn.png", "selection/shooter_btn_p.png", this, "shooterClick"); - keeperItem.setScale(0.5f); - shooterItem.setScale(0.5f); + keeperItem.setScale(winSize); + shooterItem.setScale(winSize); CCMenu menu = CCMenu.menu(keeperItem, shooterItem); - menu.alignItemsVertically(300f); + menu.setAnchorPoint(CCDirector.sharedDirector().displaySize().getWidth()/2, 400.0f); + menu.alignItemsVertically(); addChild(menu); } public void keeperClick(Object sender){ CCDirector.sharedDirector().replaceScene(GoalKeeperWaitingConnectionLayer.scene()); } public void shooterClick(Object sender){ CCDirector.sharedDirector().replaceScene(ShooterConnectLayer.scene()); } public static CCScene scene() { CCScene scene = CCScene.node(); CCLayer layer = new MainMenuLayer(ccColor4B.ccc4(255, 255, 255, 255)); scene.addChild(layer); return scene; } }
false
true
protected MainMenuLayer(ccColor4B color) { super(color); this.setIsTouchEnabled(true); CCSprite background = CCSprite.sprite("intro/intro_bg.png"); float winSize = (float) (CCDirector.sharedDirector().displaySize().getWidth()/960.0); background.setScale(winSize); background.setAnchorPoint(CGPoint.ccp(0f, 0f)); CCSprite text = CCSprite.sprite("selection/text.png"); text.setScale(0.5f); text.setAnchorPoint(CGPoint.ccp(0f, 0f)); CCMenuItem keeperItem = CCMenuItemImage.item("selection/keeper_btn.png", "selection/keeper_btn_p.png", this, "keeperClick"); CCMenuItem shooterItem = CCMenuItemImage.item("selection/shooter_btn.png", "selection/shooter_btn_p.png", this, "shooterClick"); keeperItem.setScale(0.5f); shooterItem.setScale(0.5f); CCMenu menu = CCMenu.menu(keeperItem, shooterItem); menu.alignItemsVertically(300f); addChild(menu); }
protected MainMenuLayer(ccColor4B color) { super(color); this.setIsTouchEnabled(true); CCSprite background = CCSprite.sprite("intro/intro_bg.png"); float winSize = (float) (CCDirector.sharedDirector().displaySize().getWidth()/960.0); background.setScale(winSize); background.setAnchorPoint(CGPoint.ccp(0f, 0f)); addChild(background); CCSprite text = CCSprite.sprite("selection/text.png"); text.setScale(winSize); text.setAnchorPoint(CGPoint.ccp(CCDirector.sharedDirector().displaySize().getWidth()/2, 60.0f)); addChild(text); CCMenuItem keeperItem = CCMenuItemImage.item("selection/keeper_btn.png", "selection/keeper_btn_p.png", this, "keeperClick"); CCMenuItem shooterItem = CCMenuItemImage.item("selection/shooter_btn.png", "selection/shooter_btn_p.png", this, "shooterClick"); keeperItem.setScale(winSize); shooterItem.setScale(winSize); CCMenu menu = CCMenu.menu(keeperItem, shooterItem); menu.setAnchorPoint(CCDirector.sharedDirector().displaySize().getWidth()/2, 400.0f); menu.alignItemsVertically(); addChild(menu); }
diff --git a/cadpage/src/net/anei/cadpage/parsers/dispatch/DispatchOSSIParser.java b/cadpage/src/net/anei/cadpage/parsers/dispatch/DispatchOSSIParser.java index 1a5e9b4ef..8761d4ab2 100644 --- a/cadpage/src/net/anei/cadpage/parsers/dispatch/DispatchOSSIParser.java +++ b/cadpage/src/net/anei/cadpage/parsers/dispatch/DispatchOSSIParser.java @@ -1,170 +1,170 @@ package net.anei.cadpage.parsers.dispatch; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.anei.cadpage.SmsMsgInfo.Data; import net.anei.cadpage.parsers.FieldProgramParser; /** * This class parses messages from OSSI CAD software * * Format always starts with "CAD:" and generally consists of a series of * semicolon delimited fields which will be processed according to a program * passed from the subclass. * * There are, of course, some exception * The text may contain a leading numeric call ID and a colon before the CAD: * marker. Subclasses will indicate this by inserting an ID: term as the * first field term in the program * * The text may contain some text in square brackets. This comes in two flavors * * [mm/dd/yy hh:mm:ss xxxxxx] appears to be an subsequent update marker, it will * be treated as field delimiter * * [Medical Priority Info] or [Fire Priority Info] * The field that follows this may one of the two following formats * RESPONSE: xxxxxx RESPONDER SCRIPT: xxxxxx * PROBLEM: xxxxx # PATS: n AGE: SEX: xxxxxxx * * In this case we will skip all text up to and including the keyword * "RESPONDER SCRIPT: or "PROBLEM:" * * In addition, the last field in the string may be a date/time indicator * or a truncated piece of a date/time indicator. If this is the case * drop it from further consideration **/ public class DispatchOSSIParser extends FieldProgramParser { private boolean leadID = false; // Pattern searching for a leading square bracket or semicolon private Pattern delimPattern = Pattern.compile("\\[|;"); // Pattern searching for "PROBLEM: or "RESPONDER SCRIPT:" private static final Pattern KEYWORD = Pattern.compile("\\b(PROBLEM:|RESPONDER SCRIPT:)"); // Pattern marking a trailing token that may need to be removed private static final Pattern TAIL_PAT = Pattern.compile("CLDR?[0-9]"); public DispatchOSSIParser(String defCity, String defState, String program) { super(defCity, defState, "SKIP"); setup(program); } public DispatchOSSIParser(Properties cityCodes, String defCity, String defState, String program) { super(cityCodes, defCity, defState, "SKIP"); setup(program); } public DispatchOSSIParser(String[] cityList, String defCity, String defState, String program) { super(cityList, defCity, defState, "SKIP"); setup(program); } private void setup(String program) { if (program.startsWith("ID:")) { leadID = true; program = program.substring(3).trim(); } setProgram(program); } protected void setDelimiter(char delim) { delimPattern = Pattern.compile("\\[|" + delim); } @Override protected boolean parseMsg(String body, Data data) { // Strip off leading / - if (body.startsWith("/")) body = body.substring(2).trim(); + if (body.startsWith("/")) body = body.substring(1).trim(); // If format has a leading ID, strip that off if (leadID) { int pt = body.indexOf(':'); if (pt < 0) return false; data.strCallId = body.substring(0,pt).trim(); if (!NUMERIC.matcher(data.strCallId).matches()) return false; body = body.substring(pt+1).trim(); } // Body must start with 'CAD:' if (!body.startsWith("CAD:")) return false; // Break down string into generally semicolon delimited fields // with some complications involving text in square brackets List<String> fields = new ArrayList<String>(); Matcher match = delimPattern.matcher(body); int st = 4; boolean priInfo = false; while (st < body.length()) { // search for the next delimiter (either ; or [ char delim; int pt; if (match.find(st)) { pt = match.start(); delim = body.charAt(pt); } else { pt = body.length(); delim = 0; } // The next field consists of everything from the starting point // up to the location of the delimiter // If the delimiter in front of this term was a square bracket term // Search for and delete any text up to including the keywords // "PROBLEM:" or "RESPONDER SCRIPT:" String field = body.substring(st,pt).trim(); if (priInfo) { Matcher match2 = KEYWORD.matcher(field); if (!match2.find()) field = null; else field = field.substring(match2.end()).trim(); } if (field != null) fields.add(field); // Find the start of the next field // if the delimiter was an open square bracket, the start of the // next field will follow the closing square bracket st = pt+1; priInfo = false; if (delim == '[') { pt = body.indexOf(']', st); if (pt < 0) pt = body.length(); priInfo = body.substring(st, pt).contains("Priority Info"); st = pt + 1; } } int ndx = fields.size()-1; if (ndx < 0) return false; // If the trailing field is present, start by removing it if (TAIL_PAT.matcher(fields.get(ndx)).matches()) { fields.remove(ndx--); if (ndx < 0) return false; } // Almost there. Check to see if the last term looks like a date/time stamp // or the truncated remains of a date/time stamp. If it does, remove it String field = fields.get(ndx); if (field.length()>0 && Character.isDigit(field.charAt(0))) { field = field.replaceAll("\\d", "N"); if ("NN/NN/NNNN NN:NN:NN".startsWith(field)) fields.remove(ndx); } // We have a nice clean array of data fields, pass it to the programmer // field processor to parse return parseFields(fields.toArray(new String[fields.size()]), data); } }
true
true
protected boolean parseMsg(String body, Data data) { // Strip off leading / if (body.startsWith("/")) body = body.substring(2).trim(); // If format has a leading ID, strip that off if (leadID) { int pt = body.indexOf(':'); if (pt < 0) return false; data.strCallId = body.substring(0,pt).trim(); if (!NUMERIC.matcher(data.strCallId).matches()) return false; body = body.substring(pt+1).trim(); } // Body must start with 'CAD:' if (!body.startsWith("CAD:")) return false; // Break down string into generally semicolon delimited fields // with some complications involving text in square brackets List<String> fields = new ArrayList<String>(); Matcher match = delimPattern.matcher(body); int st = 4; boolean priInfo = false; while (st < body.length()) { // search for the next delimiter (either ; or [ char delim; int pt; if (match.find(st)) { pt = match.start(); delim = body.charAt(pt); } else { pt = body.length(); delim = 0; } // The next field consists of everything from the starting point // up to the location of the delimiter // If the delimiter in front of this term was a square bracket term // Search for and delete any text up to including the keywords // "PROBLEM:" or "RESPONDER SCRIPT:" String field = body.substring(st,pt).trim(); if (priInfo) { Matcher match2 = KEYWORD.matcher(field); if (!match2.find()) field = null; else field = field.substring(match2.end()).trim(); } if (field != null) fields.add(field); // Find the start of the next field // if the delimiter was an open square bracket, the start of the // next field will follow the closing square bracket st = pt+1; priInfo = false; if (delim == '[') { pt = body.indexOf(']', st); if (pt < 0) pt = body.length(); priInfo = body.substring(st, pt).contains("Priority Info"); st = pt + 1; } } int ndx = fields.size()-1; if (ndx < 0) return false; // If the trailing field is present, start by removing it if (TAIL_PAT.matcher(fields.get(ndx)).matches()) { fields.remove(ndx--); if (ndx < 0) return false; } // Almost there. Check to see if the last term looks like a date/time stamp // or the truncated remains of a date/time stamp. If it does, remove it String field = fields.get(ndx); if (field.length()>0 && Character.isDigit(field.charAt(0))) { field = field.replaceAll("\\d", "N"); if ("NN/NN/NNNN NN:NN:NN".startsWith(field)) fields.remove(ndx); } // We have a nice clean array of data fields, pass it to the programmer // field processor to parse return parseFields(fields.toArray(new String[fields.size()]), data); }
protected boolean parseMsg(String body, Data data) { // Strip off leading / if (body.startsWith("/")) body = body.substring(1).trim(); // If format has a leading ID, strip that off if (leadID) { int pt = body.indexOf(':'); if (pt < 0) return false; data.strCallId = body.substring(0,pt).trim(); if (!NUMERIC.matcher(data.strCallId).matches()) return false; body = body.substring(pt+1).trim(); } // Body must start with 'CAD:' if (!body.startsWith("CAD:")) return false; // Break down string into generally semicolon delimited fields // with some complications involving text in square brackets List<String> fields = new ArrayList<String>(); Matcher match = delimPattern.matcher(body); int st = 4; boolean priInfo = false; while (st < body.length()) { // search for the next delimiter (either ; or [ char delim; int pt; if (match.find(st)) { pt = match.start(); delim = body.charAt(pt); } else { pt = body.length(); delim = 0; } // The next field consists of everything from the starting point // up to the location of the delimiter // If the delimiter in front of this term was a square bracket term // Search for and delete any text up to including the keywords // "PROBLEM:" or "RESPONDER SCRIPT:" String field = body.substring(st,pt).trim(); if (priInfo) { Matcher match2 = KEYWORD.matcher(field); if (!match2.find()) field = null; else field = field.substring(match2.end()).trim(); } if (field != null) fields.add(field); // Find the start of the next field // if the delimiter was an open square bracket, the start of the // next field will follow the closing square bracket st = pt+1; priInfo = false; if (delim == '[') { pt = body.indexOf(']', st); if (pt < 0) pt = body.length(); priInfo = body.substring(st, pt).contains("Priority Info"); st = pt + 1; } } int ndx = fields.size()-1; if (ndx < 0) return false; // If the trailing field is present, start by removing it if (TAIL_PAT.matcher(fields.get(ndx)).matches()) { fields.remove(ndx--); if (ndx < 0) return false; } // Almost there. Check to see if the last term looks like a date/time stamp // or the truncated remains of a date/time stamp. If it does, remove it String field = fields.get(ndx); if (field.length()>0 && Character.isDigit(field.charAt(0))) { field = field.replaceAll("\\d", "N"); if ("NN/NN/NNNN NN:NN:NN".startsWith(field)) fields.remove(ndx); } // We have a nice clean array of data fields, pass it to the programmer // field processor to parse return parseFields(fields.toArray(new String[fields.size()]), data); }
diff --git a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java index 3114c72a7..b55b757f4 100644 --- a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java +++ b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/PropertySheet.java @@ -1,715 +1,720 @@ package edu.cmu.sphinx.util.props; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Proxy; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * A property sheet which defines a collection of properties for a single component in the system. * * @author Holger Brandl */ public class PropertySheet implements Cloneable { public enum PropertyType { INT, DOUBLE, BOOL, COMP, STRING, COMPLIST } private Map<String, S4PropWrapper> registeredProperties = new HashMap<String, S4PropWrapper>(); private Map<String, Object> propValues = new HashMap<String, Object>(); /** * Maps the names of the component properties to their (possibly unresolved) values. * <p/> * Example: <code>frontend</code> to <code>${myFrontEnd}</code> */ private Map<String, Object> rawProps = new HashMap<String, Object>(); private ConfigurationManager cm; private Configurable owner; private final Class<? extends Configurable> ownerClass; private String instanceName; public PropertySheet(Configurable configurable, String name, RawPropertyData rpd, ConfigurationManager ConfigurationManager) { this(configurable.getClass(), name, ConfigurationManager, rpd); owner = configurable; } public PropertySheet(Class<? extends Configurable> confClass, String name, ConfigurationManager cm, RawPropertyData rpd) { ownerClass = confClass; this.cm = cm; this.instanceName = name; processAnnotations(this, confClass); // now apply all xml properties Map<String, Object> flatProps = rpd.flatten(cm).getProperties(); rawProps = new HashMap<String, Object>(rpd.getProperties()); for (String propName : rawProps.keySet()) propValues.put(propName, flatProps.get(propName)); } /** * Registers a new property which type and default value are defined by the given sphinx property. * * @param propName The name of the property to be registered. * @param property The property annoation masked by a proxy. */ private void registerProperty(String propName, S4PropWrapper property) { assert property != null && propName != null; registeredProperties.put(propName, property); propValues.put(propName, null); rawProps.put(propName, null); } /** Returns the property names <code>name</code> which is still wrapped into the annotation instance. */ public S4PropWrapper getProperty(String name, Class propertyClass) throws PropertyException { if (!propValues.containsKey(name)) throw new InternalConfigurationException(getInstanceName(), name, "Unknown property '" + name + "' ! Make sure that you've annotated it."); S4PropWrapper s4PropWrapper = registeredProperties.get(name); try { propertyClass.cast(s4PropWrapper.getAnnotation()); } catch (ClassCastException e) { throw new InternalConfigurationException(e, getInstanceName(), name, name + " is not an annotated sphinx property of '" + getConfigurableClass().getName() + "' !"); } return s4PropWrapper; } /** * Gets the value associated with this name * * @param name the name * @return the value */ public String getString(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4String.class); S4String s4String = ((S4String) s4PropWrapper.getAnnotation()); if (propValues.get(name) == null) { boolean isDefDefined = !s4String.defaultValue().equals(S4String.NOT_DEFINED); if (s4String.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } // else if(!isDefDefined) // throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, isDefDefined ? s4String.defaultValue() : null); } String propValue = (String) propValues.get(name); //check range List<String> range = Arrays.asList(s4String.range()); if (!range.isEmpty() && !range.contains(propValue)) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public int getInt(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Integer.class); S4Integer s4Integer = (S4Integer) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Integer.defaultValue() == S4Integer.NOT_DEFINED); if (s4Integer.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Integer.defaultValue()); } Object propObject = propValues.get(name); Integer propValue = propObject instanceof Integer ? (Integer) propObject : Integer.decode((String) propObject); int[] range = s4Integer.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public float getFloat(String name) throws PropertyException { return ((Double) getDouble(name)).floatValue(); } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public double getDouble(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Double.class); S4Double s4Double = (S4Double) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null) { boolean isDefDefined = !(s4Double.defaultValue() == S4Double.NOT_DEFINED); if (s4Double.mandatory()) { if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else if (!isDefDefined) throw new InternalConfigurationException(getInstanceName(), name, "no default value for non-mandatory property"); propValues.put(name, s4Double.defaultValue()); } Object propObject = propValues.get(name); Double propValue = propObject instanceof Double ? (Double) propObject : Double.valueOf((String) propObject); double[] range = s4Double.range(); if (range.length != 2) throw new InternalConfigurationException(getInstanceName(), name, range + " is not of expected range type, which is {minValue, maxValue)"); if (propValue < range[0] || propValue > range[1]) throw new InternalConfigurationException(getInstanceName(), name, " is not in range (" + range + ")"); return propValue; } /** * Gets the value associated with this name * * @param name the name * @return the value * @throws edu.cmu.sphinx.util.props.PropertyException * if the named property is not of this type */ public Boolean getBoolean(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Boolean.class); S4Boolean s4Boolean = (S4Boolean) s4PropWrapper.getAnnotation(); if (propValues.get(name) == null && !s4Boolean.isNotDefined()) propValues.put(name, s4Boolean.defaultValue()); Object propValue = propValues.get(name); if (propValue instanceof String) propValue = Boolean.valueOf((String) propValue); return (Boolean) propValue; } /** * Gets a component associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); if (propValues.get(name) == null || propValues.get(name) instanceof String) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet((String) propValues.get(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { - if (Modifier.isAbstract(defClass.getModifiers())) + if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, assert that it is set - if (defClass.equals(Configurable.class)) - throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); + if (defClass.equals(Configurable.class)) { + if (s4Component.mandatory()) { + throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); + } else { + return null; + } + } configurable = ConfigurationManager.getInstance(defClass); assert configurable != null; } } } catch (ClassNotFoundException e) { throw new PropertyException(e); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); } /** Returns the class of of a registered component property without instantiating it. */ public Class<? extends Configurable> getComponentClass(String propName) { Class<? extends Configurable> defClass = null; if (propValues.get(propName) != null) try { defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(propName)); } catch (ClassNotFoundException e) { e.printStackTrace(); } else { S4Component comAnno = (S4Component) registeredProperties.get(propName).getAnnotation(); defClass = comAnno.defaultClass(); if (comAnno.mandatory()) defClass = null; } return defClass; } /** * Gets a list of components associated with the given parameter name * * @param name the parameter name * @return the component associated with the name * @throws edu.cmu.sphinx.util.props.PropertyException * if the component does not exist or is of the wrong type. */ public List<? extends Configurable> getComponentList(String name) throws InternalConfigurationException { getProperty(name, S4ComponentList.class); List components = (List) propValues.get(name); assert registeredProperties.get(name).getAnnotation() instanceof S4ComponentList; S4ComponentList annoation = (S4ComponentList) registeredProperties.get(name).getAnnotation(); // no componets names are available and no comp-list was yet loaded // therefore load the default list of components from the annoation if (components == null) { List<Class<? extends Configurable>> defClasses = Arrays.asList(annoation.defaultList()); // if (annoation.mandatory() && defClasses.isEmpty()) // throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); components = new ArrayList(); for (Class<? extends Configurable> defClass : defClasses) { components.add(ConfigurationManager.getInstance(defClass)); } propValues.put(name, components); } if (!components.isEmpty() && !(components.get(0) instanceof Configurable)) { List<Configurable> list = new ArrayList<Configurable>(); for (Object componentName : components) { Configurable configurable = cm.lookup((String) componentName); assert configurable != null; list.add(configurable); } propValues.put(name, list); } return (List<? extends Configurable>) propValues.get(name); } public String getInstanceName() { return instanceName; } public void setInstanceName(String newInstanceName) { this.instanceName = newInstanceName; } /** Returns true if the owner of this property sheet is already instanciated. */ public boolean isInstanciated() { return !(owner == null); } /** * Returns the owner of this property sheet. In most cases this will be the configurable instance which was * instrumented by this property sheet. */ public synchronized Configurable getOwner() { try { if (!isInstanciated()) { owner = ownerClass.newInstance(); owner.newProperties(this); } } catch (IllegalAccessException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't access class " + ownerClass); } catch (InstantiationException e) { throw new InternalConfigurationException(e, getInstanceName(), null, "Can't instantiate class " + ownerClass); } return owner; } /** Returns the class of the owner configurable of this property sheet. */ public Class<? extends Configurable> getConfigurableClass() { return ownerClass; } /** * Sets the given property to the given name * * @param name the simple property name */ public void setString(String name, String value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4String; applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setInt(String name, int value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4Integer; applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setDouble(String name, double value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4Double; applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param value the value for the property */ public void setBoolean(String name, Boolean value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4Boolean; applyConfigurationChange(name, value, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param cmName the name of the configurable within the configuration manager (required for serialization only) * @param value the value for the property */ public void setComponent(String name, String cmName, Configurable value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4Component; applyConfigurationChange(name, cmName, value); } /** * Sets the given property to the given name * * @param name the simple property name * @param valueNames the list of names of the configurables within the configuration manager (required for * serialization only) * @param value the value for the property */ public void setComponentList(String name, List<String> valueNames, List<Configurable> value) throws PropertyException { // ensure that there is such a property assert registeredProperties.keySet().contains(name) : "'" + name + "' is not a registered compontent"; Proxy annotation = registeredProperties.get(name).getAnnotation(); assert annotation instanceof S4ComponentList; // assert valueNames.size() == value.size(); rawProps.put(name, valueNames); propValues.put(name, value); applyConfigurationChange(name, valueNames, value); } private void applyConfigurationChange(String propName, Object cmName, Object value) throws PropertyException { rawProps.put(propName, cmName); propValues.put(propName, value); if (getInstanceName() != null) cm.fireConfChanged(getInstanceName(), propName); if (owner != null) owner.newProperties(this); } /** * Sets the raw property to the given name * * @param key the simple property name * @param val the value for the property */ public void setRaw(String key, Object val) { rawProps.put(key, val); } /** * Gets the raw value associated with this name * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRaw(String name) { return rawProps.get(name); } /** * Gets the raw value associated with this name, no global symbol replacement is performed. * * @param name the name * @return the value as an object (it could be a String or a String[] depending upon the property type) */ public Object getRawNoReplacement(String name) { return rawProps.get(name); } /** Returns the type of the given property. */ public PropertyType getType(String propName) { Proxy annotation = registeredProperties.get(propName).getAnnotation(); if (annotation instanceof S4Component) return PropertyType.COMP; else if (annotation instanceof S4ComponentList) return PropertyType.COMPLIST; else if (annotation instanceof S4Integer) return PropertyType.INT; else if (annotation instanceof S4Double) return PropertyType.DOUBLE; else if (annotation instanceof S4Boolean) return PropertyType.BOOL; else if (annotation instanceof S4String) return PropertyType.STRING; else throw new RuntimeException("Unknown property type"); } /** * Gets the owning property manager * * @return the property manager */ ConfigurationManager getPropertyManager() { return cm; } /** * Returns a logger to use for this configurable component. The logger can be configured with the property: * 'logLevel' - The default logLevel value is defined (within the xml configuration file by the global property * 'defaultLogLevel' (which defaults to WARNING). * <p/> * implementation note: the logger became configured within the constructor of the parenting configuration manager. * * @return the logger for this component * @throws edu.cmu.sphinx.util.props.PropertyException * if an error occurs */ public Logger getLogger() { Logger logger; if (instanceName != null) { logger = Logger.getLogger(ownerClass.getName() + "." + instanceName); } else logger = Logger.getLogger(ownerClass.getName()); // if there's a logLevel set for component apply to the logger if (rawProps.get("logLevel") != null) logger.setLevel(Level.parse((String) rawProps.get("logLevel"))); return logger; } /** Returns the names of registered properties of this PropertySheet object. */ public Collection<String> getRegisteredProperties() { return Collections.unmodifiableCollection(registeredProperties.keySet()); } public void setCM(ConfigurationManager cm) { this.cm = cm; } /** * Returns true if two property sheet define the same object in terms of configuration. The owner (and the parent * configuration manager) are not expected to be the same. */ public boolean equals(Object obj) { if (obj == null || !(obj instanceof PropertySheet)) return false; PropertySheet ps = (PropertySheet) obj; if (!rawProps.keySet().equals(ps.rawProps.keySet())) return false; // maybe we could test a little bit more here. suggestions? return true; } protected Object clone() throws CloneNotSupportedException { PropertySheet ps = (PropertySheet) super.clone(); ps.registeredProperties = new HashMap<String, S4PropWrapper>(this.registeredProperties); ps.propValues = new HashMap<String, Object>(this.propValues); ps.rawProps = new HashMap<String, Object>(this.rawProps); // make deep copy of raw-lists for (String regProp : ps.getRegisteredProperties()) { if (getType(regProp).equals(PropertyType.COMPLIST)) { ps.rawProps.put(regProp, new ArrayList<String>((Collection<? extends String>) rawProps.get(regProp))); ps.propValues.put(regProp, null); } } ps.cm = cm; ps.owner = null; ps.instanceName = this.instanceName; return ps; } /** * use annotation based class parsing to detect the configurable properties of a <code>Configurable</code>-class * * @param propertySheet of type PropertySheet * @param configurable of type Class<? extends Configurable> */ public static void processAnnotations(PropertySheet propertySheet, Class<? extends Configurable> configurable) { Field[] classFields = configurable.getFields(); for (Field field : classFields) { Annotation[] annotations = field.getAnnotations(); for (Annotation annotation : annotations) { Annotation[] superAnnotations = annotation.annotationType().getAnnotations(); for (Annotation superAnnotation : superAnnotations) { if (superAnnotation instanceof S4Property) { int fieldModifiers = field.getModifiers(); assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static"; assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public"; assert field.getType().equals(String.class) : "properties fields are assumed to be instances of java.lang.String"; try { String propertyName = (String) field.get(null); propertySheet.registerProperty(propertyName, new S4PropWrapper((Proxy) annotation)); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } } }
false
true
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); if (propValues.get(name) == null || propValues.get(name) instanceof String) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet((String) propValues.get(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers())) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, assert that it is set if (defClass.equals(Configurable.class)) throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); configurable = ConfigurationManager.getInstance(defClass); assert configurable != null; } } } catch (ClassNotFoundException e) { throw new PropertyException(e); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
public Configurable getComponent(String name) throws PropertyException { S4PropWrapper s4PropWrapper = getProperty(name, S4Component.class); S4Component s4Component = (S4Component) s4PropWrapper.getAnnotation(); Class expectedType = s4Component.type(); if (propValues.get(name) == null || propValues.get(name) instanceof String) { Configurable configurable = null; try { if (propValues.get(name) != null) { PropertySheet ps = cm.getPropertySheet((String) propValues.get(name)); if (ps != null) configurable = ps.getOwner(); } if (configurable != null && !expectedType.isInstance(configurable)) throw new InternalConfigurationException(getInstanceName(), name, "mismatch between annoation and component type"); if (configurable == null) { Class<? extends Configurable> defClass; if (propValues.get(name) != null) defClass = (Class<? extends Configurable>) Class.forName((String) propValues.get(name)); else defClass = s4Component.defaultClass(); if (defClass.equals(Configurable.class) && s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, "mandatory property is not set!"); } else { if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory()) throw new InternalConfigurationException(getInstanceName(), name, defClass.getName() + " is abstract!"); // because we're forced to use the default type, assert that it is set if (defClass.equals(Configurable.class)) { if (s4Component.mandatory()) { throw new InternalConfigurationException(getInstanceName(), name, instanceName + ": no default class defined for " + name); } else { return null; } } configurable = ConfigurationManager.getInstance(defClass); assert configurable != null; } } } catch (ClassNotFoundException e) { throw new PropertyException(e); } propValues.put(name, configurable); } return (Configurable) propValues.get(name); }
diff --git a/src/radlab/rain/workload/httptest/BurstUrlOperation.java b/src/radlab/rain/workload/httptest/BurstUrlOperation.java index 81ebe4b..e01c0a7 100644 --- a/src/radlab/rain/workload/httptest/BurstUrlOperation.java +++ b/src/radlab/rain/workload/httptest/BurstUrlOperation.java @@ -1,95 +1,95 @@ package radlab.rain.workload.httptest; import java.io.IOException; import org.apache.http.HttpStatus; import radlab.rain.Generator; import radlab.rain.IScoreboard; import radlab.rain.LoadProfile; import radlab.rain.Operation; import radlab.rain.util.HttpTransport; public class BurstUrlOperation extends Operation { // These references will be set by the Generator. protected HttpTransport _http; private int _burstSize = 1; public static String NAME = "BurstUrl"; public BurstUrlOperation(boolean interactive, IScoreboard scoreboard) { super(interactive, scoreboard); this._operationName = NAME; this._operationIndex = BurstUrlGenerator.PING_URL; } /** * Returns the Generator that created this operation. * * @return The Generator that created this operation. */ public BurstUrlGenerator getGenerator() { return (BurstUrlGenerator) this._generator; } public void setName( String val ) { this._operationName = val; } @Override public void cleanup() { } @Override public void execute() throws Throwable { // Fetch the base url StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl ); this.trace( this.getGenerator()._baseUrl ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { String errorMessage = "Url GET ERROR - Received an empty/failed response"; throw new IOException (errorMessage); } // Do burst for base url/1 to /burst size for( int i = 0; i < this._burstSize; i++ ) { String url = this.getGenerator()._baseUrl + "/" + (i+1); response = this._http.fetchUrl( url ); this.trace( url ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { - String errorMessage = "Url GET ERROR - Received an empty response"; + String errorMessage = "Url GET ERROR - Received an empty/failed response"; throw new IOException (errorMessage); } } // Once we get here mark the operation as successful this.setFailed( false ); } @Override public void prepare(Generator generator) { this._generator = generator; BurstUrlGenerator specificUrlGenerator = (BurstUrlGenerator) generator; LoadProfile currentLoadProfile = generator.getLatestLoadProfile(); if( currentLoadProfile != null ) this.setGeneratedDuringProfile( currentLoadProfile ); this._http = specificUrlGenerator.getHttpTransport(); // Set the burst count this._burstSize = specificUrlGenerator.getBurstSize(); } }
true
true
public void execute() throws Throwable { // Fetch the base url StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl ); this.trace( this.getGenerator()._baseUrl ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { String errorMessage = "Url GET ERROR - Received an empty/failed response"; throw new IOException (errorMessage); } // Do burst for base url/1 to /burst size for( int i = 0; i < this._burstSize; i++ ) { String url = this.getGenerator()._baseUrl + "/" + (i+1); response = this._http.fetchUrl( url ); this.trace( url ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { String errorMessage = "Url GET ERROR - Received an empty response"; throw new IOException (errorMessage); } } // Once we get here mark the operation as successful this.setFailed( false ); }
public void execute() throws Throwable { // Fetch the base url StringBuilder response = this._http.fetchUrl( this.getGenerator()._baseUrl ); this.trace( this.getGenerator()._baseUrl ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { String errorMessage = "Url GET ERROR - Received an empty/failed response"; throw new IOException (errorMessage); } // Do burst for base url/1 to /burst size for( int i = 0; i < this._burstSize; i++ ) { String url = this.getGenerator()._baseUrl + "/" + (i+1); response = this._http.fetchUrl( url ); this.trace( url ); if( response.length() == 0 || this._http.getStatusCode() != HttpStatus.SC_OK ) { String errorMessage = "Url GET ERROR - Received an empty/failed response"; throw new IOException (errorMessage); } } // Once we get here mark the operation as successful this.setFailed( false ); }
diff --git a/jetty-jboss/src/main/java/org/jboss/jetty/security/JBossIdentityService.java b/jetty-jboss/src/main/java/org/jboss/jetty/security/JBossIdentityService.java index 576193c9b..0d0960abc 100644 --- a/jetty-jboss/src/main/java/org/jboss/jetty/security/JBossIdentityService.java +++ b/jetty-jboss/src/main/java/org/jboss/jetty/security/JBossIdentityService.java @@ -1,128 +1,128 @@ package org.jboss.jetty.security; import java.security.Principal; import java.util.Collections; import java.util.Set; import javax.security.auth.Subject; import org.eclipse.jetty.security.DefaultIdentityService; import org.eclipse.jetty.security.RoleRunAsToken; import org.eclipse.jetty.security.RunAsToken; import org.eclipse.jetty.server.UserIdentity; import org.jboss.logging.Logger; import org.jboss.security.RealmMapping; import org.jboss.security.RunAsIdentity; import org.jboss.security.SecurityAssociation; import org.jboss.security.SimplePrincipal; public class JBossIdentityService extends DefaultIdentityService { private RealmMapping _realmMapping; private Logger _log; public class JBossUserIdentity implements UserIdentity { private Subject _subject; private Principal _principal; public JBossUserIdentity(Subject subject, Principal principal) { _subject = subject; _principal = principal; } public String[] getRoles() { //No equivalent method on JBoss - not needed anyway return null; } public Subject getSubject() { return _subject; } public Principal getUserPrincipal() { return _principal; } - public boolean isUserInRole(String role) + public boolean isUserInRole(String role, UserIdentity.Scope scope) { if (_log.isDebugEnabled()) _log.debug("Checking role "+role+" for user "+_principal.getName()); boolean isUserInRole = false; Set requiredRoles = Collections.singleton(new SimplePrincipal(role)); if (_realmMapping != null && _realmMapping.doesUserHaveRole(this._principal,requiredRoles)) { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is in Role: " + role); isUserInRole = true; } else { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is NOT in Role: " + role); } return isUserInRole; } } public JBossIdentityService (String realmName) { _log = Logger.getLogger(JBossIdentityService.class.getName() + "#"+ realmName); } public void setRealmMapping (RealmMapping realmMapping) { _realmMapping = realmMapping; } public void associate(UserIdentity user) { if (user == null) { if (_log.isDebugEnabled()) _log.debug("Disassociating user "+user); SecurityAssociation.clear(); } else { if (_log.isDebugEnabled()) _log.debug("Associating user "+user); SecurityAssociation.setPrincipal(user.getUserPrincipal()); SecurityAssociation.setCredential(user.getSubject().getPrivateCredentials()); SecurityAssociation.setSubject(user.getSubject()); } } public Object setRunAs(UserIdentity identity, RunAsToken token) { String role = ((RoleRunAsToken)token).getRunAsRole(); String user = (identity==null?null:identity.getUserPrincipal().getName()); RunAsIdentity runAs = new RunAsIdentity(role, user); SecurityAssociation.pushRunAsIdentity(runAs); return null; } public void unsetRunAs(Object lastToken) { SecurityAssociation.popRunAsIdentity(); } public UserIdentity newUserIdentity(Subject subject, Principal userPrincipal, String[] roles) { if (_log.isDebugEnabled()) _log.debug("Creating new JBossUserIdentity for user "+userPrincipal.getName()); return new JBossUserIdentity(subject, userPrincipal); } }
true
true
public boolean isUserInRole(String role) { if (_log.isDebugEnabled()) _log.debug("Checking role "+role+" for user "+_principal.getName()); boolean isUserInRole = false; Set requiredRoles = Collections.singleton(new SimplePrincipal(role)); if (_realmMapping != null && _realmMapping.doesUserHaveRole(this._principal,requiredRoles)) { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is in Role: " + role); isUserInRole = true; } else { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is NOT in Role: " + role); } return isUserInRole; }
public boolean isUserInRole(String role, UserIdentity.Scope scope) { if (_log.isDebugEnabled()) _log.debug("Checking role "+role+" for user "+_principal.getName()); boolean isUserInRole = false; Set requiredRoles = Collections.singleton(new SimplePrincipal(role)); if (_realmMapping != null && _realmMapping.doesUserHaveRole(this._principal,requiredRoles)) { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is in Role: " + role); isUserInRole = true; } else { if (_log.isDebugEnabled()) _log.debug("JBossUserPrincipal: " + _principal + " is NOT in Role: " + role); } return isUserInRole; }
diff --git a/modules/org.restlet/src/org/restlet/resource/ServerResource.java b/modules/org.restlet/src/org/restlet/resource/ServerResource.java index c415e53cf..fee435c76 100644 --- a/modules/org.restlet/src/org/restlet/resource/ServerResource.java +++ b/modules/org.restlet/src/org/restlet/resource/ServerResource.java @@ -1,1667 +1,1673 @@ /** * Copyright 2005-2012 Restlet S.A.S. * * The contents of this file are subject to the terms of one of the following * open source licenses: Apache 2.0 or LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL * 1.0 (the "Licenses"). You can select the license that you prefer but you may * not use this file except in compliance with one of these Licenses. * * You can obtain a copy of the Apache 2.0 license at * http://www.opensource.org/licenses/apache-2.0 * * You can obtain a copy of the LGPL 3.0 license at * http://www.opensource.org/licenses/lgpl-3.0 * * You can obtain a copy of the LGPL 2.1 license at * http://www.opensource.org/licenses/lgpl-2.1 * * You can obtain a copy of the CDDL 1.0 license at * http://www.opensource.org/licenses/cddl1 * * You can obtain a copy of the EPL 1.0 license at * http://www.opensource.org/licenses/eclipse-1.0 * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royalty free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.restlet.com/products/restlet-framework * * Restlet is a registered trademark of Restlet S.A.S. */ package org.restlet.resource; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import org.restlet.Context; import org.restlet.Request; import org.restlet.Response; import org.restlet.Restlet; import org.restlet.Uniform; import org.restlet.data.ChallengeRequest; import org.restlet.data.CookieSetting; import org.restlet.data.Dimension; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Method; import org.restlet.data.Reference; import org.restlet.data.ServerInfo; import org.restlet.data.Status; import org.restlet.engine.resource.AnnotationInfo; import org.restlet.engine.resource.AnnotationUtils; import org.restlet.engine.resource.VariantInfo; import org.restlet.representation.Representation; import org.restlet.representation.RepresentationInfo; import org.restlet.representation.Variant; import org.restlet.routing.Filter; import org.restlet.routing.Router; import org.restlet.util.Series; /** * Base class for server-side resources. It acts as a wrapper to a given call, * including the incoming {@link Request} and the outgoing {@link Response}. <br> * <br> * It's life cycle is managed by a {@link Finder} created either explicitly or * more likely implicitly when your {@link ServerResource} subclass is attached * to a {@link Filter} or a {@link Router} via the {@link Filter#setNext(Class)} * or {@link Router#attach(String, Class)} methods for example. After * instantiation using the default constructor, the final * {@link #init(Context, Request, Response)} method is invoked, setting the * context, request and response. You can intercept this by overriding the * {@link #doInit()} method. Then, if the response status is still a success, * the {@link #handle()} method is invoked to actually handle the call. Finally, * the final {@link #release()} method is invoked to do the necessary clean-up, * which you can intercept by overriding the {@link #doRelease()} method. During * this life cycle, if any exception is caught, then the * {@link #doCatch(Throwable)} method is invoked.<br> * <br> * Note that when an annotated method manually sets the response entity, if this * entity is available then it will be preserved and the result of the annotated * method ignored.<br> * <br> * In addition, there are two ways to declare representation variants, one is * based on the {@link #getVariants()} method and another one on the annotated * methods. Both approaches can't however be used at the same time for now.<br> * <br> * Concurrency note: contrary to the {@link org.restlet.Uniform} class and its * main {@link Restlet} subclass where a single instance can handle several * calls concurrently, one instance of {@link ServerResource} is created for * each call handled and accessed by only one thread at a time. * * @author Jerome Louvel */ @SuppressWarnings("deprecation") public abstract class ServerResource extends UniformResource { /** Indicates if annotations are supported. */ private volatile boolean annotated; /** Indicates if conditional handling is enabled. */ private volatile boolean conditional; /** Indicates if the identified resource exists. */ private volatile boolean existing; /** Indicates if content negotiation of response entities is enabled. */ private volatile boolean negotiated; /** Modifiable list of variants. */ private volatile List<Variant> variants; /** * Initializer block to ensure that the basic properties are initialized * consistently across constructors. */ { this.annotated = true; this.conditional = true; this.existing = true; this.negotiated = true; this.variants = null; } /** * Default constructor. Note that the * {@link #init(Context, Request, Response)}() method will be invoked right * after the creation of the resource. */ public ServerResource() { } /** * Ask the connector to abort the related network connection, for example * immediately closing the socket. */ public void abort() { getResponse().abort(); } /** * Asks the response to immediately commit making it ready to be sent back * to the client. Note that all server connectors don't necessarily support * this feature. */ public void commit() { getResponse().commit(); } /** * Deletes the resource and all its representations. This method is only * invoked if content negotiation has been disabled as indicated by the * {@link #isNegotiated()}, otherwise the {@link #delete(Variant)} method is * invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The optional response entity. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7" * >HTTP DELETE method</a> */ protected Representation delete() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.DELETE); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Deletes the resource and all its representations. A variant parameter is * passed to indicate which representation should be returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #delete()} * method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param variant * The variant of the response entity. * @return The optional response entity. * @throws ResourceException * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7" * >HTTP DELETE method</a> */ protected Representation delete(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Describes the available variants to help client-side content negotiation. * Return null by default. * * @return The description of available variants. */ protected Representation describeVariants() { Representation result = null; // The list of all variants is transmitted to the client // final ReferenceList refs = new ReferenceList(variants.size()); // for (final Variant variant : variants) { // if (variant.getIdentifier() != null) { // refs.add(variant.getIdentifier()); // } // } // // result = refs.getTextRepresentation(); return result; } /** * Invoked when an error or an exception is caught during initialization, * handling or releasing. By default, updates the responses's status with * the result of * {@link org.restlet.service.StatusService#getStatus(Throwable, Resource)} * . * * @param throwable * The caught error or exception. */ protected void doCatch(Throwable throwable) { Level level = Level.INFO; Status status = getStatusService().getStatus(throwable, this); if (status.isServerError()) { level = Level.WARNING; } else if (status.isConnectorError()) { level = Level.INFO; } else if (status.isClientError()) { level = Level.FINE; } getLogger().log(level, "Exception or error caught in server resource", throwable); if (getResponse() != null) { getResponse().setStatus(status); } } /** * Handles a call by first verifying the optional request conditions and * continue the processing if possible. Note that in order to evaluate those * conditions, {@link #getInfo()} or {@link #getInfo(Variant)} methods might * be invoked. * * @return The response entity. * @throws ResourceException */ protected Representation doConditionalHandle() throws ResourceException { Representation result = null; if (getConditions().hasSome()) { RepresentationInfo resultInfo = null; if (existing) { if (isNegotiated()) { - resultInfo = doGetInfo(getPreferredVariant(getVariants(Method.GET))); + Variant preferredVariant = getPreferredVariant(getVariants(Method.GET)); + if (preferredVariant == null + && getConnegService().isStrict()) { + doError(Status.CLIENT_ERROR_NOT_ACCEPTABLE); + } else { + resultInfo = doGetInfo(preferredVariant); + } } else { resultInfo = doGetInfo(); } if (resultInfo == null) { if ((getStatus() == null) || (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getStatus()))) { doError(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer // a special status like 'method not authorized'. } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } if ((Method.GET.equals(getMethod()) || Method.HEAD .equals(getMethod())) && resultInfo instanceof Representation) { result = (Representation) resultInfo; } else if ((getStatus() != null) && getStatus().isSuccess()) { // Conditions were passed successfully, continue the normal // processing. if (isNegotiated()) { // Reset the list of variants, as the method differs. getVariants().clear(); result = doNegotiatedHandle(); } else { result = doHandle(); } } } else { if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } } return result; } /** * By default, it sets the status on the response. */ @Override protected void doError(Status errorStatus) { setStatus(errorStatus); } /** * Returns a descriptor of the response entity returned by a * {@link Method#GET} call. * * @return The response entity. * @throws ResourceException */ private RepresentationInfo doGetInfo() throws ResourceException { RepresentationInfo result = null; AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { result = getInfo(); } return result; } /** * Returns a descriptor of the response entity returned by a negotiated * {@link Method#GET} call. * * @param variant * The selected variant descriptor. * @return The response entity descriptor. * @throws ResourceException */ private RepresentationInfo doGetInfo(Variant variant) throws ResourceException { RepresentationInfo result = null; if (variant != null) { if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else if (variant instanceof RepresentationInfo) { result = (RepresentationInfo) variant; } else { result = getInfo(variant); } } else { result = doGetInfo(); } return result; } /** * Effectively handles a call without content negotiation of the response * entity. The default behavior is to dispatch the call to one of the * {@link #get()}, {@link #post(Representation)}, * {@link #put(Representation)}, {@link #delete()}, {@link #head()} or * {@link #options()} methods. * * @return The response entity. * @throws ResourceException */ protected Representation doHandle() throws ResourceException { Representation result = null; Method method = getMethod(); if (method == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (method.equals(Method.PUT)) { result = put(getRequestEntity()); } else if (isExisting()) { if (method.equals(Method.GET)) { result = get(); } else if (method.equals(Method.POST)) { result = post(getRequestEntity()); } else if (method.equals(Method.DELETE)) { result = delete(); } else if (method.equals(Method.HEAD)) { result = head(); } else if (method.equals(Method.OPTIONS)) { result = options(); } else { result = doHandle(method, getQuery(), getRequestEntity()); } } else { doError(Status.CLIENT_ERROR_NOT_FOUND); } } return result; } /** * Effectively handles a call with content negotiation of the response * entity using an annotated method. * * @param annotationInfo * The annotation descriptor. * @param variant * The response variant expected (can be null). * @return The response entity. * @throws ResourceException */ private Representation doHandle(AnnotationInfo annotationInfo, Variant variant) throws ResourceException { Representation result = null; Class<?>[] parameterTypes = annotationInfo.getJavaInputTypes(); // Invoke the annotated method and get the resulting object. Object resultObject = null; try { if (parameterTypes.length > 0) { List<Object> parameters = new ArrayList<Object>(); Object parameter = null; for (Class<?> parameterType : parameterTypes) { if (Variant.class.equals(parameterType)) { parameters.add(variant); } else { if (getRequestEntity() != null && getRequestEntity().isAvailable() && getRequestEntity().getSize() != 0) { // Assume there is content to be read. // NB: it does not handle the case where the size is // unknown, but there is no content. parameter = toObject(getRequestEntity(), parameterType); if (parameter == null) { throw new ResourceException( Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } } else { parameter = null; } parameters.add(parameter); } } resultObject = annotationInfo.getJavaMethod().invoke(this, parameters.toArray()); } else { resultObject = annotationInfo.getJavaMethod().invoke(this); } } catch (IllegalArgumentException e) { throw new ResourceException(e); } catch (IllegalAccessException e) { throw new ResourceException(e); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ResourceException) { throw (ResourceException) e.getTargetException(); } throw new ResourceException(e.getTargetException()); } if (resultObject != null) { result = toRepresentation(resultObject, variant); } return result; } /** * Handles a call and checks the request's method and entity. If the method * is not supported, the response status is set to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. If the request's entity * is no supported, the response status is set to * {@link Status#CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE}. * * @param method * The request method. * @param query * The query parameters. * @param entity * The request entity (can be null, or unavailable). * @return The response entity. * @throws ResourceException */ private Representation doHandle(Method method, Form query, Representation entity) { Representation result = null; if (getAnnotation(method) != null) { // We know the method is supported, let's check the entity. AnnotationInfo annotationInfo = getAnnotation(method, query, entity); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { // The request entity is not supported. doError(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE); } } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Effectively handles a call with content negotiation of the response * entity. The default behavior is to dispatch the call to one of the * {@link #get(Variant)}, {@link #post(Representation,Variant)}, * {@link #put(Representation,Variant)}, {@link #delete(Variant)}, * {@link #head(Variant)} or {@link #options(Variant)} methods. * * @param variant * The response variant expected. * @return The response entity. * @throws ResourceException */ protected Representation doHandle(Variant variant) throws ResourceException { Representation result = null; Method method = getMethod(); if (method == null) { setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "No method specified"); } else { if (method.equals(Method.PUT)) { result = put(getRequestEntity(), variant); } else if (isExisting()) { if (method.equals(Method.GET)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = get(variant); } } else if (method.equals(Method.POST)) { result = post(getRequestEntity(), variant); } else if (method.equals(Method.DELETE)) { result = delete(variant); } else if (method.equals(Method.HEAD)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = head(variant); } } else if (method.equals(Method.OPTIONS)) { if (variant instanceof Representation) { result = (Representation) variant; } else { result = options(variant); } } else if (variant instanceof VariantInfo) { result = doHandle( ((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } } else { doError(Status.CLIENT_ERROR_NOT_FOUND); } } return result; } /** * Effectively handles a call with content negotiation of the response * entity. The default behavior is to dispatch the call to call a matching * annotated method or one of the {@link #get(Variant)}, * {@link #post(Representation,Variant)}, * {@link #put(Representation,Variant)}, {@link #delete(Variant)}, * {@link #head(Variant)} or {@link #options(Variant)} methods.<br> * <br> * If no acceptable variant is found, the * {@link Status#CLIENT_ERROR_NOT_ACCEPTABLE} status is set. * * @return The response entity. * @throws ResourceException */ protected Representation doNegotiatedHandle() throws ResourceException { Representation result = null; if ((getVariants() != null) && (!getVariants().isEmpty())) { Variant preferredVariant = getPreferredVariant(getVariants()); if (preferredVariant == null) { // No variant was found matching the client preferences doError(Status.CLIENT_ERROR_NOT_ACCEPTABLE); result = describeVariants(); } else { // Update the variant dimensions used for content negotiation updateDimensions(); result = doHandle(preferredVariant); } } else { // No variant declared for this method. result = doHandle(); } return result; } /** * Returns a full representation. This method is only invoked if content * negotiation has been disabled as indicated by the {@link #isNegotiated()} * , otherwise the {@link #get(Variant)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The resource's representation. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP * GET method</a> */ protected Representation get() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.GET); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Returns a full representation for a given variant. A variant parameter is * passed to indicate which representation should be returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #get()} * method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br> * * @param variant * The variant whose full representation must be returned. * @return The resource's representation. * @see #get(Variant) * @throws ResourceException */ protected Representation get(Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Returns the first annotation descriptor matching the given method. * * @param method * The method to match. * @return The annotation descriptor. */ private AnnotationInfo getAnnotation(Method method) { return getAnnotation(method, getQuery(), null); } /** * Returns the first annotation descriptor matching the given method. * * @param method * The method to match. * @param query * The query parameters. * @param entity * The request entity or null. * @return The annotation descriptor. */ private AnnotationInfo getAnnotation(Method method, Form query, Representation entity) { if (isAnnotated()) { return AnnotationUtils.getInstance().getAnnotation( getAnnotations(), method, query, entity, getMetadataService(), getConverterService()); } return null; } /** * Returns the annotation descriptors. * * @return The annotation descriptors. */ private List<AnnotationInfo> getAnnotations() { return isAnnotated() ? AnnotationUtils.getInstance().getAnnotations( getClass()) : null; } /** * Returns the attribute value by looking up the given name in the response * attributes maps. The toString() method is then invoked on the attribute * value. * * @param name * The attribute name. * @return The response attribute value. */ public String getAttribute(String name) { Object value = getResponseAttributes().get(name); return (value == null) ? null : value.toString(); } /** * Returns information about the resource's representation. Those metadata * are important for conditional method processing. The advantage over the * complete {@link Representation} class is that it is much lighter to * create. This method is only invoked if content negotiation has been * disabled as indicated by the {@link #isNegotiated()}, otherwise the * {@link #getInfo(Variant)} method is invoked.<br> * <br> * The default behavior is to invoke the {@link #get()} method. * * @return Information about the resource's representation. * @throws ResourceException */ protected RepresentationInfo getInfo() throws ResourceException { return get(); } /** * Returns information about the resource's representation. Those metadata * are important for conditional method processing. The advantage over the * complete {@link Representation} class is that it is much lighter to * create. A variant parameter is passed to indicate which representation * should be returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #getInfo(Variant)} method is invoked.<br> * <br> * The default behavior is to invoke the {@link #get(Variant)} method. * * @param variant * The variant whose representation information must be returned. * @return Information about the resource's representation. * @throws ResourceException */ protected RepresentationInfo getInfo(Variant variant) throws ResourceException { return get(variant); } /** * Returns the callback invoked after sending the response. * * @return The callback invoked after sending the response. */ public Uniform getOnSent() { return getResponse().getOnSent(); } /** * Returns the preferred variant among a list of available variants. The * selection is based on the client preferences using the * {@link org.restlet.service.ConnegService#getPreferredVariant(List, Request, org.restlet.service.MetadataService)} * method. * * @param variants * The available variants. * @return The preferred variant. */ protected Variant getPreferredVariant(List<Variant> variants) { Variant result = null; // If variants were found, select the best matching one if ((variants != null) && (!variants.isEmpty())) { result = getConnegService().getPreferredVariant(variants, getRequest(), getMetadataService()); } return result; } /** * Returns a modifiable list of exposed variants for the current request * method. You can declare variants manually by updating the result list , * by overriding this method. By default, the variants will be provided * based on annotated methods. * * @return The modifiable list of variants. */ public List<Variant> getVariants() { return getVariants(getMethod()); } /** * Returns a modifiable list of exposed variants for the given method. You * can declare variants manually by updating the result list , by overriding * this method. By default, the variants will be provided based on annotated * methods. * * @param method * The method. * @return The modifiable list of variants. */ protected List<Variant> getVariants(Method method) { List<Variant> result = this.variants; if (result == null) { result = new ArrayList<Variant>(); // Add annotation-based variants in priority if (isAnnotated() && hasAnnotations()) { List<Variant> annoVariants = null; method = (Method.HEAD.equals(method)) ? Method.GET : method; for (AnnotationInfo annotationInfo : getAnnotations()) { if (annotationInfo.isCompatible(method, getQuery(), getRequestEntity(), getMetadataService(), getConverterService())) { annoVariants = annotationInfo.getResponseVariants( getMetadataService(), getConverterService()); if (annoVariants != null) { // Compute an affinity score between this annotation // and the input entity. float score = 0.5f; if ((getRequest().getEntity() != null) && getRequest().getEntity().isAvailable()) { MediaType emt = getRequest().getEntity() .getMediaType(); List<MediaType> amts = getMetadataService() .getAllMediaTypes( annotationInfo.getInput()); if (amts != null) { for (MediaType amt : amts) { if (amt.equals(emt)) { score = 1.0f; } else if (amt.includes(emt)) { score = Math.max(0.8f, score); } else if (amt.isCompatible(emt)) { score = Math.max(0.6f, score); } } } } for (Variant v : annoVariants) { VariantInfo vi = new VariantInfo(v, annotationInfo); vi.setInputScore(score); result.add(vi); } } } } } this.variants = result; } return result; } /** * Handles any call to this resource. The default implementation check the * {@link #isConditional()} and {@link #isNegotiated()} method to determine * which one of the {@link #doConditionalHandle()}, * {@link #doNegotiatedHandle()} and {@link #doHandle()} methods should be * invoked. It also catches any {@link ResourceException} thrown and updates * the response status using the * {@link #setStatus(Status, Throwable, String)} method.<br> * <br> * After handling, if the status is set to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}, then * {@link #updateAllowedMethods()} is invoked to give the resource a chance * to inform the client about the allowed methods. * * @return The response entity. */ @Override public Representation handle() { Representation result = null; // If the resource is not available after initialization and if this a // retrieval method, then return a "not found" response. if (!isExisting() && getMethod().isSafe()) { doError(Status.CLIENT_ERROR_NOT_FOUND); } else { try { if (isConditional()) { result = doConditionalHandle(); } else if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } if (!getResponse().isEntityAvailable()) { // If the user manually set the entity, keep it getResponse().setEntity(result); } if (Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus())) { updateAllowedMethods(); } else if (Method.GET.equals(getMethod()) && Status.SUCCESS_OK.equals(getStatus()) && (getResponseEntity() == null || !getResponseEntity() .isAvailable())) { getLogger() .fine("A response with a 200 (Ok) status should have an entity. Changing the status to 204 (No content)."); setStatus(Status.SUCCESS_NO_CONTENT); } } catch (Throwable t) { doCatch(t); } } return result; } /** * Indicates if annotations were defined on this resource. * * @return True if annotations were defined on this resource. */ protected boolean hasAnnotations() { return (getAnnotations() != null) && (!getAnnotations().isEmpty()); } /** * Returns a representation whose metadata will be returned to the client. * This method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #head(Variant)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The resource's representation. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3">HTTP * GET method</a> */ protected Representation head() throws ResourceException { return get(); } /** * Returns a representation whose metadata will be returned to the client. A * variant parameter is passed to indicate which representation should be * returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the {@link #head()} * method is invoked.<br> * <br> * The default implementation directly returns the variant if it is already * an instance of {@link Representation}. In other cases, you need to * override this method in order to provide your own implementation. * * * @param variant * The variant whose full representation must be returned. * @return The resource's representation. * @see #get(Variant) * @throws ResourceException */ protected Representation head(Variant variant) throws ResourceException { return get(variant); } /** * Indicates if annotations are supported. The default value is true. * * @return True if annotations are supported. */ public boolean isAnnotated() { return annotated; } /** * Indicates if the response should be automatically committed. When * processing a request on the server-side, setting this property to 'false' * let you ask to the server connector to wait before sending the response * back to the client when the initial calling thread returns. This will let * you do further updates to the response and manually calling * {@link #commit()} later on, using another thread. * * @return True if the response should be automatically committed. */ public boolean isAutoCommitting() { return getResponse().isAutoCommitting(); } /** * Indicates if the response has already been committed. * * @return True if the response has already been committed. */ public boolean isCommitted() { return getResponse().isCommitted(); } /** * Indicates if conditional handling is enabled. The default value is true. * * @return True if conditional handling is enabled. */ public boolean isConditional() { return conditional; } /** * Indicates if the identified resource exists. The default value is true. * * @return True if the identified resource exists. */ public boolean isExisting() { return existing; } /** * Indicates if the authenticated client user associated to the current * request is in the given role name. * * @param roleName * The role name to test. * @return True if the authenticated subject is in the given role. */ public boolean isInRole(String roleName) { return getClientInfo().getRoles().contains( getApplication().getRole(roleName)); } /** * Indicates if content negotiation of response entities is enabled. The * default value is true. * * @return True if content negotiation of response entities is enabled. */ public boolean isNegotiated() { return this.negotiated; } /** * Indicates the communication options available for this resource. This * method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #options(Variant)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @return The optional response entity. */ protected Representation options() throws ResourceException { Representation result = null; AnnotationInfo annotationInfo = getAnnotation(Method.OPTIONS); // Updates the list of allowed methods updateAllowedMethods(); if (annotationInfo != null) { result = doHandle(annotationInfo, null); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Indicates the communication options available for this resource. A * variant parameter is passed to indicate which representation should be * returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #options()} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br> * * @param variant * The variant of the response entity. * @return The optional response entity. * @see #get(Variant) */ protected Representation options(Variant variant) throws ResourceException { Representation result = null; // Updates the list of allowed methods updateAllowedMethods(); if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Posts a representation to the resource at the target URI reference. This * method is only invoked if content negotiation has been disabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #post(Representation, Variant)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param entity * The posted entity. * @return The optional response entity. * @throws ResourceException * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5">HTTP * POST method</a> */ protected Representation post(Representation entity) throws ResourceException { return doHandle(Method.POST, getQuery(), entity); } /** * Posts a representation to the resource at the target URI reference. A * variant parameter is passed to indicate which representation should be * returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #post(Representation)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br> * * @param entity * The posted entity. * @param variant * The variant of the response entity. * @return The optional result entity. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5" * >HTTP POST method</a> */ protected Representation post(Representation entity, Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Creates or updates a resource with the given representation as new state * to be stored. This method is only invoked if content negotiation has been * disabled as indicated by the {@link #isNegotiated()}, otherwise the * {@link #put(Representation, Variant)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}. * * @param entity * The representation to store. * @return The optional result entity. * @throws ResourceException * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6">HTTP * PUT method</a> */ protected Representation put(Representation entity) throws ResourceException { return doHandle(Method.PUT, getQuery(), entity); } /** * Creates or updates a resource with the given representation as new state * to be stored. A variant parameter is passed to indicate which * representation should be returned if any.<br> * <br> * This method is only invoked if content negotiation has been enabled as * indicated by the {@link #isNegotiated()}, otherwise the * {@link #put(Representation)} method is invoked.<br> * <br> * The default behavior is to set the response status to * {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}.<br> * * @param representation * The representation to store. * @param variant * The variant of the response entity. * @return The optional result entity. * @throws ResourceException * @see #get(Variant) * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6" * >HTTP PUT method</a> */ protected Representation put(Representation representation, Variant variant) throws ResourceException { Representation result = null; if (variant instanceof VariantInfo) { result = doHandle(((VariantInfo) variant).getAnnotationInfo(), variant); } else { doError(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED); } return result; } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target URI reference. */ public void redirectPermanent(Reference targetRef) { if (getResponse() != null) { getResponse().redirectPermanent(targetRef); } } /** * Permanently redirects the client to a target URI. The client is expected * to reuse the same method for the new request.<br> * <br> * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectPermanent(String targetUri) { if (getResponse() != null) { getResponse().redirectPermanent(targetUri); } } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource. * * @param targetRef * The target reference. */ public void redirectSeeOther(Reference targetRef) { if (getResponse() != null) { getResponse().redirectSeeOther(targetRef); } } /** * Redirects the client to a different URI that SHOULD be retrieved using a * GET method on that resource. This method exists primarily to allow the * output of a POST-activated script to redirect the user agent to a * selected resource. The new URI is not a substitute reference for the * originally requested resource.<br> * <br> * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectSeeOther(String targetUri) { if (getResponse() != null) { getResponse().redirectSeeOther(targetUri); } } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request. * * @param targetRef * The target reference. */ public void redirectTemporary(Reference targetRef) { if (getResponse() != null) { getResponse().redirectTemporary(targetRef); } } /** * Temporarily redirects the client to a target URI. The client is expected * to reuse the same method for the new request.<br> * <br> * If you pass a relative target URI, it will be resolved with the current * base reference of the request's resource reference (see * {@link Request#getResourceRef()} and {@link Reference#getBaseRef()}. * * @param targetUri * The target URI. */ public void redirectTemporary(String targetUri) { if (getResponse() != null) { getResponse().redirectTemporary(targetUri); } } /** * Sets the set of methods allowed on the requested resource. The set * instance set must be thread-safe (use {@link CopyOnWriteArraySet} for * example. * * @param allowedMethods * The set of methods allowed on the requested resource. * @see Response#setAllowedMethods(Set) */ public void setAllowedMethods(Set<Method> allowedMethods) { if (getResponse() != null) { getResponse().setAllowedMethods(allowedMethods); } } /** * Indicates if annotations are supported. The default value is true. * * @param annotated * Indicates if annotations are supported. */ public void setAnnotated(boolean annotated) { this.annotated = annotated; } /** * Sets the response attribute value. * * @param name * The attribute name. * @param value * The attribute to set. */ public void setAttribute(String name, Object value) { getResponseAttributes().put(name, value); } /** * Indicates if the response should be automatically committed. * * @param autoCommitting * True if the response should be automatically committed */ public void setAutoCommitting(boolean autoCommitting) { getResponse().setAutoCommitting(autoCommitting); } /** * Sets the list of authentication requests sent by an origin server to a * client. The list instance set must be thread-safe (use * {@link CopyOnWriteArrayList} for example. * * @param requests * The list of authentication requests sent by an origin server * to a client. * @see Response#setChallengeRequests(List) */ public void setChallengeRequests(List<ChallengeRequest> requests) { if (getResponse() != null) { getResponse().setChallengeRequests(requests); } } /** * Indicates if the response has already been committed. * * @param committed * True if the response has already been committed. */ public void setCommitted(boolean committed) { getResponse().setCommitted(committed); } /** * Indicates if conditional handling is enabled. The default value is true. * * @param conditional * True if conditional handling is enabled. */ public void setConditional(boolean conditional) { this.conditional = conditional; } /** * Sets the cookie settings provided by the server. * * @param cookieSettings * The cookie settings provided by the server. * @see Response#setCookieSettings(Series) */ public void setCookieSettings(Series<CookieSetting> cookieSettings) { if (getResponse() != null) { getResponse().setCookieSettings(cookieSettings); } } /** * Sets the set of dimensions on which the response entity may vary. The set * instance set must be thread-safe (use {@link CopyOnWriteArraySet} for * example. * * @param dimensions * The set of dimensions on which the response entity may vary. * @see Response#setDimensions(Set) */ public void setDimensions(Set<Dimension> dimensions) { if (getResponse() != null) { getResponse().setDimensions(dimensions); } } /** * Indicates if the identified resource exists. The default value is true. * * @param exists * Indicates if the identified resource exists. */ public void setExisting(boolean exists) { this.existing = exists; } /** * Sets the reference that the client should follow for redirections or * resource creations. * * @param locationRef * The reference to set. * @see Response#setLocationRef(Reference) */ public void setLocationRef(Reference locationRef) { if (getResponse() != null) { getResponse().setLocationRef(locationRef); } } /** * Sets the reference that the client should follow for redirections or * resource creations. If you pass a relative location URI, it will be * resolved with the current base reference of the request's resource * reference (see {@link Request#getResourceRef()} and * {@link Reference#getBaseRef()}. * * @param locationUri * The URI to set. * @see Response#setLocationRef(String) */ public void setLocationRef(String locationUri) { if (getResponse() != null) { getResponse().setLocationRef(locationUri); } } /** * Indicates if content negotiation of response entities is enabled. The * default value is true. * * @param negotiateContent * True if content negotiation of response entities is enabled. */ public void setNegotiated(boolean negotiateContent) { this.negotiated = negotiateContent; } /** * Sets the callback invoked after sending the response. * * @param onSentCallback * The callback invoked after sending the response. */ public void setOnSent(Uniform onSentCallback) { getResponse().setOnSent(onSentCallback); } /** * Sets the list of proxy authentication requests sent by an origin server * to a client. The list instance set must be thread-safe (use * {@link CopyOnWriteArrayList} for example. * * @param requests * The list of proxy authentication requests sent by an origin * server to a client. * @see Response#setProxyChallengeRequests(List) */ public void setProxyChallengeRequests(List<ChallengeRequest> requests) { if (getResponse() != null) { getResponse().setProxyChallengeRequests(requests); } } /** * Sets the server-specific information. * * @param serverInfo * The server-specific information. * @see Response#setServerInfo(ServerInfo) */ public void setServerInfo(ServerInfo serverInfo) { if (getResponse() != null) { getResponse().setServerInfo(serverInfo); } } /** * Sets the status. * * @param status * The status to set. * @see Response#setStatus(Status) */ public void setStatus(Status status) { if (getResponse() != null) { getResponse().setStatus(status); } } /** * Sets the status. * * @param status * The status to set. * @param message * The status message. * @see Response#setStatus(Status, String) */ public void setStatus(Status status, String message) { if (getResponse() != null) { getResponse().setStatus(status, message); } } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. * @see Response#setStatus(Status, Throwable) */ public void setStatus(Status status, Throwable throwable) { if (getResponse() != null) { getResponse().setStatus(status, throwable); } } /** * Sets the status. * * @param status * The status to set. * @param throwable * The related error or exception. * @param message * The status message. * @see Response#setStatus(Status, Throwable, String) */ public void setStatus(Status status, Throwable throwable, String message) { if (getResponse() != null) { getResponse().setStatus(status, throwable, message); } } /** * Invoked when the list of allowed methods needs to be updated. The * {@link #getAllowedMethods()} or the {@link #setAllowedMethods(Set)} * methods should be used. The default implementation lists the annotated * methods. */ public void updateAllowedMethods() { getAllowedMethods().clear(); List<AnnotationInfo> annotations = getAnnotations(); if (annotations != null) { for (AnnotationInfo annotationInfo : annotations) { if (!getAllowedMethods().contains( annotationInfo.getRestletMethod())) { getAllowedMethods().add(annotationInfo.getRestletMethod()); } } } } /** * Update the dimensions that were used for content negotiation. By default, * it adds the {@link Dimension#CHARACTER_SET}, {@link Dimension#ENCODING}, * {@link Dimension#LANGUAGE}and {@link Dimension#MEDIA_TYPE} constants. */ protected void updateDimensions() { getDimensions().add(Dimension.CHARACTER_SET); getDimensions().add(Dimension.ENCODING); getDimensions().add(Dimension.LANGUAGE); getDimensions().add(Dimension.MEDIA_TYPE); } }
true
true
protected Representation doConditionalHandle() throws ResourceException { Representation result = null; if (getConditions().hasSome()) { RepresentationInfo resultInfo = null; if (existing) { if (isNegotiated()) { resultInfo = doGetInfo(getPreferredVariant(getVariants(Method.GET))); } else { resultInfo = doGetInfo(); } if (resultInfo == null) { if ((getStatus() == null) || (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getStatus()))) { doError(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer // a special status like 'method not authorized'. } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } if ((Method.GET.equals(getMethod()) || Method.HEAD .equals(getMethod())) && resultInfo instanceof Representation) { result = (Representation) resultInfo; } else if ((getStatus() != null) && getStatus().isSuccess()) { // Conditions were passed successfully, continue the normal // processing. if (isNegotiated()) { // Reset the list of variants, as the method differs. getVariants().clear(); result = doNegotiatedHandle(); } else { result = doHandle(); } } } else { if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } } return result; }
protected Representation doConditionalHandle() throws ResourceException { Representation result = null; if (getConditions().hasSome()) { RepresentationInfo resultInfo = null; if (existing) { if (isNegotiated()) { Variant preferredVariant = getPreferredVariant(getVariants(Method.GET)); if (preferredVariant == null && getConnegService().isStrict()) { doError(Status.CLIENT_ERROR_NOT_ACCEPTABLE); } else { resultInfo = doGetInfo(preferredVariant); } } else { resultInfo = doGetInfo(); } if (resultInfo == null) { if ((getStatus() == null) || (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT .equals(getStatus()))) { doError(Status.CLIENT_ERROR_NOT_FOUND); } else { // Keep the current status as the developer might prefer // a special status like 'method not authorized'. } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } } else { Status status = getConditions().getStatus(getMethod(), resultInfo); if (status != null) { if (status.isError()) { doError(status); } else { setStatus(status); } } } if ((Method.GET.equals(getMethod()) || Method.HEAD .equals(getMethod())) && resultInfo instanceof Representation) { result = (Representation) resultInfo; } else if ((getStatus() != null) && getStatus().isSuccess()) { // Conditions were passed successfully, continue the normal // processing. if (isNegotiated()) { // Reset the list of variants, as the method differs. getVariants().clear(); result = doNegotiatedHandle(); } else { result = doHandle(); } } } else { if (isNegotiated()) { result = doNegotiatedHandle(); } else { result = doHandle(); } } return result; }
diff --git a/src/com/android/settings/DeviceInfoSettings.java b/src/com/android/settings/DeviceInfoSettings.java index be01f7dc5..7768b7dc7 100644 --- a/src/com/android/settings/DeviceInfoSettings.java +++ b/src/com/android/settings/DeviceInfoSettings.java @@ -1,153 +1,153 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Build; import android.os.Bundle; import android.os.SystemProperties; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.util.Config; import android.util.Log; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DeviceInfoSettings extends PreferenceActivity { private static final String TAG = "DeviceInfoSettings"; private static final boolean LOGD = false || Config.LOGD; private static final String KEY_CONTAINER = "container"; private static final String KEY_TEAM = "team"; private static final String KEY_CONTRIBUTORS = "contributors"; private static final String KEY_TERMS = "terms"; private static final String KEY_LICENSE = "license"; private static final String KEY_COPYRIGHT = "copyright"; private static final String KEY_SYSTEM_UPDATE_SETTINGS = "system_update_settings"; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.device_info_settings); setStringSummary("firmware_version", Build.VERSION.RELEASE); setValueSummary("baseband_version", "gsm.version.baseband"); setStringSummary("device_model", Build.MODEL); setStringSummary("build_number", Build.DISPLAY); findPreference("kernel_version").setSummary(getFormattedKernelVersion()); /* * Settings is a generic app and should not contain any device-specific * info. */ // These are contained in the "container" preference group PreferenceGroup parentPreference = (PreferenceGroup) findPreference(KEY_CONTAINER); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_TERMS, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_LICENSE, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_COPYRIGHT, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_TEAM, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); // These are contained by the root preference screen parentPreference = getPreferenceScreen(); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_SYSTEM_UPDATE_SETTINGS, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); Utils.updatePreferenceToSpecificActivityOrRemove(this, parentPreference, KEY_CONTRIBUTORS, Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY); } private void setStringSummary(String preference, String value) { try { findPreference(preference).setSummary(value); } catch (RuntimeException e) { findPreference(preference).setSummary( getResources().getString(R.string.device_info_default)); } } private void setValueSummary(String preference, String property) { try { findPreference(preference).setSummary( SystemProperties.get(property, getResources().getString(R.string.device_info_default))); } catch (RuntimeException e) { } } private String getFormattedKernelVersion() { String procVersionStr; try { BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 256); try { procVersionStr = reader.readLine(); } finally { reader.close(); } final String PROC_VERSION_REGEX = "\\w+\\s+" + /* ignore: Linux */ "\\w+\\s+" + /* ignore: version */ "([^\\s]+)\\s+" + /* group 1: 2.6.22-omap1 */ "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+" + /* group 2: ([email protected]) */ - "\\([^)]+\\)\\s+" + /* ignore: (gcc ..) */ + "\\(.*?(?:\\(.*?\\)).*?\\)\\s+" + /* ignore: (gcc ..) */ "([^\\s]+)\\s+" + /* group 3: #26 */ "(?:PREEMPT\\s+)?" + /* ignore: PREEMPT (optional) */ "(.+)"; /* group 4: date */ Pattern p = Pattern.compile(PROC_VERSION_REGEX); Matcher m = p.matcher(procVersionStr); if (!m.matches()) { Log.e(TAG, "Regex did not match on /proc/version: " + procVersionStr); return "Unavailable"; } else if (m.groupCount() < 4) { Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount() + " groups"); return "Unavailable"; } else { return (new StringBuilder(m.group(1)).append("\n").append( m.group(2)).append(" ").append(m.group(3)).append("\n") .append(m.group(4))).toString(); } } catch (IOException e) { Log.e(TAG, "IO Exception when getting kernel version for Device Info screen", e); return "Unavailable"; } } }
true
true
private String getFormattedKernelVersion() { String procVersionStr; try { BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 256); try { procVersionStr = reader.readLine(); } finally { reader.close(); } final String PROC_VERSION_REGEX = "\\w+\\s+" + /* ignore: Linux */ "\\w+\\s+" + /* ignore: version */ "([^\\s]+)\\s+" + /* group 1: 2.6.22-omap1 */ "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+" + /* group 2: ([email protected]) */ "\\([^)]+\\)\\s+" + /* ignore: (gcc ..) */ "([^\\s]+)\\s+" + /* group 3: #26 */ "(?:PREEMPT\\s+)?" + /* ignore: PREEMPT (optional) */ "(.+)"; /* group 4: date */ Pattern p = Pattern.compile(PROC_VERSION_REGEX); Matcher m = p.matcher(procVersionStr); if (!m.matches()) { Log.e(TAG, "Regex did not match on /proc/version: " + procVersionStr); return "Unavailable"; } else if (m.groupCount() < 4) { Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount() + " groups"); return "Unavailable"; } else { return (new StringBuilder(m.group(1)).append("\n").append( m.group(2)).append(" ").append(m.group(3)).append("\n") .append(m.group(4))).toString(); } } catch (IOException e) { Log.e(TAG, "IO Exception when getting kernel version for Device Info screen", e); return "Unavailable"; } }
private String getFormattedKernelVersion() { String procVersionStr; try { BufferedReader reader = new BufferedReader(new FileReader("/proc/version"), 256); try { procVersionStr = reader.readLine(); } finally { reader.close(); } final String PROC_VERSION_REGEX = "\\w+\\s+" + /* ignore: Linux */ "\\w+\\s+" + /* ignore: version */ "([^\\s]+)\\s+" + /* group 1: 2.6.22-omap1 */ "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+" + /* group 2: ([email protected]) */ "\\(.*?(?:\\(.*?\\)).*?\\)\\s+" + /* ignore: (gcc ..) */ "([^\\s]+)\\s+" + /* group 3: #26 */ "(?:PREEMPT\\s+)?" + /* ignore: PREEMPT (optional) */ "(.+)"; /* group 4: date */ Pattern p = Pattern.compile(PROC_VERSION_REGEX); Matcher m = p.matcher(procVersionStr); if (!m.matches()) { Log.e(TAG, "Regex did not match on /proc/version: " + procVersionStr); return "Unavailable"; } else if (m.groupCount() < 4) { Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount() + " groups"); return "Unavailable"; } else { return (new StringBuilder(m.group(1)).append("\n").append( m.group(2)).append(" ").append(m.group(3)).append("\n") .append(m.group(4))).toString(); } } catch (IOException e) { Log.e(TAG, "IO Exception when getting kernel version for Device Info screen", e); return "Unavailable"; } }
diff --git a/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java b/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java index 9fcde5b..f832bbb 100644 --- a/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java +++ b/core/src/main/java/org/jvnet/sorcerer/ParsedSourceSet.java @@ -1,669 +1,672 @@ package org.jvnet.sorcerer; import antlr.Token; import antlr.TokenStreamException; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LineMap; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.PrimitiveTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.JavacTask; import com.sun.source.util.SourcePositions; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.source.util.TreeScanner; import com.sun.source.util.Trees; import org.jvnet.sorcerer.Tag.ClassDecl; import org.jvnet.sorcerer.Tag.DeclName; import org.jvnet.sorcerer.Tag.FieldDecl; import org.jvnet.sorcerer.Tag.FieldRef; import org.jvnet.sorcerer.Tag.Literal; import org.jvnet.sorcerer.Tag.LocalVarDecl; import org.jvnet.sorcerer.Tag.LocalVarRef; import org.jvnet.sorcerer.Tag.MethodDecl; import org.jvnet.sorcerer.Tag.MethodRef; import org.jvnet.sorcerer.Tag.TypeRef; import org.jvnet.sorcerer.impl.JavaLexer; import org.jvnet.sorcerer.impl.JavaTokenTypes; import org.jvnet.sorcerer.util.CharSequenceReader; import org.jvnet.sorcerer.util.TreeUtil; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.DiagnosticListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; /** * Represents set of analyzed source code. * * <p> * This object retains the entire parse trees of the source files * and type information, as well as enough indexes among them * to make page generation fast enough. There's always a tricky trade-off * between how much index you retain in memory vs how much you compute * dynamically. * * <p> * Instances of this class can be safely accessed from multiple threads * concurrently. * * <p> * Normally, {@link Analyzer} is used to create this object, but * advanced clients may invoke the constructor with a properly * configured {@link JavacTask}. * * @see Analyzer#analyze * @author Kohsuke Kawaguchi */ public class ParsedSourceSet { // javac related objects private final Trees trees; private final SourcePositions srcPos; private final Elements elements; private final Types types; private final List<CompilationUnitTree> compilationUnits = new ArrayList<CompilationUnitTree>(); /** * path to {@link ClassTree} keyed by its full-qualified class name. */ private final Map<String,TreePath> classes = new TreeMap<String,TreePath>(); private final Set<PackageElement> packages = new TreeSet<PackageElement>(PACKAGENAME_COMPARATOR); private final List<Dependency> dependencies = new ArrayList<Dependency>(); private final int tabWidth; /** * {@link ParsedType}s keyed by its {@link ParsedType#element}. */ /*package*/ final Map<TypeElement,ParsedType> parsedTypes = new HashMap<TypeElement,ParsedType>(); /** * {@link ClassTree}s in the compilation unit to their {@link TreePath}. */ /*package*/ final Map<ClassTree,TreePath> treePathByClass = new HashMap<ClassTree,TreePath>(); /** * Runs <tt>javac</tt> and analyzes the result. * * <p> * Any error found during the analysis will be reported to * {@link DiagnosticListener} installed on {@link JavacTask}. */ public ParsedSourceSet(JavacTask javac, int tabWidth) throws IOException { trees = Trees.instance(javac); elements = javac.getElements(); types = javac.getTypes(); srcPos = new SourcePositionsWrapper(trees.getSourcePositions()); this.tabWidth = tabWidth; Iterable<? extends CompilationUnitTree> parsed = javac.parse(); javac.analyze(); // used to list up all analyzed classes TreePathScanner<?,?> classScanner = new TreePathScanner<Void,Void>() { public Void visitClass(ClassTree ct, Void _) { TreePath path = getCurrentPath(); treePathByClass.put(ct,path); TypeElement e = (TypeElement) trees.getElement(path); if(e!=null) { classes.put(e.getQualifiedName().toString(), path); // make sure we have descendants tree built for all compilation units getParsedType(e); // remember packages that have compilation units in it Element p = e.getEnclosingElement(); if(p.getKind()==ElementKind.PACKAGE) packages.add((PackageElement) p); } return super.visitClass(ct, _); } }; for( CompilationUnitTree u : parsed ) { compilationUnits.add(u); classScanner.scan(u,null); } // build up index for find usage. for( Map.Entry<TypeElement,Set<CompilationUnitTree>> e : ClassReferenceBuilder.build(compilationUnits).entrySet() ) getParsedType(e.getKey()).referers = e.getValue().toArray(new CompilationUnitTree[e.getValue().size()]); } /** * Gets all the {@link CompilationUnitTree}s that are analyzed. * * @return * can be empty but never null. */ public List<CompilationUnitTree> getCompilationUnits() { return Collections.unmodifiableList(compilationUnits); } /** * Gets all the {@link TreePath}s to {@link ClassTree}s included * in the analyzed source files. * * @return * can be empty but never null. */ public Collection<TreePath> getClasses() { return Collections.unmodifiableCollection(classes.values()); } /** * All the {@link ClassTree}s to their {@link TreePath}s. */ public Map<ClassTree,TreePath> getTreePathByClass() { return treePathByClass; } /** * Gets the javadoc/sorcerer locations of dependencies. */ public List<Dependency> getDependencies() { return dependencies; } public void addDependency(Dependency d) { dependencies.add(d); } /** * Gets all the classes included in the analyzed source files. * * <p> * This includes interfaces, enums, and annotation types. * It also includes types that are defined elsewhere (that are referenced by * compiled source code.) * * @return * can be empty but never null. */ public Collection<TypeElement> getClassElements() { return Collections.unmodifiableCollection(parsedTypes.keySet()); } /** * Gets all the classes in the given package. */ public Collection<TypeElement> getClassElements(PackageElement pkg) { Set<TypeElement> r = new TreeSet<TypeElement>(TYPE_COMPARATOR); for (TypeElement e : parsedTypes.keySet()) { Element p = e.getEnclosingElement(); if(p.equals(pkg)) r.add(e); } return r; } /** * Gets all the packages of the analyzed source files. * * <p> * This does not include those packages that are just referenced. * * @return * can be empty but never null. */ public Collection<PackageElement> getPackageElement() { return Collections.unmodifiableCollection(packages); } /** * Gets the list of all fully-qualified class names in the analyzed source files. * * @return * can be empty but never null. */ public Set<String> getClassNames() { return Collections.unmodifiableSet(classes.keySet()); } /** * Gets the {@link TreePath} by its fully qualified class name. */ public TreePath getClassTreePath(String fullyQualifiedClassName) { return classes.get(fullyQualifiedClassName); } /** * Gets the {@link Trees} object that lets you navigate around the tree model. * * @return * always non-null, same object. */ public Trees getTrees() { return trees; } /** * Gets the {@link SourcePositions} object that lets you find the location of objects. * * @return * always non-null, same object. */ public SourcePositions getSourcePositions() { return srcPos; } /** * Gets the {@link Elements} object that lets you navigate around {@link Element}s. * * @return * always non-null, same object. */ public Elements getElements() { return elements; } /** * Gets the {@link Types} object that lets you navigate around {@link TypeMirror}s. * * @return * always non-null, same object. */ public Types getTypes() { return types; } /** * Gets the current TAB width. */ public int getTabWidth() { return tabWidth; } /** * Gets or creates a {@link ParsedType} for the given {@link TypeElement}. */ public ParsedType getParsedType(TypeElement e) { ParsedType v = parsedTypes.get(e); if(v==null) return new ParsedType(this,e); // the constructor will register itself to the map else return v; } /** * Gets all the {@link ParsedType}s. */ public Collection<ParsedType> getParsedTypes() { return parsedTypes.values(); } /** * Invoked by {@link AstGenerator}'s constructor to complete the initialization. * <p> * This is where the actual annotation of the source code happens. */ protected void configure(final CompilationUnitTree cu, final AstGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new FieldDecl(cu,srcPos,vt)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } // TODO: handle declarations like "String abc[]" if(token!=null) gen.add(new DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { if(e.getKind()==ElementKind.CONSTRUCTOR && e.getEnclosingElement().getSimpleName().length()==0) return _; // this is a synthesized constructor for an anonymous class // TODO: I suspect we need some kind of uniform treatment for all synthesized methods // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. - Token token; + Token token=null; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); - else + // on enum class, like "public enum En {ABC,DEF}", the above returns null somehow. + // so go with the plan B if it's not found. + // TODO: report to javac team + if(token==null) token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new FieldRef(cu,srcPos,id,(VariableElement)e)); break; case PARAMETER: case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: gen.add(new LocalVarRef(cu,srcPos,id,(VariableElement)e)); break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; TypeElement ownerType = (TypeElement) ee.getEnclosingElement(); if(ownerType.getSimpleName().length()==0) { // if this is the constructor for an anonymous class, // can't link to the constructor as it's synthetic scan(nt.getIdentifier()); } else { // TODO: the identifier tree might contain type parameters, packaga names, etc. // we should visit those gen.add(new MethodRef(sp,ep,ee)); } } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion Element e = TreeUtil.getElement(mi); if (e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; Name methodName = ee.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new MethodRef(ep-methodName.length(),ep,ee)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } } private long getPosition(LineMap lineMap, Token token) { return lineMap.getPosition(token.getLine(),token.getColumn()); } public static final Comparator<PackageElement> PACKAGENAME_COMPARATOR = new Comparator<PackageElement>() { public int compare(PackageElement lhs, PackageElement rhs) { return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString()); } }; public static final Comparator<Element> SIMPLENAME_COMPARATOR = new Comparator<Element>() { public int compare(Element lhs, Element rhs) { return lhs.getSimpleName().toString().compareTo(rhs.getSimpleName().toString()); } }; private static final Comparator<TypeElement> TYPE_COMPARATOR = new Comparator<TypeElement>() { public int compare(TypeElement lhs, TypeElement rhs) { return lhs.getQualifiedName().toString().compareTo(rhs.getQualifiedName().toString()); } }; }
false
true
protected void configure(final CompilationUnitTree cu, final AstGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new FieldDecl(cu,srcPos,vt)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } // TODO: handle declarations like "String abc[]" if(token!=null) gen.add(new DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { if(e.getKind()==ElementKind.CONSTRUCTOR && e.getEnclosingElement().getSimpleName().length()==0) return _; // this is a synthesized constructor for an anonymous class // TODO: I suspect we need some kind of uniform treatment for all synthesized methods // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. Token token; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); else token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new FieldRef(cu,srcPos,id,(VariableElement)e)); break; case PARAMETER: case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: gen.add(new LocalVarRef(cu,srcPos,id,(VariableElement)e)); break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; TypeElement ownerType = (TypeElement) ee.getEnclosingElement(); if(ownerType.getSimpleName().length()==0) { // if this is the constructor for an anonymous class, // can't link to the constructor as it's synthetic scan(nt.getIdentifier()); } else { // TODO: the identifier tree might contain type parameters, packaga names, etc. // we should visit those gen.add(new MethodRef(sp,ep,ee)); } } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion Element e = TreeUtil.getElement(mi); if (e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; Name methodName = ee.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new MethodRef(ep-methodName.length(),ep,ee)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } }
protected void configure(final CompilationUnitTree cu, final AstGenerator gen) throws IOException { final LineMap lineMap = cu.getLineMap(); // add lexical markers JavaLexer lexer = new JavaLexer(new CharSequenceReader(gen.sourceFile)); lexer.setTabSize(tabWidth); try { Stack<Long> openBraces = new Stack<Long>(); while(true) { Token token = lexer.nextToken(); int type = token.getType(); if(type == JavaTokenTypes.EOF) break; if(type == JavaTokenTypes.IDENT && ReservedWords.LIST.contains(token.getText())) gen.add(new Tag.ReservedWord(lineMap,token)); if(type == JavaTokenTypes.ML_COMMENT || type == JavaTokenTypes.SL_COMMENT) gen.add(new Tag.Comment(lineMap,token)); if(type == JavaTokenTypes.LCURLY || type==JavaTokenTypes.LPAREN) { openBraces.push(getPosition(lineMap,token)); gen.add(new Tag.Killer(lineMap,token)); // CurlyBracket tag yields '{'. so kill this off. } if(type == JavaTokenTypes.RCURLY) { long sp = openBraces.pop(); gen.add(new Tag.CurlyBracket(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } if(type == JavaTokenTypes.RPAREN) { long sp = openBraces.pop(); gen.add(new Tag.Parenthesis(sp,getPosition(lineMap,token)+1)); gen.add(new Tag.Killer(lineMap,token)); } } } catch (TokenStreamException e) { // the analysis phase should have reported all the errors, // so we should ignore any failures at this point. } final Name CLASS = elements.getName("class"); // then semantic ones new TreeScanner<Void,Void>() { /** * primitive types like int, long, void, etc. */ public Void visitPrimitiveType(PrimitiveTypeTree pt, Void _) { // all primitives should be marked up by lexer // gen.add(new Tag.PrimitiveType(cu,srcPos,pt)); return super.visitPrimitiveType(pt,_); } /** * literal string, int, etc. Null. */ public Void visitLiteral(LiteralTree lit, Void _) { gen.add(new Literal(cu,srcPos,lit)); return super.visitLiteral(lit, _); } /** * Definition of a variable, such as parameter, field, and local variables. */ public Void visitVariable(VariableTree vt, Void _) { VariableElement e = (VariableElement) TreeUtil.getElement(vt); if(e!=null) { switch (e.getKind()) { case ENUM_CONSTANT: case FIELD: gen.add(new FieldDecl(cu,srcPos,vt)); break; case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: case PARAMETER: gen.add(new LocalVarDecl(cu,srcPos,vt,e)); break; } Token token; if(e.getKind()!= ElementKind.ENUM_CONSTANT) { // put the marker just on the variable name. // the token for the variable name is after its type. // note that we need to handle declarations like "int a,b". token = gen.findTokenAfter(vt.getType(), true, vt.getName().toString()); } else { // for the enum constant put the anchor around vt token = gen.findTokenAfter(vt, false, vt.getName().toString()); } // TODO: handle declarations like "String abc[]" if(token!=null) gen.add(new DeclName(lineMap,token)); } return super.visitVariable(vt,_); } /** * Method declaration. */ public Void visitMethod(MethodTree mt, Void _) { ExecutableElement e = (ExecutableElement) TreeUtil.getElement(mt); if(e!=null) { if(e.getKind()==ElementKind.CONSTRUCTOR && e.getEnclosingElement().getSimpleName().length()==0) return _; // this is a synthesized constructor for an anonymous class // TODO: I suspect we need some kind of uniform treatment for all synthesized methods // mark up the method name Tree prev = mt.getReturnType(); String name = mt.getName().toString(); Token token; if(prev!=null) token = gen.findTokenAfter(prev, true, name); else token = gen.findTokenAfter(mt,false,name); if(token!=null) gen.add(new DeclName(lineMap,token)); ParsedType pt = getParsedType((TypeElement) e.getEnclosingElement()); gen.add(new MethodDecl(cu, srcPos, mt, e, pt.findOverriddenMethods(elements, e), pt.findOverridingMethods(elements, e) )); } return super.visitMethod(mt, _); } /** * Class declaration. */ public Void visitClass(ClassTree ct, Void _) { TypeElement e = (TypeElement) TreeUtil.getElement(ct); if(e!=null) { // put the marker on the class name portion. Token token=null; if(ct.getModifiers()!=null) token = gen.findTokenAfter(ct.getModifiers(), true, ct.getSimpleName().toString()); // on enum class, like "public enum En {ABC,DEF}", the above returns null somehow. // so go with the plan B if it's not found. // TODO: report to javac team if(token==null) token = gen.findTokenAfter(ct, false, ct.getSimpleName().toString()); if(token!=null) gen.add(new DeclName(lineMap, token)); List<ParsedType> descendants = getParsedType(e).descendants; gen.add(new ClassDecl(cu, srcPos, ct, e, descendants)); if(e.getNestingKind()== NestingKind.ANONYMOUS) { // don't visit the extends and implements clause as // they already show up in the NewClassTree scan(ct.getMembers()); return _; } } return super.visitClass(ct, _); } /** * All the symbols found in the source code. */ public Void visitIdentifier(IdentifierTree id, Void _) { if(!ReservedWords.LIST.contains(id.getName().toString())) { Element e = TreeUtil.getElement(id); if(e!=null) { switch (e.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(cu,srcPos,id,(TypeElement)e)); break; case FIELD: // such as objects imported by static import. case ENUM_CONSTANT: gen.add(new FieldRef(cu,srcPos,id,(VariableElement)e)); break; case PARAMETER: case EXCEPTION_PARAMETER: case LOCAL_VARIABLE: gen.add(new LocalVarRef(cu,srcPos,id,(VariableElement)e)); break; } } } return super.visitIdentifier(id,_); } /** * "exp.token" */ public Void visitMemberSelect(MemberSelectTree mst, Void _) { // avoid marking 'Foo.class' as static reference if(!mst.getIdentifier().equals(CLASS)) { // just select the 'token' portion long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // marker for the selected identifier Element e = TreeUtil.getElement(mst); if(e!=null) { switch(e.getKind()) { case FIELD: case ENUM_CONSTANT: gen.add(new FieldRef(sp,ep,(VariableElement)e)); break; // these show up in the import statement case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: gen.add(new TypeRef(sp,ep,(TypeElement)e)); break; } } } return super.visitMemberSelect(mst, _); } /** * Constructor invocation. */ public Void visitNewClass(NewClassTree nt, Void _) { long ep = srcPos.getEndPosition(cu, nt.getIdentifier()); long sp = srcPos.getStartPosition(cu, nt.getIdentifier()); // marker for jumping to the definition Element e = TreeUtil.getElement(nt); if(e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; TypeElement ownerType = (TypeElement) ee.getEnclosingElement(); if(ownerType.getSimpleName().length()==0) { // if this is the constructor for an anonymous class, // can't link to the constructor as it's synthetic scan(nt.getIdentifier()); } else { // TODO: the identifier tree might contain type parameters, packaga names, etc. // we should visit those gen.add(new MethodRef(sp,ep,ee)); } } scan(nt.getEnclosingExpression()); scan(nt.getArguments()); scan(nt.getTypeArguments()); scan(nt.getClassBody()); return _; } // TODO: how is the 'super' or 'this' constructor invocation handled? /** * Method invocation of the form "exp.method()" */ public Void visitMethodInvocation(MethodInvocationTree mi, Void _) { ExpressionTree ms = mi.getMethodSelect(); // PRIMARY.methodName portion Element e = TreeUtil.getElement(mi); if (e instanceof ExecutableElement) {// this check is needed in case the source code contains errors ExecutableElement ee = (ExecutableElement) e; Name methodName = ee.getSimpleName(); long ep = srcPos.getEndPosition(cu, ms); if(ep>=0) { // marker for the method name (and jump to definition) gen.add(new MethodRef(ep-methodName.length(),ep,ee)); } } return super.visitMethodInvocation(mi,_); } // recursively scan trees private void scan(List<? extends Tree> list) { for (Tree t : list) scan(t); } private void scan(Tree t) { scan(t,null); } }.scan(cu,null); // compilationUnit -> package name consists of member select trees // but it fails to create an element, so do this manually ExpressionTree packageName = cu.getPackageName(); if(packageName!=null) { new TreeScanner<String,Void>() { /** * For "a" of "a.b.c" */ public String visitIdentifier(IdentifierTree id, Void _) { String name = id.getName().toString(); PackageElement pe = elements.getPackageElement(name); // addRef(id,pe); return name; } public String visitMemberSelect(MemberSelectTree mst, Void _) { String baseName = scan(mst.getExpression(),_); String name = mst.getIdentifier().toString(); if(baseName.length()>0) name = baseName+'.'+name; PackageElement pe = elements.getPackageElement(name); long ep = srcPos.getEndPosition(cu,mst); long sp = ep-mst.getIdentifier().length(); // addRef(sp,ep,pe); return name; } }.scan(packageName,null); } }
diff --git a/AndroidMovingMap/AndroidMovingMap/src/edu/rosehulman/androidmovingmap/MainActivity.java b/AndroidMovingMap/AndroidMovingMap/src/edu/rosehulman/androidmovingmap/MainActivity.java index 72cb131..d6e2937 100644 --- a/AndroidMovingMap/AndroidMovingMap/src/edu/rosehulman/androidmovingmap/MainActivity.java +++ b/AndroidMovingMap/AndroidMovingMap/src/edu/rosehulman/androidmovingmap/MainActivity.java @@ -1,412 +1,414 @@ package edu.rosehulman.androidmovingmap; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.osmdroid.tileprovider.MapTile; import org.osmdroid.tileprovider.tilesource.XYTileSource; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.overlay.MyLocationOverlay; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.Settings; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import edu.rosehulman.maps.OSMMapView; import edu.rosehulman.overlays.AMMItemizedOverlay; import edu.rosehulman.overlays.IItemizedOverlay; import edu.rosehulman.overlays.OverlayIconRegistry; import edu.rosehulman.server.POI; import edu.rosehulman.server.Server; public class MainActivity extends Activity implements OnClickListener, Serializable { private SharedPreferences prefs; private OSMMapView mMapView; private LocationManager locationManager; LocationProvider provider; private MyLocationOverlay deviceOverlay; private ImageView mCompass; private ImageView mFindMe; private boolean mNorthUp; private XYTileSource tileSource; private String mapSourcePrefix = "initial source prefix"; private ArrayList<String> mapSourceNames = new ArrayList<String>( Arrays.asList("map1", "map2")); private ArrayList<Integer> mapMaxZoom = new ArrayList<Integer>( Arrays.asList(16, 4)); private int mapSourceIndex = 0; private int UID_to_track = -1; private Handler invalidateDisplay = new Handler() { @Override public void handleMessage(Message msg) { updatePOIandScreen(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); int refreshGPStime = 1000; int refreshGPSdistance = 20; locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); provider = locationManager.getProvider(LocationManager.GPS_PROVIDER); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, refreshGPStime, refreshGPSdistance, listener); mMapView = (OSMMapView) findViewById(R.id.map_view); mMapView.setClickable(true); mMapView.setMultiTouchControls(true); mMapView.setBuiltInZoomControls(true); deviceOverlay = new MyLocationOverlay(this, mMapView); deviceOverlay.enableFollowLocation(); deviceOverlay.enableMyLocation(); // Comment back in to use MAPNIK server data // mMapView.setTileSource(TileSourceFactory.MAPNIK); String server_name = this.prefs.getString("KEY_SERVER", "bad preferences"); Log.d("server_name", server_name); mapSourcePrefix = "http://" + server_name; tileSource = new XYTileSource("local" + mapSourceIndex, null, 0, mapMaxZoom.get(mapSourceIndex), 256, ".png", mapSourcePrefix + "/" + mapSourceNames.get(mapSourceIndex) + "/"); mMapView.setTileSource(tileSource); mMapView.getController().setZoom(13); mCompass = (ImageView) findViewById(R.id.compass); mCompass.setOnClickListener(this); mFindMe = (ImageView) findViewById(R.id.find_me); mFindMe.setOnClickListener(this); Server.getInstance().updatePOIHandler = invalidateDisplay; Server.getInstance().setServerAddress(server_name); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.add_poi_type) { Toast.makeText(this, "I can totally add POI types", Toast.LENGTH_SHORT).show(); AddPOITypeDialogFragment.newInstance( mMapView.getAMMOverlayManager(), this).show( getFragmentManager(), "lol"); return true; } else if (itemId == R.id.menu_settings) { Intent intent = new Intent(this, Preferences.class); startActivity(intent); return true; } else if (itemId == R.id.menu_cycle_map_type) { mapSourceIndex = (mapSourceIndex + 1) % mapSourceNames.size(); tileSource = new XYTileSource("local" + mapSourceIndex, null, 0, mapMaxZoom.get(mapSourceIndex), 256, ".png", mapSourcePrefix + mapSourceNames.get(mapSourceIndex)); Log.d("menu cycle", "pathBase: " + tileSource.getTileURLString(new MapTile(0, 0, 0))); mMapView.setTileSource(tileSource); mMapView.invalidate(); return true; } else if (itemId == R.id.menu_track_point) { UID_to_track += 1; if (UID_to_track == Server.getInstance().POIelements.size()) { UID_to_track = -1; } return true; } else if (itemId == R.id.menu_start_stop_sync) { Log.d("sync", "status: " + Server.getInstance().startedPOISync()); if (Server.getInstance().startedPOISync()) { Server.getInstance().stopPOISync(); } else { Server.getInstance().startPOISync(); } return true; } else if (itemId == R.id.menu_push_server) { Log.d("POI", "attempting to sync onto server"); for (IItemizedOverlay type : mMapView.getAMMOverlayManager().getOverlays()) { Iterator<POI> iter = type.getOverlays().iterator(); while (iter.hasNext()) { POI tempPoint = iter.next(); if (tempPoint.getUID() < 0) { try { Server.getInstance().sendMessage( "addPoint:" + tempPoint.toJSONString() + "\n"); iter.remove(); } catch (Exception e) { Log.d("POI", "failed to send POI"); } } } for (int UIDToRemove : Server.POIUIDToDelete) { POI tempPoint = new POI(UIDToRemove, "", 0.0, 0.0, "", new TreeMap<String,String>()); try { Server.getInstance().sendMessage("removePoint:" + tempPoint.toJSONString() + "\n"); + Server.POIelements.remove(UIDToRemove); } catch (Exception e) { Log.d("POI", "failed to remove UID: " + UIDToRemove); } } + Server.POIUIDToDelete.clear(); } return true; } else if (itemId == R.id.choose_poi_to_display) { new ChooseDisplayedPOIFragment().show(getFragmentManager(), "show displayed poi dialog"); return true; } else { return super.onOptionsItemSelected(item); } } private class ChooseDisplayedPOIFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { ListView listView = new ListView(getBaseContext()); final List<IItemizedOverlay> overlays = mMapView.getAMMOverlayManager().getOverlays(); final OverlayListAdapter adapter = new OverlayListAdapter( MainActivity.this.getBaseContext(), OverlayIconRegistry .getInstance().getRegisteredOverlays(), ListView.CHOICE_MODE_MULTIPLE, overlays); listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setItemsCanFocus(false); for(int i = 0; i < listView.getCount(); i++){ AMMItemizedOverlay overlay = (AMMItemizedOverlay)((IItemizedOverlay) overlays.get(i)); listView.setItemChecked(i, overlay.isActive()); } listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { OverlayTypeView item = (OverlayTypeView) adapter.getView(position, view, parent); item.toggle(); AMMItemizedOverlay mur = (AMMItemizedOverlay)((IItemizedOverlay) overlays.get(position)); mur.setActive(item.isChecked()); } }); return new AlertDialog.Builder(getActivity()) .setTitle(R.string.displayed_poi_title).setView(listView) .setCancelable(false) .create(); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); mMapView.setOverylays(); mMapView.invalidate(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == AddPOIActivity.NEW_POI_REQUEST) { if (resultCode == RESULT_OK) { GeoPoint geopoint = (GeoPoint) data .getSerializableExtra(AddPOIActivity.KEY_GEOPOINT); String name = data.getStringExtra(AddPOIActivity.KEY_POI_NAME); String type = data.getStringExtra(AddPOIActivity.KEY_POI_TYPE); String descr = data .getStringExtra(AddPOIActivity.KEY_POI_DESCR); double latitude = geopoint.getLatitudeE6() / 1000000.0; double longitude = geopoint.getLongitudeE6() / 1000000.0; Map<String, String> attribs = new HashMap<String, String>(); attribs.put("description", descr); POI poi = new POI(-2, name, latitude, longitude, type, attribs); mMapView.getAMMOverlayManager().addOverlay(poi); } } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onStart() { super.onStart(); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); final boolean gpsEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); if (!gpsEnabled) { new EnableGpsDialogFragment().show(getFragmentManager(), "enableGpsDialog"); } } private class EnableGpsDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setTitle(R.string.enable_gps) .setMessage(R.string.enable_gps_dialog) .setPositiveButton(R.string.enable_gps, new DialogInterface.OnClickListener() { // @Override public void onClick(DialogInterface dialog, int which) { enableLocationSettings(); } }).setNegativeButton(R.string.server_gps, null) .create(); } } @Override protected void onStop() { super.onStop(); locationManager.removeUpdates(listener); Server.getInstance().stopServer(); } private void enableLocationSettings() { Intent settingsIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(settingsIntent); } private final LocationListener listener = new LocationListener() { public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onLocationChanged(Location location) { CharSequence loc = "Lat: " + location.getLatitude() + "\n Lon: " + location.getLongitude(); Log.d("AMM", "loc: " + loc); // Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show(); } }; public void onClick(View v) { if (v.getId() == R.id.compass) { mNorthUp = !mNorthUp; String s; if (mNorthUp) { s = getString(R.string.north_up); } else { s = getString(R.string.heading_up); } Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } else if (v.getId() == R.id.find_me) { // Toast.makeText(this, "centering on device location", // Toast.LENGTH_SHORT).show(); mMapView.getController().setCenter(deviceOverlay.getMyLocation()); } } private void updatePOIandScreen() { for (IItemizedOverlay type : mMapView.getAMMOverlayManager() .getOverlays()) { Iterator<POI> iter = type.getOverlays().iterator(); while (iter.hasNext()) { POI testPoint = iter.next(); if (testPoint.getUID() >= 0) { iter.remove(); } } for (POI point : Server.getInstance().POIelements.values()) { if (point.getType().equalsIgnoreCase(type.getName())) { type.addOverlay(point); } if (point.getUID() == UID_to_track) { mMapView.getController().setCenter(point.getGeoPoint()); } } } Log.d("status", "over"); this.mMapView.invalidate(); } public void setUIDtoTrack(int UID) { UID_to_track = UID; Log.d("AMM", "tracking UID: " + UID_to_track); } public LocationProvider getLocationProvider() { return provider; } @Override public SharedPreferences getSharedPreferences(String name, int mode) { // TODO Auto-generated method stub return super.getSharedPreferences(name, mode); } }
false
true
public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.add_poi_type) { Toast.makeText(this, "I can totally add POI types", Toast.LENGTH_SHORT).show(); AddPOITypeDialogFragment.newInstance( mMapView.getAMMOverlayManager(), this).show( getFragmentManager(), "lol"); return true; } else if (itemId == R.id.menu_settings) { Intent intent = new Intent(this, Preferences.class); startActivity(intent); return true; } else if (itemId == R.id.menu_cycle_map_type) { mapSourceIndex = (mapSourceIndex + 1) % mapSourceNames.size(); tileSource = new XYTileSource("local" + mapSourceIndex, null, 0, mapMaxZoom.get(mapSourceIndex), 256, ".png", mapSourcePrefix + mapSourceNames.get(mapSourceIndex)); Log.d("menu cycle", "pathBase: " + tileSource.getTileURLString(new MapTile(0, 0, 0))); mMapView.setTileSource(tileSource); mMapView.invalidate(); return true; } else if (itemId == R.id.menu_track_point) { UID_to_track += 1; if (UID_to_track == Server.getInstance().POIelements.size()) { UID_to_track = -1; } return true; } else if (itemId == R.id.menu_start_stop_sync) { Log.d("sync", "status: " + Server.getInstance().startedPOISync()); if (Server.getInstance().startedPOISync()) { Server.getInstance().stopPOISync(); } else { Server.getInstance().startPOISync(); } return true; } else if (itemId == R.id.menu_push_server) { Log.d("POI", "attempting to sync onto server"); for (IItemizedOverlay type : mMapView.getAMMOverlayManager().getOverlays()) { Iterator<POI> iter = type.getOverlays().iterator(); while (iter.hasNext()) { POI tempPoint = iter.next(); if (tempPoint.getUID() < 0) { try { Server.getInstance().sendMessage( "addPoint:" + tempPoint.toJSONString() + "\n"); iter.remove(); } catch (Exception e) { Log.d("POI", "failed to send POI"); } } } for (int UIDToRemove : Server.POIUIDToDelete) { POI tempPoint = new POI(UIDToRemove, "", 0.0, 0.0, "", new TreeMap<String,String>()); try { Server.getInstance().sendMessage("removePoint:" + tempPoint.toJSONString() + "\n"); } catch (Exception e) { Log.d("POI", "failed to remove UID: " + UIDToRemove); } } } return true; } else if (itemId == R.id.choose_poi_to_display) { new ChooseDisplayedPOIFragment().show(getFragmentManager(), "show displayed poi dialog"); return true; } else { return super.onOptionsItemSelected(item); } }
public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.add_poi_type) { Toast.makeText(this, "I can totally add POI types", Toast.LENGTH_SHORT).show(); AddPOITypeDialogFragment.newInstance( mMapView.getAMMOverlayManager(), this).show( getFragmentManager(), "lol"); return true; } else if (itemId == R.id.menu_settings) { Intent intent = new Intent(this, Preferences.class); startActivity(intent); return true; } else if (itemId == R.id.menu_cycle_map_type) { mapSourceIndex = (mapSourceIndex + 1) % mapSourceNames.size(); tileSource = new XYTileSource("local" + mapSourceIndex, null, 0, mapMaxZoom.get(mapSourceIndex), 256, ".png", mapSourcePrefix + mapSourceNames.get(mapSourceIndex)); Log.d("menu cycle", "pathBase: " + tileSource.getTileURLString(new MapTile(0, 0, 0))); mMapView.setTileSource(tileSource); mMapView.invalidate(); return true; } else if (itemId == R.id.menu_track_point) { UID_to_track += 1; if (UID_to_track == Server.getInstance().POIelements.size()) { UID_to_track = -1; } return true; } else if (itemId == R.id.menu_start_stop_sync) { Log.d("sync", "status: " + Server.getInstance().startedPOISync()); if (Server.getInstance().startedPOISync()) { Server.getInstance().stopPOISync(); } else { Server.getInstance().startPOISync(); } return true; } else if (itemId == R.id.menu_push_server) { Log.d("POI", "attempting to sync onto server"); for (IItemizedOverlay type : mMapView.getAMMOverlayManager().getOverlays()) { Iterator<POI> iter = type.getOverlays().iterator(); while (iter.hasNext()) { POI tempPoint = iter.next(); if (tempPoint.getUID() < 0) { try { Server.getInstance().sendMessage( "addPoint:" + tempPoint.toJSONString() + "\n"); iter.remove(); } catch (Exception e) { Log.d("POI", "failed to send POI"); } } } for (int UIDToRemove : Server.POIUIDToDelete) { POI tempPoint = new POI(UIDToRemove, "", 0.0, 0.0, "", new TreeMap<String,String>()); try { Server.getInstance().sendMessage("removePoint:" + tempPoint.toJSONString() + "\n"); Server.POIelements.remove(UIDToRemove); } catch (Exception e) { Log.d("POI", "failed to remove UID: " + UIDToRemove); } } Server.POIUIDToDelete.clear(); } return true; } else if (itemId == R.id.choose_poi_to_display) { new ChooseDisplayedPOIFragment().show(getFragmentManager(), "show displayed poi dialog"); return true; } else { return super.onOptionsItemSelected(item); } }
diff --git a/Superuser/src/com/koushikdutta/superuser/PolicyFragmentInternal.java b/Superuser/src/com/koushikdutta/superuser/PolicyFragmentInternal.java index 83fb41b..dd241ff 100644 --- a/Superuser/src/com/koushikdutta/superuser/PolicyFragmentInternal.java +++ b/Superuser/src/com/koushikdutta/superuser/PolicyFragmentInternal.java @@ -1,188 +1,176 @@ /* * Copyright (C) 2013 Koushik Dutta (@koush) * * 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.koushikdutta.superuser; import java.util.ArrayList; import android.content.Context; import android.content.res.Configuration; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.format.DateFormat; import android.view.ContextThemeWrapper; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.View; import android.widget.ImageView; import com.koushikdutta.superuser.db.SuDatabaseHelper; import com.koushikdutta.superuser.db.UidPolicy; import com.koushikdutta.widgets.FragmentInterfaceWrapper; import com.koushikdutta.widgets.ListContentFragmentInternal; import com.koushikdutta.widgets.ListItem; public class PolicyFragmentInternal extends ListContentFragmentInternal { public PolicyFragmentInternal(FragmentInterfaceWrapper fragment) { super(fragment); } ContextThemeWrapper mWrapper; @Override public Context getContext() { if (mWrapper != null) return mWrapper; mWrapper = new ContextThemeWrapper(super.getContext(), R.style.Superuser_PolicyIcon); return mWrapper; } void showAllLogs() { setContent(null, null); getListView().clearChoices(); } void load() { clear(); final ArrayList<UidPolicy> policies = SuDatabaseHelper.getPolicies(getActivity()); for (UidPolicy up: policies) { addPolicy(up); } } FragmentInterfaceWrapper mContent; @Override public void onCreate(Bundle savedInstanceState, View view) { super.onCreate(savedInstanceState, view); getFragment().setHasOptionsMenu(true); setEmpty(R.string.no_apps); load(); if ("com.koushikdutta.superuser".equals(getContext().getPackageName())) { ImageView watermark = (ImageView)view.findViewById(R.id.watermark); if (watermark != null) watermark.setImageResource(R.drawable.clockwork512); } if (!isPaged()) showAllLogs(); } void addPolicy(final UidPolicy up) { java.text.DateFormat df = DateFormat.getLongDateFormat(getActivity()); String date = df.format(up.getLastDate()); if (up.last == 0) date = null; ListItem li = addItem(up.getPolicyResource(), new ListItem(this, up.name, date) { public void onClick(View view) { super.onClick(view); setContent(this, up); }; }); Drawable icon = Helper.loadPackageIcon(getActivity(), up.packageName); if (icon == null) li.setIcon(R.drawable.ic_launcher); else li.setDrawable(icon); } public void onConfigurationChanged(Configuration newConfig) { }; FragmentInterfaceWrapper setContentNative(final ListItem li, final UidPolicy up) { LogNativeFragment l = new LogNativeFragment(); l.getInternal().setUidPolicy(up); if (up != null) { Bundle args = new Bundle(); args.putString("command", up.command); args.putInt("uid", up.uid); args.putInt("desiredUid", up.desiredUid); l.setArguments(args); } l.getInternal().setListContentId(getFragment().getId()); return l; } void setContent(final ListItem li, final UidPolicy up) { if (getActivity() instanceof FragmentActivity) { LogFragment l = new LogFragment(); l.getInternal().setUidPolicy(up); l.getInternal().setListContentId(getFragment().getId()); mContent = l; } else { mContent = setContentNative(li, up); } setContent(mContent, up == null, up == null ? getString(R.string.logs) : up.getName()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); MenuInflater mi = new MenuInflater(getActivity()); mi.inflate(R.menu.main, menu); MenuItem log = menu.findItem(R.id.logs); log.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { showAllLogs(); return true; } }); MenuItem settings = menu.findItem(R.id.settings); settings.setOnMenuItemClickListener(new OnMenuItemClickListener() { void openSettingsNative(final MenuItem item) { - setContent(new SettingsNativeFragment() { - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - onMenuItemClick(item); - } - }, true, getString(R.string.settings)); + setContent(new SettingsNativeFragment(), true, getString(R.string.settings)); } @Override public boolean onMenuItemClick(final MenuItem item) { if (getActivity() instanceof FragmentActivity) { - setContent(new SettingsFragment() { - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - onMenuItemClick(item); - } - }, true, getString(R.string.settings)); + setContent(new SettingsFragment(), true, getString(R.string.settings)); } else { openSettingsNative(item); } return true; } }); } }
false
true
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); MenuInflater mi = new MenuInflater(getActivity()); mi.inflate(R.menu.main, menu); MenuItem log = menu.findItem(R.id.logs); log.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { showAllLogs(); return true; } }); MenuItem settings = menu.findItem(R.id.settings); settings.setOnMenuItemClickListener(new OnMenuItemClickListener() { void openSettingsNative(final MenuItem item) { setContent(new SettingsNativeFragment() { @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); onMenuItemClick(item); } }, true, getString(R.string.settings)); } @Override public boolean onMenuItemClick(final MenuItem item) { if (getActivity() instanceof FragmentActivity) { setContent(new SettingsFragment() { @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); onMenuItemClick(item); } }, true, getString(R.string.settings)); } else { openSettingsNative(item); } return true; } }); }
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); MenuInflater mi = new MenuInflater(getActivity()); mi.inflate(R.menu.main, menu); MenuItem log = menu.findItem(R.id.logs); log.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { showAllLogs(); return true; } }); MenuItem settings = menu.findItem(R.id.settings); settings.setOnMenuItemClickListener(new OnMenuItemClickListener() { void openSettingsNative(final MenuItem item) { setContent(new SettingsNativeFragment(), true, getString(R.string.settings)); } @Override public boolean onMenuItemClick(final MenuItem item) { if (getActivity() instanceof FragmentActivity) { setContent(new SettingsFragment(), true, getString(R.string.settings)); } else { openSettingsNative(item); } return true; } }); }
diff --git a/src/com/android/email/MessagingController.java b/src/com/android/email/MessagingController.java index c04280f2..3ac6f7c9 100644 --- a/src/com/android/email/MessagingController.java +++ b/src/com/android/email/MessagingController.java @@ -1,2073 +1,2078 @@ /* * 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.email; import com.android.email.mail.FetchProfile; import com.android.email.mail.Flag; import com.android.email.mail.Folder; import com.android.email.mail.Message; import com.android.email.mail.MessageRetrievalListener; import com.android.email.mail.MessagingException; import com.android.email.mail.Part; import com.android.email.mail.Sender; import com.android.email.mail.Store; import com.android.email.mail.StoreSynchronizer; import com.android.email.mail.Folder.FolderType; import com.android.email.mail.Folder.OpenMode; import com.android.email.mail.internet.MimeBodyPart; import com.android.email.mail.internet.MimeHeader; import com.android.email.mail.internet.MimeMultipart; import com.android.email.mail.internet.MimeUtility; import com.android.email.provider.AttachmentProvider; import com.android.email.provider.EmailContent; import com.android.email.provider.EmailContent.Attachment; import com.android.email.provider.EmailContent.AttachmentColumns; import com.android.email.provider.EmailContent.Mailbox; import com.android.email.provider.EmailContent.MailboxColumns; import com.android.email.provider.EmailContent.MessageColumns; import com.android.email.provider.EmailContent.SyncColumns; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Process; import android.util.Log; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Starts a long running (application) Thread that will run through commands * that require remote mailbox access. This class is used to serialize and * prioritize these commands. Each method that will submit a command requires a * MessagingListener instance to be provided. It is expected that that listener * has also been added as a registered listener using addListener(). When a * command is to be executed, if the listener that was provided with the command * is no longer registered the command is skipped. The design idea for the above * is that when an Activity starts it registers as a listener. When it is paused * it removes itself. Thus, any commands that that activity submitted are * removed from the queue once the activity is no longer active. */ public class MessagingController implements Runnable { /** * The maximum message size that we'll consider to be "small". A small message is downloaded * in full immediately instead of in pieces. Anything over this size will be downloaded in * pieces with attachments being left off completely and downloaded on demand. * * * 25k for a "small" message was picked by educated trial and error. * http://answers.google.com/answers/threadview?id=312463 claims that the * average size of an email is 59k, which I feel is too large for our * blind download. The following tests were performed on a download of * 25 random messages. * <pre> * 5k - 61 seconds, * 25k - 51 seconds, * 55k - 53 seconds, * </pre> * So 25k gives good performance and a reasonable data footprint. Sounds good to me. */ private static final int MAX_SMALL_MESSAGE_SIZE = (25 * 1024); private static Flag[] FLAG_LIST_SEEN = new Flag[] { Flag.SEEN }; private static Flag[] FLAG_LIST_FLAGGED = new Flag[] { Flag.FLAGGED }; /** * We write this into the serverId field of messages that will never be upsynced. */ private static final String LOCAL_SERVERID_PREFIX = "Local-"; /** * Projections & CVs used by pruneCachedAttachments */ private static String[] PRUNE_ATTACHMENT_PROJECTION = new String[] { AttachmentColumns.LOCATION }; private static ContentValues PRUNE_ATTACHMENT_CV = new ContentValues(); static { PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI); } private static MessagingController inst = null; private BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>(); private Thread mThread; /** * All access to mListeners *must* be synchronized */ private GroupMessagingListener mListeners = new GroupMessagingListener(); private boolean mBusy; private Context mContext; protected MessagingController(Context _context) { mContext = _context; mThread = new Thread(this); mThread.start(); } /** * Gets or creates the singleton instance of MessagingController. Application is used to * provide a Context to classes that need it. * @param application * @return */ public synchronized static MessagingController getInstance(Context _context) { if (inst == null) { inst = new MessagingController(_context); } return inst; } /** * Inject a mock controller. Used only for testing. Affects future calls to getInstance(). */ public static void injectMockController(MessagingController mockController) { inst = mockController; } // TODO: seems that this reading of mBusy isn't thread-safe public boolean isBusy() { return mBusy; } public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); // TODO: add an end test to this infinite loop while (true) { Command command; try { command = mCommands.take(); } catch (InterruptedException e) { continue; //re-test the condition on the eclosing while } if (command.listener == null || isActiveListener(command.listener)) { mBusy = true; command.runnable.run(); mListeners.controllerCommandCompleted(mCommands.size() > 0); } mBusy = false; } } private void put(String description, MessagingListener listener, Runnable runnable) { try { Command command = new Command(); command.listener = listener; command.runnable = runnable; command.description = description; mCommands.add(command); } catch (IllegalStateException ie) { throw new Error(ie); } } public void addListener(MessagingListener listener) { mListeners.addListener(listener); } public void removeListener(MessagingListener listener) { mListeners.removeListener(listener); } private boolean isActiveListener(MessagingListener listener) { return mListeners.isActiveListener(listener); } /** * Lightweight class for capturing local mailboxes in an account. Just the columns * necessary for a sync. */ private static class LocalMailboxInfo { private static final int COLUMN_ID = 0; private static final int COLUMN_DISPLAY_NAME = 1; private static final int COLUMN_ACCOUNT_KEY = 2; private static final int COLUMN_TYPE = 3; private static final String[] PROJECTION = new String[] { EmailContent.RECORD_ID, MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE, }; long mId; String mDisplayName; long mAccountKey; int mType; public LocalMailboxInfo(Cursor c) { mId = c.getLong(COLUMN_ID); mDisplayName = c.getString(COLUMN_DISPLAY_NAME); mAccountKey = c.getLong(COLUMN_ACCOUNT_KEY); mType = c.getInt(COLUMN_TYPE); } } /** * Lists folders that are available locally and remotely. This method calls * listFoldersCallback for local folders before it returns, and then for * remote folders at some later point. If there are no local folders * includeRemote is forced by this method. This method should be called from * a Thread as it may take several seconds to list the local folders. * * TODO this needs to cache the remote folder list * TODO break out an inner listFoldersSynchronized which could simplify checkMail * * @param account * @param listener * @throws MessagingException */ public void listFolders(final long accountId, MessagingListener listener) { final EmailContent.Account account = EmailContent.Account.restoreAccountWithId(mContext, accountId); if (account == null) { return; } mListeners.listFoldersStarted(accountId); put("listFolders", listener, new Runnable() { public void run() { Cursor localFolderCursor = null; try { // Step 1: Get remote folders, make a list, and add any local folders // that don't already exist. Store store = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder[] remoteFolders = store.getPersonalNamespaces(); HashSet<String> remoteFolderNames = new HashSet<String>(); for (int i = 0, count = remoteFolders.length; i < count; i++) { remoteFolderNames.add(remoteFolders[i].getName()); } HashMap<String, LocalMailboxInfo> localFolders = new HashMap<String, LocalMailboxInfo>(); HashSet<String> localFolderNames = new HashSet<String>(); localFolderCursor = mContext.getContentResolver().query( EmailContent.Mailbox.CONTENT_URI, LocalMailboxInfo.PROJECTION, EmailContent.MailboxColumns.ACCOUNT_KEY + "=?", new String[] { String.valueOf(account.mId) }, null); while (localFolderCursor.moveToNext()) { LocalMailboxInfo info = new LocalMailboxInfo(localFolderCursor); localFolders.put(info.mDisplayName, info); localFolderNames.add(info.mDisplayName); } // Short circuit the rest if the sets are the same (the usual case) if (!remoteFolderNames.equals(localFolderNames)) { // They are different, so we have to do some adds and drops // Drops first, to make things smaller rather than larger HashSet<String> localsToDrop = new HashSet<String>(localFolderNames); localsToDrop.removeAll(remoteFolderNames); for (String localNameToDrop : localsToDrop) { LocalMailboxInfo localInfo = localFolders.get(localNameToDrop); // Exclusion list - never delete local special folders, irrespective // of server-side existence. switch (localInfo.mType) { case Mailbox.TYPE_INBOX: case Mailbox.TYPE_DRAFTS: case Mailbox.TYPE_OUTBOX: case Mailbox.TYPE_SENT: case Mailbox.TYPE_TRASH: break; default: // Drop all attachment files related to this mailbox AttachmentProvider.deleteAllMailboxAttachmentFiles( mContext, accountId, localInfo.mId); // Delete the mailbox. Triggers will take care of // related Message, Body and Attachment records. Uri uri = ContentUris.withAppendedId( EmailContent.Mailbox.CONTENT_URI, localInfo.mId); mContext.getContentResolver().delete(uri, null, null); break; } } // Now do the adds remoteFolderNames.removeAll(localFolderNames); for (String remoteNameToAdd : remoteFolderNames) { EmailContent.Mailbox box = new EmailContent.Mailbox(); box.mDisplayName = remoteNameToAdd; // box.mServerId; // box.mParentServerId; box.mAccountKey = account.mId; box.mType = LegacyConversions.inferMailboxTypeFromName( mContext, remoteNameToAdd); // box.mDelimiter; // box.mSyncKey; // box.mSyncLookback; // box.mSyncFrequency; // box.mSyncTime; // box.mUnreadCount; box.mFlagVisible = true; // box.mFlags; box.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT; box.save(mContext); } } mListeners.listFoldersFinished(accountId); } catch (Exception e) { mListeners.listFoldersFailed(accountId, ""); } finally { if (localFolderCursor != null) { localFolderCursor.close(); } } } }); } /** * Start background synchronization of the specified folder. * @param account * @param folder * @param listener */ public void synchronizeMailbox(final EmailContent.Account account, final EmailContent.Mailbox folder, MessagingListener listener) { /* * We don't ever sync the Outbox. */ if (folder.mType == EmailContent.Mailbox.TYPE_OUTBOX) { return; } mListeners.synchronizeMailboxStarted(account.mId, folder.mId); put("synchronizeMailbox", listener, new Runnable() { public void run() { synchronizeMailboxSynchronous(account, folder); } }); } /** * Start foreground synchronization of the specified folder. This is called by * synchronizeMailbox or checkMail. * TODO this should use ID's instead of fully-restored objects * @param account * @param folder */ private void synchronizeMailboxSynchronous(final EmailContent.Account account, final EmailContent.Mailbox folder) { mListeners.synchronizeMailboxStarted(account.mId, folder.mId); try { processPendingActionsSynchronous(account); StoreSynchronizer.SyncResults results; // Select generic sync or store-specific sync Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); StoreSynchronizer customSync = remoteStore.getMessageSynchronizer(); if (customSync == null) { results = synchronizeMailboxGeneric(account, folder); } else { results = customSync.SynchronizeMessagesSynchronous( account, folder, mListeners, mContext); } mListeners.synchronizeMailboxFinished(account.mId, folder.mId, results.mTotalMessages, results.mNewMessages); } catch (MessagingException e) { if (Email.LOGD) { Log.v(Email.LOG_TAG, "synchronizeMailbox", e); } mListeners.synchronizeMailboxFailed(account.mId, folder.mId, e); } } /** * Lightweight record for the first pass of message sync, where I'm just seeing if * the local message requires sync. Later (for messages that need syncing) we'll do a full * readout from the DB. */ private static class LocalMessageInfo { private static final int COLUMN_ID = 0; private static final int COLUMN_FLAG_READ = 1; private static final int COLUMN_FLAG_FAVORITE = 2; private static final int COLUMN_FLAG_LOADED = 3; private static final int COLUMN_SERVER_ID = 4; private static final String[] PROJECTION = new String[] { EmailContent.RECORD_ID, MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_LOADED, SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY }; int mCursorIndex; long mId; boolean mFlagRead; boolean mFlagFavorite; int mFlagLoaded; String mServerId; public LocalMessageInfo(Cursor c) { mCursorIndex = c.getPosition(); mId = c.getLong(COLUMN_ID); mFlagRead = c.getInt(COLUMN_FLAG_READ) != 0; mFlagFavorite = c.getInt(COLUMN_FLAG_FAVORITE) != 0; mFlagLoaded = c.getInt(COLUMN_FLAG_LOADED); mServerId = c.getString(COLUMN_SERVER_ID); // Note: mailbox key and account key not needed - they are projected for the SELECT } } private void saveOrUpdate(EmailContent content) { if (content.isSaved()) { content.update(mContext, content.toContentValues()); } else { content.save(mContext); } } /** * Generic synchronizer - used for POP3 and IMAP. * * TODO Break this method up into smaller chunks. * * @param account the account to sync * @param folder the mailbox to sync * @return results of the sync pass * @throws MessagingException */ private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } - if (localMessage == null - || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED) - || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) { + // localMessage == null -> message has never been created (not even headers) + // mFlagLoaded = UNLOADED -> message created, but none of body loaded + // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded + // mFlagLoaded = COMPLETE -> message body has been completely loaded + // mFlagLoaded = DELETED -> message has been deleted + // Only the first two of these are "unsynced", so let's retrieve them + if (localMessage == null || + (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } public void messageStarted(String uid, int number, int ofTotal) { } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } public void messageStarted(String uid, int number, int ofTotal) { } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); } /** * Copy one downloaded message (which may have partially-loaded sections) * into a provider message * * @param message the remote message we've just downloaded * @param account the account it will be stored into * @param folder the mailbox it will be stored into * @param loadStatus when complete, the message will be marked with this status (e.g. * EmailContent.Message.LOADED) */ private void copyOneMessageToProvider(Message message, EmailContent.Account account, EmailContent.Mailbox folder, int loadStatus) { try { EmailContent.Message localMessage = null; Cursor c = null; try { c = mContext.getContentResolver().query( EmailContent.Message.CONTENT_URI, EmailContent.Message.CONTENT_PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + SyncColumns.SERVER_ID + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId), String.valueOf(message.getUid()) }, null); if (c.moveToNext()) { localMessage = EmailContent.getContent(c, EmailContent.Message.class); } } finally { if (c != null) { c.close(); } } if (localMessage == null) { Log.d(Email.LOG_TAG, "Could not retrieve message from db, UUID=" + message.getUid()); return; } EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(mContext, localMessage.mId); if (body == null) { body = new EmailContent.Body(); } try { // Copy the fields that are available into the message object LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Now process body parts & attachments ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); LegacyConversions.updateBodyFields(body, localMessage, viewables); // Commit the message & body to the local store immediately saveOrUpdate(localMessage); saveOrUpdate(body); // process (and save) attachments LegacyConversions.updateAttachments(mContext, localMessage, attachments, false); // One last update of message with two updated flags localMessage.mFlagLoaded = loadStatus; ContentValues cv = new ContentValues(); cv.put(EmailContent.MessageColumns.FLAG_ATTACHMENT, localMessage.mFlagAttachment); cv.put(EmailContent.MessageColumns.FLAG_LOADED, localMessage.mFlagLoaded); Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, localMessage.mId); mContext.getContentResolver().update(uri, cv, null, null); } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } catch (RuntimeException rte) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + rte.toString()); } catch (IOException ioe) { Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString()); } } public void processPendingActions(final long accountId) { put("processPendingActions", null, new Runnable() { public void run() { try { EmailContent.Account account = EmailContent.Account.restoreAccountWithId(mContext, accountId); if (account == null) { return; } processPendingActionsSynchronous(account); } catch (MessagingException me) { if (Email.LOGD) { Log.v(Email.LOG_TAG, "processPendingActions", me); } /* * Ignore any exceptions from the commands. Commands will be processed * on the next round. */ } } }); } /** * Find messages in the updated table that need to be written back to server. * * Handles: * Read/Unread * Flagged * Append (upload) * Move To Trash * Empty trash * TODO: * Move * * @param account the account to scan for pending actions * @throws MessagingException */ private void processPendingActionsSynchronous(EmailContent.Account account) throws MessagingException { ContentResolver resolver = mContext.getContentResolver(); String[] accountIdArgs = new String[] { Long.toString(account.mId) }; // Handle deletes first, it's always better to get rid of things first processPendingDeletesSynchronous(account, resolver, accountIdArgs); // Handle uploads (currently, only to sent messages) processPendingUploadsSynchronous(account, resolver, accountIdArgs); // Now handle updates / upsyncs processPendingUpdatesSynchronous(account, resolver, accountIdArgs); } /** * Scan for messages that are in the Message_Deletes table, look for differences that * we can deal with, and do the work. * * @param account * @param resolver * @param accountIdArgs */ private void processPendingDeletesSynchronous(EmailContent.Account account, ContentResolver resolver, String[] accountIdArgs) { Cursor deletes = resolver.query(EmailContent.Message.DELETED_CONTENT_URI, EmailContent.Message.CONTENT_PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs, EmailContent.MessageColumns.MAILBOX_KEY); long lastMessageId = -1; try { // Defer setting up the store until we know we need to access it Store remoteStore = null; // Demand load mailbox (note order-by to reduce thrashing here) Mailbox mailbox = null; // loop through messages marked as deleted while (deletes.moveToNext()) { boolean deleteFromTrash = false; EmailContent.Message oldMessage = EmailContent.getContent(deletes, EmailContent.Message.class); lastMessageId = oldMessage.mId; if (oldMessage != null) { if (mailbox == null || mailbox.mId != oldMessage.mMailboxKey) { mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); } deleteFromTrash = mailbox.mType == Mailbox.TYPE_TRASH; } // Load the remote store if it will be needed if (remoteStore == null && deleteFromTrash) { remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); } // Dispatch here for specific change types if (deleteFromTrash) { // Move message to trash processPendingDeleteFromTrash(remoteStore, account, mailbox, oldMessage); } // Finally, delete the update Uri uri = ContentUris.withAppendedId(EmailContent.Message.DELETED_CONTENT_URI, oldMessage.mId); resolver.delete(uri, null, null); } } catch (MessagingException me) { // Presumably an error here is an account connection failure, so there is // no point in continuing through the rest of the pending updates. if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Unable to process pending delete for id=" + lastMessageId + ": " + me); } } finally { deletes.close(); } } /** * Scan for messages that are in Sent, and are in need of upload, * and send them to the server. "In need of upload" is defined as: * serverId == null (no UID has been assigned) * or * message is in the updated list * * Note we also look for messages that are moving from drafts->outbox->sent. They never * go through "drafts" or "outbox" on the server, so we hang onto these until they can be * uploaded directly to the Sent folder. * * @param account * @param resolver * @param accountIdArgs */ private void processPendingUploadsSynchronous(EmailContent.Account account, ContentResolver resolver, String[] accountIdArgs) throws MessagingException { // Find the Sent folder (since that's all we're uploading for now Cursor mailboxes = resolver.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=?" + " and " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_SENT, accountIdArgs, null); long lastMessageId = -1; try { // Defer setting up the store until we know we need to access it Store remoteStore = null; while (mailboxes.moveToNext()) { long mailboxId = mailboxes.getLong(Mailbox.ID_PROJECTION_COLUMN); String[] mailboxKeyArgs = new String[] { Long.toString(mailboxId) }; // Demand load mailbox Mailbox mailbox = null; // First handle the "new" messages (serverId == null) Cursor upsyncs1 = resolver.query(EmailContent.Message.CONTENT_URI, EmailContent.Message.ID_PROJECTION, EmailContent.Message.MAILBOX_KEY + "=?" + " and (" + EmailContent.Message.SERVER_ID + " is null" + " or " + EmailContent.Message.SERVER_ID + "=''" + ")", mailboxKeyArgs, null); try { while (upsyncs1.moveToNext()) { // Load the remote store if it will be needed if (remoteStore == null) { remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); } // Load the mailbox if it will be needed if (mailbox == null) { mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); } // upsync the message long id = upsyncs1.getLong(EmailContent.Message.ID_PROJECTION_COLUMN); lastMessageId = id; processUploadMessage(resolver, remoteStore, account, mailbox, id); } } finally { if (upsyncs1 != null) { upsyncs1.close(); } } // Next, handle any updates (e.g. edited in place, although this shouldn't happen) Cursor upsyncs2 = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI, EmailContent.Message.ID_PROJECTION, EmailContent.MessageColumns.MAILBOX_KEY + "=?", mailboxKeyArgs, null); try { while (upsyncs2.moveToNext()) { // Load the remote store if it will be needed if (remoteStore == null) { remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); } // Load the mailbox if it will be needed if (mailbox == null) { mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); } // upsync the message long id = upsyncs2.getLong(EmailContent.Message.ID_PROJECTION_COLUMN); lastMessageId = id; processUploadMessage(resolver, remoteStore, account, mailbox, id); } } finally { if (upsyncs2 != null) { upsyncs2.close(); } } } } catch (MessagingException me) { // Presumably an error here is an account connection failure, so there is // no point in continuing through the rest of the pending updates. if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Unable to process pending upsync for id=" + lastMessageId + ": " + me); } } finally { if (mailboxes != null) { mailboxes.close(); } } } /** * Scan for messages that are in the Message_Updates table, look for differences that * we can deal with, and do the work. * * @param account * @param resolver * @param accountIdArgs */ private void processPendingUpdatesSynchronous(EmailContent.Account account, ContentResolver resolver, String[] accountIdArgs) { Cursor updates = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI, EmailContent.Message.CONTENT_PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs, EmailContent.MessageColumns.MAILBOX_KEY); long lastMessageId = -1; try { // Defer setting up the store until we know we need to access it Store remoteStore = null; // Demand load mailbox (note order-by to reduce thrashing here) Mailbox mailbox = null; // loop through messages marked as needing updates while (updates.moveToNext()) { boolean changeMoveToTrash = false; boolean changeRead = false; boolean changeFlagged = false; EmailContent.Message oldMessage = EmailContent.getContent(updates, EmailContent.Message.class); lastMessageId = oldMessage.mId; EmailContent.Message newMessage = EmailContent.Message.restoreMessageWithId(mContext, oldMessage.mId); if (newMessage != null) { if (mailbox == null || mailbox.mId != newMessage.mMailboxKey) { mailbox = Mailbox.restoreMailboxWithId(mContext, newMessage.mMailboxKey); } changeMoveToTrash = (oldMessage.mMailboxKey != newMessage.mMailboxKey) && (mailbox.mType == Mailbox.TYPE_TRASH); changeRead = oldMessage.mFlagRead != newMessage.mFlagRead; changeFlagged = oldMessage.mFlagFavorite != newMessage.mFlagFavorite; } // Load the remote store if it will be needed if (remoteStore == null && (changeMoveToTrash || changeRead || changeFlagged)) { remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); } // Dispatch here for specific change types if (changeMoveToTrash) { // Move message to trash processPendingMoveToTrash(remoteStore, account, mailbox, oldMessage, newMessage); } else if (changeRead || changeFlagged) { processPendingFlagChange(remoteStore, mailbox, changeRead, changeFlagged, newMessage); } // Finally, delete the update Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI, oldMessage.mId); resolver.delete(uri, null, null); } } catch (MessagingException me) { // Presumably an error here is an account connection failure, so there is // no point in continuing through the rest of the pending updates. if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Unable to process pending update for id=" + lastMessageId + ": " + me); } } finally { updates.close(); } } /** * Upsync an entire message. This must also unwind whatever triggered it (either by * updating the serverId, or by deleting the update record, or it's going to keep happening * over and over again. * * Note: If the message is being uploaded into an unexpected mailbox, we *do not* upload. * This is to avoid unnecessary uploads into the trash. Although the caller attempts to select * only the Drafts and Sent folders, this can happen when the update record and the current * record mismatch. In this case, we let the update record remain, because the filters * in processPendingUpdatesSynchronous() will pick it up as a move and handle it (or drop it) * appropriately. * * @param resolver * @param remoteStore * @param account * @param mailbox the actual mailbox * @param messageId */ private void processUploadMessage(ContentResolver resolver, Store remoteStore, EmailContent.Account account, Mailbox mailbox, long messageId) throws MessagingException { EmailContent.Message message = EmailContent.Message.restoreMessageWithId(mContext, messageId); boolean deleteUpdate = false; if (message == null) { deleteUpdate = true; Log.d(Email.LOG_TAG, "Upsync failed for null message, id=" + messageId); } else if (mailbox.mType == Mailbox.TYPE_DRAFTS) { deleteUpdate = false; Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=drafts, id=" + messageId); } else if (mailbox.mType == Mailbox.TYPE_OUTBOX) { deleteUpdate = false; Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=outbox, id=" + messageId); } else if (mailbox.mType == Mailbox.TYPE_TRASH) { deleteUpdate = false; Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=trash, id=" + messageId); } else { Log.d(Email.LOG_TAG, "Upsyc triggered for message id=" + messageId); deleteUpdate = processPendingAppend(remoteStore, account, mailbox, message); } if (deleteUpdate) { // Finally, delete the update (if any) Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI, messageId); resolver.delete(uri, null, null); } } /** * Upsync changes to read or flagged * * @param remoteStore * @param mailbox * @param changeRead * @param changeFlagged * @param newMessage */ private void processPendingFlagChange(Store remoteStore, Mailbox mailbox, boolean changeRead, boolean changeFlagged, EmailContent.Message newMessage) throws MessagingException { // 0. No remote update if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. No remote update for DRAFTS or OUTBOX if (mailbox.mType == Mailbox.TYPE_DRAFTS || mailbox.mType == Mailbox.TYPE_OUTBOX) { return; } // 2. Open the remote store & folder Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return; } // 3. Finally, apply the changes to the message Message remoteMessage = remoteFolder.getMessage(newMessage.mServerId); if (remoteMessage == null) { return; } if (Email.DEBUG) { Log.d(Email.LOG_TAG, "Update flags for msg id=" + newMessage.mId + " read=" + newMessage.mFlagRead + " flagged=" + newMessage.mFlagFavorite); } Message[] messages = new Message[] { remoteMessage }; if (changeRead) { remoteFolder.setFlags(messages, FLAG_LIST_SEEN, newMessage.mFlagRead); } if (changeFlagged) { remoteFolder.setFlags(messages, FLAG_LIST_FLAGGED, newMessage.mFlagFavorite); } } /** * Process a pending trash message command. * * @param remoteStore the remote store we're working in * @param account The account in which we are working * @param newMailbox The local trash mailbox * @param oldMessage The message copy that was saved in the updates shadow table * @param newMessage The message that was moved to the mailbox */ private void processPendingMoveToTrash(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage, final EmailContent.Message newMessage) throws MessagingException { // 0. No remote move if the message is local-only if (newMessage.mServerId == null || newMessage.mServerId.equals("") || newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) { return; } // 1. Escape early if we can't find the local mailbox // TODO smaller projection here Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey); if (oldMailbox == null) { // can't find old mailbox, it may have been deleted. just return. return; } // 2. We don't support delete-from-trash here if (oldMailbox.mType == Mailbox.TYPE_TRASH) { return; } // 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return // // This sentinel takes the place of the server-side message, and locally "deletes" it // by inhibiting future sync or display of the message. It will eventually go out of // scope when it becomes old, or is deleted on the server, and the regular sync code // will clean it up for us. if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) { EmailContent.Message sentinel = new EmailContent.Message(); sentinel.mAccountKey = oldMessage.mAccountKey; sentinel.mMailboxKey = oldMessage.mMailboxKey; sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED; sentinel.mFlagRead = true; sentinel.mServerId = oldMessage.mServerId; sentinel.save(mContext); return; } // The rest of this method handles server-side deletion // 4. Find the remote mailbox (that we deleted from), and open it Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteFolder.exists()) { return; } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); return; } // 5. Find the remote original message Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteFolder.close(false); return; } // 6. Find the remote trash folder, and create it if not found Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { /* * If the remote trash folder doesn't exist we try to create it. */ remoteTrashFolder.create(FolderType.HOLDS_MESSAGES); } // 7. Try to copy the message into the remote trash folder // Note, this entire section will be skipped for POP3 because there's no remote trash if (remoteTrashFolder.exists()) { /* * Because remoteTrashFolder may be new, we need to explicitly open it */ remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteFolder.close(false); remoteTrashFolder.close(false); return; } remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder, new Folder.MessageUpdateCallbacks() { public void onMessageUidChange(Message message, String newUid) { // update the UID in the local trash folder, because some stores will // have to change it when copying to remoteTrashFolder ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, newUid); mContext.getContentResolver().update(newMessage.getUri(), cv, null, null); } /** * This will be called if the deleted message doesn't exist and can't be * deleted (e.g. it was already deleted from the server.) In this case, * attempt to delete the local copy as well. */ public void onMessageNotFound(Message message) { mContext.getContentResolver().delete(newMessage.getUri(), null, null); } } ); remoteTrashFolder.close(false); } // 8. Delete the message from the remote source folder remoteMessage.setFlag(Flag.DELETED, true); remoteFolder.expunge(); remoteFolder.close(false); } /** * Process a pending trash message command. * * @param remoteStore the remote store we're working in * @param account The account in which we are working * @param oldMailbox The local trash mailbox * @param oldMessage The message that was deleted from the trash */ private void processPendingDeleteFromTrash(Store remoteStore, EmailContent.Account account, Mailbox oldMailbox, EmailContent.Message oldMessage) throws MessagingException { // 1. We only support delete-from-trash here if (oldMailbox.mType != Mailbox.TYPE_TRASH) { return; } // 2. Find the remote trash folder (that we are deleting from), and open it Folder remoteTrashFolder = remoteStore.getFolder(oldMailbox.mDisplayName); if (!remoteTrashFolder.exists()) { return; } remoteTrashFolder.open(OpenMode.READ_WRITE, null); if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) { remoteTrashFolder.close(false); return; } // 3. Find the remote original message Message remoteMessage = remoteTrashFolder.getMessage(oldMessage.mServerId); if (remoteMessage == null) { remoteTrashFolder.close(false); return; } // 4. Delete the message from the remote trash folder remoteMessage.setFlag(Flag.DELETED, true); remoteTrashFolder.expunge(); remoteTrashFolder.close(false); } /** * Process a pending append message command. This command uploads a local message to the * server, first checking to be sure that the server message is not newer than * the local message. * * @param remoteStore the remote store we're working in * @param account The account in which we are working * @param newMailbox The mailbox we're appending to * @param message The message we're appending * @return true if successfully uploaded */ private boolean processPendingAppend(Store remoteStore, EmailContent.Account account, Mailbox newMailbox, EmailContent.Message message) throws MessagingException { boolean updateInternalDate = false; boolean updateMessage = false; boolean deleteMessage = false; // 1. Find the remote folder that we're appending to and create and/or open it Folder remoteFolder = remoteStore.getFolder(newMailbox.mDisplayName); if (!remoteFolder.exists()) { if (!remoteFolder.canCreate(FolderType.HOLDS_MESSAGES)) { // This is POP3, we cannot actually upload. Instead, we'll update the message // locally with a fake serverId (so we don't keep trying here) and return. if (message.mServerId == null || message.mServerId.length() == 0) { message.mServerId = LOCAL_SERVERID_PREFIX + message.mId; Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId); ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, message.mServerId); mContext.getContentResolver().update(uri, cv, null, null); } return true; } if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { // This is a (hopefully) transient error and we return false to try again later return false; } } remoteFolder.open(OpenMode.READ_WRITE, null); if (remoteFolder.getMode() != OpenMode.READ_WRITE) { return false; } // 2. If possible, load a remote message with the matching UID Message remoteMessage = null; if (message.mServerId != null && message.mServerId.length() > 0) { remoteMessage = remoteFolder.getMessage(message.mServerId); } // 3. If a remote message could not be found, upload our local message if (remoteMessage == null) { // 3a. Create a legacy message to upload Message localMessage = LegacyConversions.makeMessage(mContext, message); // 3b. Upload it FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.appendMessages(new Message[] { localMessage }); // 3b. And record the UID from the server message.mServerId = localMessage.getUid(); updateInternalDate = true; updateMessage = true; } else { // 4. If the remote message exists we need to determine which copy to keep. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); Date localDate = new Date(message.mServerTimeStamp); Date remoteDate = remoteMessage.getInternalDate(); if (remoteDate.compareTo(localDate) > 0) { // 4a. If the remote message is newer than ours we'll just // delete ours and move on. A sync will get the server message // if we need to be able to see it. deleteMessage = true; } else { // 4b. Otherwise we'll upload our message and then delete the remote message. // Create a legacy message to upload Message localMessage = LegacyConversions.makeMessage(mContext, message); // 4c. Upload it fp.clear(); fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.appendMessages(new Message[] { localMessage }); // 4d. Record the UID and new internalDate from the server message.mServerId = localMessage.getUid(); updateInternalDate = true; updateMessage = true; // 4e. And delete the old copy of the message from the server remoteMessage.setFlag(Flag.DELETED, true); } } // 5. If requested, Best-effort to capture new "internaldate" from the server if (updateInternalDate && message.mServerId != null) { try { Message remoteMessage2 = remoteFolder.getMessage(message.mServerId); if (remoteMessage2 != null) { FetchProfile fp2 = new FetchProfile(); fp2.add(FetchProfile.Item.ENVELOPE); remoteFolder.fetch(new Message[] { remoteMessage2 }, fp2, null); message.mServerTimeStamp = remoteMessage2.getInternalDate().getTime(); updateMessage = true; } } catch (MessagingException me) { // skip it - we can live without this } } // 6. Perform required edits to local copy of message if (deleteMessage || updateMessage) { Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId); ContentResolver resolver = mContext.getContentResolver(); if (deleteMessage) { resolver.delete(uri, null, null); } else if (updateMessage) { ContentValues cv = new ContentValues(); cv.put(EmailContent.Message.SERVER_ID, message.mServerId); cv.put(EmailContent.Message.SERVER_TIMESTAMP, message.mServerTimeStamp); resolver.update(uri, cv, null, null); } } return true; } /** * Finish loading a message that have been partially downloaded. * * @param messageId the message to load * @param listener the callback by which results will be reported */ public void loadMessageForView(final long messageId, MessagingListener listener) { mListeners.loadMessageForViewStarted(messageId); put("loadMessageForViewRemote", listener, new Runnable() { public void run() { try { // 1. Resample the message, in case it disappeared or synced while // this command was in queue EmailContent.Message message = EmailContent.Message.restoreMessageWithId(mContext, messageId); if (message == null) { mListeners.loadMessageForViewFailed(messageId, "Unknown message"); return; } if (message.mFlagLoaded == EmailContent.Message.FLAG_LOADED_COMPLETE) { mListeners.loadMessageForViewFinished(messageId); return; } // 2. Open the remote folder. // TODO all of these could be narrower projections // TODO combine with common code in loadAttachment EmailContent.Account account = EmailContent.Account.restoreAccountWithId(mContext, message.mAccountKey); EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey); if (account == null || mailbox == null) { mListeners.loadMessageForViewFailed(messageId, "null account or mailbox"); return; } Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName); remoteFolder.open(OpenMode.READ_WRITE, null); // 3. Not supported, because IMAP & POP don't use it: structure prefetch // if (remoteStore.requireStructurePrefetch()) { // // For remote stores that require it, prefetch the message structure. // FetchProfile fp = new FetchProfile(); // fp.add(FetchProfile.Item.STRUCTURE); // localFolder.fetch(new Message[] { message }, fp, null); // // ArrayList<Part> viewables = new ArrayList<Part>(); // ArrayList<Part> attachments = new ArrayList<Part>(); // MimeUtility.collectParts(message, viewables, attachments); // fp.clear(); // for (Part part : viewables) { // fp.add(part); // } // // remoteFolder.fetch(new Message[] { message }, fp, null); // // // Store the updated message locally // localFolder.updateMessage((LocalMessage)message); // 4. Set up to download the entire message Message remoteMessage = remoteFolder.getMessage(message.mServerId); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(new Message[] { remoteMessage }, fp, null); // 5. Write to provider copyOneMessageToProvider(remoteMessage, account, mailbox, EmailContent.Message.FLAG_LOADED_COMPLETE); // 6. Notify UI mListeners.loadMessageForViewFinished(messageId); } catch (MessagingException me) { if (Email.LOGD) Log.v(Email.LOG_TAG, "", me); mListeners.loadMessageForViewFailed(messageId, me.getMessage()); } catch (RuntimeException rte) { mListeners.loadMessageForViewFailed(messageId, rte.getMessage()); } } }); } /** * Attempts to load the attachment specified by id from the given account and message. * @param account * @param message * @param part * @param listener */ public void loadAttachment(final long accountId, final long messageId, final long mailboxId, final long attachmentId, MessagingListener listener) { mListeners.loadAttachmentStarted(accountId, messageId, attachmentId, true); put("loadAttachment", listener, new Runnable() { public void run() { try { //1. Check if the attachment is already here and return early in that case File saveToFile = AttachmentProvider.getAttachmentFilename(mContext, accountId, attachmentId); Attachment attachment = Attachment.restoreAttachmentWithId(mContext, attachmentId); if (attachment == null) { mListeners.loadAttachmentFailed(accountId, messageId, attachmentId, "Attachment is null"); return; } if (saveToFile.exists() && attachment.mContentUri != null) { mListeners.loadAttachmentFinished(accountId, messageId, attachmentId); return; } // 2. Open the remote folder. // TODO all of these could be narrower projections EmailContent.Account account = EmailContent.Account.restoreAccountWithId(mContext, accountId); EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(mContext, mailboxId); EmailContent.Message message = EmailContent.Message.restoreMessageWithId(mContext, messageId); if (account == null || mailbox == null || message == null) { mListeners.loadAttachmentFailed(accountId, messageId, attachmentId, "Account, mailbox, message or attachment are null"); return; } // Pruning. Policy is to have one downloaded attachment at a time, // per account, to reduce disk storage pressure. pruneCachedAttachments(accountId); Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName); remoteFolder.open(OpenMode.READ_WRITE, null); // 3. Generate a shell message in which to retrieve the attachment, // and a shell BodyPart for the attachment. Then glue them together. Message storeMessage = remoteFolder.createMessage(message.mServerId); MimeBodyPart storePart = new MimeBodyPart(); storePart.setSize((int)attachment.mSize); storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA, attachment.mLocation); storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n name=\"%s\"", attachment.mMimeType, attachment.mFileName)); // TODO is this always true for attachments? I think we dropped the // true encoding along the way storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64"); MimeMultipart multipart = new MimeMultipart(); multipart.setSubType("mixed"); multipart.addBodyPart(storePart); storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed"); storeMessage.setBody(multipart); // 4. Now ask for the attachment to be fetched FetchProfile fp = new FetchProfile(); fp.add(storePart); remoteFolder.fetch(new Message[] { storeMessage }, fp, null); // 5. Save the downloaded file and update the attachment as necessary LegacyConversions.saveAttachmentBody(mContext, storePart, attachment, accountId); // 6. Report success mListeners.loadAttachmentFinished(accountId, messageId, attachmentId); } catch (MessagingException me) { if (Email.LOGD) Log.v(Email.LOG_TAG, "", me); mListeners.loadAttachmentFailed(accountId, messageId, attachmentId, me.getMessage()); } catch (IOException ioe) { Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString()); } }}); } /** * Erase all stored attachments for a given account. Rules: * 1. All files in attachment directory are up for deletion * 2. If filename does not match an known attachment id, it's deleted * 3. If the attachment has location data (implying that it's reloadable), it's deleted */ /* package */ void pruneCachedAttachments(long accountId) { ContentResolver resolver = mContext.getContentResolver(); File cacheDir = AttachmentProvider.getAttachmentDirectory(mContext, accountId); File[] fileList = cacheDir.listFiles(); // fileList can be null if the directory doesn't exist or if there's an IOException if (fileList == null) return; for (File file : fileList) { if (file.exists()) { long id; try { // the name of the file == the attachment id id = Long.valueOf(file.getName()); Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, id); Cursor c = resolver.query(uri, PRUNE_ATTACHMENT_PROJECTION, null, null, null); try { if (c.moveToNext()) { // if there is no way to reload the attachment, don't delete it if (c.getString(0) == null) { continue; } } } finally { c.close(); } // Clear the content URI field since we're losing the attachment resolver.update(uri, PRUNE_ATTACHMENT_CV, null, null); } catch (NumberFormatException nfe) { // ignore filename != number error, and just delete it anyway } // This file can be safely deleted if (!file.delete()) { file.deleteOnExit(); } } } } /** * Attempt to send any messages that are sitting in the Outbox. * @param account * @param listener */ public void sendPendingMessages(final EmailContent.Account account, final long sentFolderId, MessagingListener listener) { put("sendPendingMessages", listener, new Runnable() { public void run() { sendPendingMessagesSynchronous(account, sentFolderId); } }); } /** * Attempt to send any messages that are sitting in the Outbox. * * @param account * @param listener */ public void sendPendingMessagesSynchronous(final EmailContent.Account account, long sentFolderId) { // 1. Loop through all messages in the account's outbox long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX); if (outboxId == Mailbox.NO_MAILBOX) { return; } ContentResolver resolver = mContext.getContentResolver(); Cursor c = resolver.query(EmailContent.Message.CONTENT_URI, EmailContent.Message.ID_COLUMN_PROJECTION, EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) }, null); try { // 2. exit early if (c.getCount() <= 0) { return; } // 3. do one-time setup of the Sender & other stuff mListeners.sendPendingMessagesStarted(account.mId, -1); Sender sender = Sender.getInstance(mContext, account.getSenderUri(mContext)); Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); boolean requireMoveMessageToSentFolder = remoteStore.requireCopyMessageToSentFolder(); ContentValues moveToSentValues = null; if (requireMoveMessageToSentFolder) { moveToSentValues = new ContentValues(); moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolderId); } // 4. loop through the available messages and send them while (c.moveToNext()) { long messageId = -1; try { messageId = c.getLong(0); mListeners.sendPendingMessagesStarted(account.mId, messageId); sender.sendMessage(messageId); } catch (MessagingException me) { // report error for this message, but keep trying others mListeners.sendPendingMessagesFailed(account.mId, messageId, me); continue; } // 5. move to sent, or delete Uri syncedUri = ContentUris.withAppendedId(EmailContent.Message.SYNCED_CONTENT_URI, messageId); if (requireMoveMessageToSentFolder) { resolver.update(syncedUri, moveToSentValues, null, null); } else { AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, messageId); Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId); resolver.delete(uri, null, null); resolver.delete(syncedUri, null, null); } } // 6. report completion/success mListeners.sendPendingMessagesCompleted(account.mId); } catch (MessagingException me) { mListeners.sendPendingMessagesFailed(account.mId, -1, me); } finally { c.close(); } } /** * Checks mail for one or multiple accounts. If account is null all accounts * are checked. This entry point is for use by the mail checking service only, because it * gives slightly different callbacks (so the service doesn't get confused by callbacks * triggered by/for the foreground UI. * * TODO clean up the execution model which is unnecessarily threaded due to legacy code * * @param context * @param accountId the account to check * @param listener */ public void checkMail(final long accountId, final long tag, final MessagingListener listener) { mListeners.checkMailStarted(mContext, accountId, tag); // This puts the command on the queue (not synchronous) listFolders(accountId, null); // Put this on the queue as well so it follows listFolders put("checkMail", listener, new Runnable() { public void run() { // send any pending outbound messages. note, there is a slight race condition // here if we somehow don't have a sent folder, but this should never happen // because the call to sendMessage() would have built one previously. long inboxId = -1; EmailContent.Account account = EmailContent.Account.restoreAccountWithId(mContext, accountId); if (account != null) { long sentboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_SENT); if (sentboxId != Mailbox.NO_MAILBOX) { sendPendingMessagesSynchronous(account, sentboxId); } // find mailbox # for inbox and sync it. // TODO we already know this in Controller, can we pass it in? inboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX); if (inboxId != Mailbox.NO_MAILBOX) { EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(mContext, inboxId); if (mailbox != null) { synchronizeMailboxSynchronous(account, mailbox); } } } mListeners.checkMailFinished(mContext, accountId, inboxId, tag); } }); } private static class Command { public Runnable runnable; public MessagingListener listener; public String description; @Override public String toString() { return description; } } }
true
true
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED) || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } public void messageStarted(String uid, int number, int ofTotal) { } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } public void messageStarted(String uid, int number, int ofTotal) { } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric( final EmailContent.Account account, final EmailContent.Mailbox folder) throws MessagingException { Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***"); ContentResolver resolver = mContext.getContentResolver(); // 0. We do not ever sync DRAFTS or OUTBOX (down or up) if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) { int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null); return new StoreSynchronizer.SyncResults(totalMessages, 0); } // 1. Get the message list from the local store and create an index of the uids Cursor localUidCursor = null; HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>(); try { localUidCursor = resolver.query( EmailContent.Message.CONTENT_URI, LocalMessageInfo.PROJECTION, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }, null); while (localUidCursor.moveToNext()) { LocalMessageInfo info = new LocalMessageInfo(localUidCursor); localMessageMap.put(info.mServerId, info); } } finally { if (localUidCursor != null) { localUidCursor.close(); } } // 1a. Count the unread messages before changing anything int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI, EmailContent.MessageColumns.ACCOUNT_KEY + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?" + " AND " + MessageColumns.FLAG_READ + "=0", new String[] { String.valueOf(account.mId), String.valueOf(folder.mId) }); // 2. Open the remote folder and create the remote folder if necessary Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null); Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName); /* * If the folder is a "special" folder we need to see if it exists * on the remote server. It if does not exist we'll try to create it. If we * can't create we'll abort. This will happen on every single Pop3 folder as * designed and on Imap folders during error conditions. This allows us * to treat Pop3 and Imap the same in this code. */ if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT || folder.mType == Mailbox.TYPE_DRAFTS) { if (!remoteFolder.exists()) { if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) { return new StoreSynchronizer.SyncResults(0, 0); } } } // 3, Open the remote folder. This pre-loads certain metadata like message count. remoteFolder.open(OpenMode.READ_WRITE, null); // 4. Trash any remote messages that are marked as trashed locally. // TODO - this comment was here, but no code was here. // 5. Get the remote message count. int remoteMessageCount = remoteFolder.getMessageCount(); // 6. Determine the limit # of messages to download int visibleLimit = folder.mVisibleLimit; if (visibleLimit <= 0) { Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext), mContext); visibleLimit = info.mVisibleLimitDefault; } // 7. Create a list of messages to download Message[] remoteMessages = new Message[0]; final ArrayList<Message> unsyncedMessages = new ArrayList<Message>(); HashMap<String, Message> remoteUidMap = new HashMap<String, Message>(); int newMessageCount = 0; if (remoteMessageCount > 0) { /* * Message numbers start at 1. */ int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1; int remoteEnd = remoteMessageCount; remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null); for (Message message : remoteMessages) { remoteUidMap.put(message.getUid(), message); } /* * Get a list of the messages that are in the remote list but not on the * local store, or messages that are in the local store but failed to download * on the last sync. These are the new messages that we will download. * Note, we also skip syncing messages which are flagged as "deleted message" sentinels, * because they are locally deleted and we don't need or want the old message from * the server. */ for (Message message : remoteMessages) { LocalMessageInfo localMessage = localMessageMap.get(message.getUid()); if (localMessage == null) { newMessageCount++; } // localMessage == null -> message has never been created (not even headers) // mFlagLoaded = UNLOADED -> message created, but none of body loaded // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded // mFlagLoaded = COMPLETE -> message body has been completely loaded // mFlagLoaded = DELETED -> message has been deleted // Only the first two of these are "unsynced", so let's retrieve them if (localMessage == null || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) { unsyncedMessages.add(message); } } } // 8. Download basic info about the new/unloaded messages (if any) /* * A list of messages that were downloaded and which did not have the Seen flag set. * This will serve to indicate the true "new" message count that will be reported to * the user via notification. */ final ArrayList<Message> newMessages = new ArrayList<Message>(); /* * Fetch the flags and envelope only of the new messages. This is intended to get us * critical data as fast as possible, and then we'll fill in the details. */ if (unsyncedMessages.size() > 0) { FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); fp.add(FetchProfile.Item.ENVELOPE); final HashMap<String, LocalMessageInfo> localMapCopy = new HashMap<String, LocalMessageInfo>(localMessageMap); remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { try { // Determine if the new message was already known (e.g. partial) // And create or reload the full message info LocalMessageInfo localMessageInfo = localMapCopy.get(message.getUid()); EmailContent.Message localMessage = null; if (localMessageInfo == null) { localMessage = new EmailContent.Message(); } else { localMessage = EmailContent.Message.restoreMessageWithId( mContext, localMessageInfo.mId); } if (localMessage != null) { try { // Copy the fields that are available into the message LegacyConversions.updateMessageFields(localMessage, message, account.mId, folder.mId); // Commit the message to the local store saveOrUpdate(localMessage); // Track the "new" ness of the downloaded message if (!message.isSet(Flag.SEEN)) { newMessages.add(message); } } catch (MessagingException me) { Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me); } } } catch (Exception e) { Log.e(Email.LOG_TAG, "Error while storing downloaded message." + e.toString()); } } public void messageStarted(String uid, int number, int ofTotal) { } }); } // 9. Refresh the flags for any messages in the local store that we didn't just download. FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.FLAGS); remoteFolder.fetch(remoteMessages, fp, null); boolean remoteSupportsSeen = false; boolean remoteSupportsFlagged = false; for (Flag flag : remoteFolder.getPermanentFlags()) { if (flag == Flag.SEEN) { remoteSupportsSeen = true; } if (flag == Flag.FLAGGED) { remoteSupportsFlagged = true; } } // Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3) if (remoteSupportsSeen || remoteSupportsFlagged) { for (Message remoteMessage : remoteMessages) { LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid()); if (localMessageInfo == null) { continue; } boolean localSeen = localMessageInfo.mFlagRead; boolean remoteSeen = remoteMessage.isSet(Flag.SEEN); boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen)); boolean localFlagged = localMessageInfo.mFlagFavorite; boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED); boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged)); if (newSeen || newFlagged) { Uri uri = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, localMessageInfo.mId); ContentValues updateValues = new ContentValues(); updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen); updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged); resolver.update(uri, updateValues, null, null); } } } // 10. Compute and store the unread message count. // -- no longer necessary - Provider uses DB triggers to keep track // int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount(); // if (remoteUnreadMessageCount == -1) { // if (remoteSupportsSeenFlag) { // /* // * If remote folder doesn't supported unread message count but supports // * seen flag, use local folder's unread message count and the size of // * new messages. This mode is not used for POP3, or IMAP. // */ // // remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size(); // } else { // /* // * If remote folder doesn't supported unread message count and doesn't // * support seen flag, use localUnreadCount and newMessageCount which // * don't rely on remote SEEN flag. This mode is used by POP3. // */ // remoteUnreadMessageCount = localUnreadCount + newMessageCount; // } // } else { // /* // * If remote folder supports unread message count, use remoteUnreadMessageCount. // * This mode is used by IMAP. // */ // } // Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId); // ContentValues updateValues = new ContentValues(); // updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount); // resolver.update(uri, updateValues, null, null); // 11. Remove any messages that are in the local store but no longer on the remote store. HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet()); localUidsToDelete.removeAll(remoteUidMap.keySet()); for (String uidToDelete : localUidsToDelete) { LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete); // Delete associated data (attachment files) // Attachment & Body records are auto-deleted when we delete the Message record AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId); // Delete the message itself Uri uriToDelete = ContentUris.withAppendedId( EmailContent.Message.CONTENT_URI, infoToDelete.mId); resolver.delete(uriToDelete, null, null); // Delete extra rows (e.g. synced or deleted) Uri syncRowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(syncRowToDelete, null, null); Uri deletERowToDelete = ContentUris.withAppendedId( EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId); resolver.delete(deletERowToDelete, null, null); } // 12. Divide the unsynced messages into small & large (by size) // TODO doing this work here (synchronously) is problematic because it prevents the UI // from affecting the order (e.g. download a message because the user requested it.) Much // of this logic should move out to a different sync loop that attempts to update small // groups of messages at a time, as a background task. However, we can't just return // (yet) because POP messages don't have an envelope yet.... ArrayList<Message> largeMessages = new ArrayList<Message>(); ArrayList<Message> smallMessages = new ArrayList<Message>(); for (Message message : unsyncedMessages) { if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) { largeMessages.add(message); } else { smallMessages.add(message); } } // 13. Download small messages // TODO Problems with this implementation. 1. For IMAP, where we get a real envelope, // this is going to be inefficient and duplicate work we've already done. 2. It's going // back to the DB for a local message that we already had (and discarded). // For small messages, we specify "body", which returns everything (incl. attachments) fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp, new MessageRetrievalListener() { public void messageFinished(Message message, int number, int ofTotal) { // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } public void messageStarted(String uid, int number, int ofTotal) { } }); // 14. Download large messages. We ask the server to give us the message structure, // but not all of the attachments. fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { // POP doesn't support STRUCTURE mode, so we'll just do a partial download // (hopefully enough to see some/all of the body) and mark the message for // further download. fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); // TODO a good optimization here would be to make sure that all Stores set // the proper size after this fetch and compare the before and after size. If // they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED remoteFolder.fetch(new Message[] { message }, fp, null); // Store the partially-loaded message and mark it partially loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_PARTIAL); } else { // We have a structure to deal with, from which // we can pull down the parts we want to actually store. // Build a list of parts we are interested in. Text parts will be downloaded // right now, attachments will be left for later. ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); // Download the viewables immediately for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally and mark it fully loaded copyOneMessageToProvider(message, account, folder, EmailContent.Message.FLAG_LOADED_COMPLETE); } } // 15. Clean up and report results remoteFolder.close(false); // TODO - more // Original sync code. Using for reference, will delete when done. if (false) { /* * Now do the large messages that require more round trips. */ fp.clear(); fp.add(FetchProfile.Item.STRUCTURE); remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null); for (Message message : largeMessages) { if (message.getBody() == null) { /* * The provider was unable to get the structure of the message, so * we'll download a reasonable portion of the messge and mark it as * incomplete so the entire thing can be downloaded later if the user * wishes to download it. */ fp.clear(); fp.add(FetchProfile.Item.BODY_SANE); /* * TODO a good optimization here would be to make sure that all Stores set * the proper size after this fetch and compare the before and after size. If * they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED */ remoteFolder.fetch(new Message[] { message }, fp, null); // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating that the message has been partially downloaded and // is ready for view. // localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true); } else { /* * We have a structure to deal with, from which * we can pull down the parts we want to actually store. * Build a list of parts we are interested in. Text parts will be downloaded * right now, attachments will be left for later. */ ArrayList<Part> viewables = new ArrayList<Part>(); ArrayList<Part> attachments = new ArrayList<Part>(); MimeUtility.collectParts(message, viewables, attachments); /* * Now download the parts we're interested in storing. */ for (Part part : viewables) { fp.clear(); fp.add(part); // TODO what happens if the network connection dies? We've got partial // messages with incorrect status stored. remoteFolder.fetch(new Message[] { message }, fp, null); } // Store the updated message locally // localFolder.appendMessages(new Message[] { // message // }); // Message localMessage = localFolder.getMessage(message.getUid()); // Set a flag indicating this message has been fully downloaded and can be // viewed. // localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true); } // Update the listener with what we've found // synchronized (mListeners) { // for (MessagingListener l : mListeners) { // l.synchronizeMailboxNewMessage( // account, // folder, // localFolder.getMessage(message.getUid())); // } // } } /* * Report successful sync */ StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults( remoteFolder.getMessageCount(), newMessages.size()); remoteFolder.close(false); // localFolder.close(false); return results; } return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size()); }
diff --git a/modules/compute4/org/molgenis/compute/commandline/ArgumentParser.java b/modules/compute4/org/molgenis/compute/commandline/ArgumentParser.java index 12d70879c..4f9d2e539 100644 --- a/modules/compute4/org/molgenis/compute/commandline/ArgumentParser.java +++ b/modules/compute4/org/molgenis/compute/commandline/ArgumentParser.java @@ -1,197 +1,199 @@ package org.molgenis.compute.commandline; import java.io.File; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import org.molgenis.compute.commandline.options.Options; import org.molgenis.compute.commandline.options.Options.Multiplicity; import org.molgenis.compute.commandline.options.Options.Separator; public class ArgumentParser { static Options o; static String DEF = "DEFAULT", EMPTY = "EMPTY"; /* * The map that is returned. */ static LinkedHashMap<String, String> paramMap = new LinkedHashMap<String, String>(); /* * All command line parameters */ static List<String> parameters = Arrays.asList("inputdir", "outputdir", "workflow", "templates", "protocols", "parameters", "worksheet", "mcdir", "id"); /* * Get value of command line option 'option' in set 'set'. */ private static String getValue(String set, String option) { if (o.getSet(set).getOption(option).getResultCount() == 1) return o.getSet(set).getOption(option) .getResultValue(0); else return null; } /* * Add an obligatory parameter 'name' to parameter set 'set'. */ private static void addParam(String set, String name) { o.getSet(set).addOption(name, false, Separator.EQUALS, Multiplicity.ONCE); } /* * Add an optional parameter to set. */ private static void addParamOptional(String set, String name) { o.getSet(set).addOption(name, false, Separator.EQUALS, Multiplicity.ZERO_OR_ONE); } /* * Fill paramMap with values based on user inputs and defaults */ private static void fillParamMap(String set) { String inputdir = "input"; // is reused below // set default for inputdir paramMap.put("inputdir", inputdir); // set default for outputdir String id = "output"; paramMap.put("outputdir", inputdir + File.separator + id); // add/overwrite parameters that are not null for (String p : parameters) { String value = getValue(set, p); if (value != null) paramMap.put(p, value); } inputdir = paramMap.get("inputdir") + File.separator; if (getValue(set, "workflow") == null) paramMap.put("workflow", inputdir + "workflow.csv"); if (getValue(set, "templates") == null) paramMap.put("templates", inputdir + "templates"); if (getValue(set, "protocols") == null) paramMap.put("protocols", inputdir + "protocols"); if (getValue(set, "parameters") == null) paramMap.put("parameters", inputdir + "parameters.csv"); if (getValue(set, "worksheet") == null) paramMap.put("worksheet", inputdir + "worksheet.csv"); if (getValue(set, "mcdir") == null) paramMap.put("mcdir", "."); if (getValue(set, "id") == null) paramMap.put("id", id); /* * 'Repair' outputdir. */ if (getValue(set, "outputdir") == null) { paramMap.put("outputdir", inputdir + paramMap.get("id")); } } /* * Define three different sets of parameters */ private static Options defineSets(String[] args) { o = new Options(args, Options.Prefix.DASH); o.addSet(DEF); for (String p : parameters) addParamOptional(DEF, p); o.addSet(EMPTY); return o; } /* * Determine to which of our three parameter sets the given parameters * match. Return a boolean that indicates whether a match has been found. */ private static boolean matchParameters() { boolean match = false; if (o.check(DEF, false, false) || o.check(EMPTY, false, false)) { match = true; fillParamMap(DEF); } return match; } /* * Takes command line arguments as input and returns a map with the * following parameters: inputdir, outputdir, worksheet, workflow, * protocols, parameters, id and mcdir. But, if command line arguments are * not specified properly, then an error message this function produces an * error message and exits with status code 1. */ public static LinkedHashMap<String, String> parseParameters(String[] args, Exiter exiter) { defineSets(args); if (!matchParameters()) { System.err.println("#"); System.err.println("##"); System.err.println("### Begin of error message."); System.err.println("##"); System.err.println("#\n"); // System.err.println(o.getCheckErrors()); System.err.println("Valid command line arguments are:\n"); System.err .println(" -inputdir=<input> # Directory with default inputs: workflow.cvs, protocols, parameters.csv, worksheet.csv."); System.err .println(" -outputdir=<inputdir/id> # Directory where the generated scripts will be stored."); System.err .println(" -workflow=<inputdir/workflow.csv> # A file describing the workflowsteps and their interdependencies."); System.err + .println(" -templates=<inputdir/templates> # A directory containing your *.ftl template files."); + System.err .println(" -protocols=<inputdir/protocols> # A directory containing the *.ftl protocol files."); System.err .println(" -parameters=<inputdir/parameters.csv> # A file that describes the parameters that are used in the protocols."); System.err.println(" -worksheet=<inputdir/worksheet.csv> # A file that describes the work to be doen."); System.err .println(" -id=<output> # An ID that may be different each time you generate."); System.err .println(" -mcdir=<.> # A directory containing molgenis_compute.sh. This may be used by a protocol that executes that script."); System.err .println("\nNo parameters are obligatory. Each parameter has its default value, as specified betweet the brackets < and >.\n"); System.err.println("#"); System.err.println("##"); System.err.println("### End of error message."); System.err.println("##"); System.err.println("#"); System.err.println("\nProgram exits with status code 1."); exiter.exit(); // systemExit(); } else { System.out.println(">> Parsed command line parameters:"); for (String p : paramMap.keySet()) System.out.println(" -" + p + "=" + paramMap.get(p)); System.out.println("\n"); } return (paramMap); } private static void systemExit() { System.exit(1); } }
true
true
public static LinkedHashMap<String, String> parseParameters(String[] args, Exiter exiter) { defineSets(args); if (!matchParameters()) { System.err.println("#"); System.err.println("##"); System.err.println("### Begin of error message."); System.err.println("##"); System.err.println("#\n"); // System.err.println(o.getCheckErrors()); System.err.println("Valid command line arguments are:\n"); System.err .println(" -inputdir=<input> # Directory with default inputs: workflow.cvs, protocols, parameters.csv, worksheet.csv."); System.err .println(" -outputdir=<inputdir/id> # Directory where the generated scripts will be stored."); System.err .println(" -workflow=<inputdir/workflow.csv> # A file describing the workflowsteps and their interdependencies."); System.err .println(" -protocols=<inputdir/protocols> # A directory containing the *.ftl protocol files."); System.err .println(" -parameters=<inputdir/parameters.csv> # A file that describes the parameters that are used in the protocols."); System.err.println(" -worksheet=<inputdir/worksheet.csv> # A file that describes the work to be doen."); System.err .println(" -id=<output> # An ID that may be different each time you generate."); System.err .println(" -mcdir=<.> # A directory containing molgenis_compute.sh. This may be used by a protocol that executes that script."); System.err .println("\nNo parameters are obligatory. Each parameter has its default value, as specified betweet the brackets < and >.\n"); System.err.println("#"); System.err.println("##"); System.err.println("### End of error message."); System.err.println("##"); System.err.println("#"); System.err.println("\nProgram exits with status code 1."); exiter.exit(); // systemExit(); } else { System.out.println(">> Parsed command line parameters:"); for (String p : paramMap.keySet()) System.out.println(" -" + p + "=" + paramMap.get(p)); System.out.println("\n"); } return (paramMap); }
public static LinkedHashMap<String, String> parseParameters(String[] args, Exiter exiter) { defineSets(args); if (!matchParameters()) { System.err.println("#"); System.err.println("##"); System.err.println("### Begin of error message."); System.err.println("##"); System.err.println("#\n"); // System.err.println(o.getCheckErrors()); System.err.println("Valid command line arguments are:\n"); System.err .println(" -inputdir=<input> # Directory with default inputs: workflow.cvs, protocols, parameters.csv, worksheet.csv."); System.err .println(" -outputdir=<inputdir/id> # Directory where the generated scripts will be stored."); System.err .println(" -workflow=<inputdir/workflow.csv> # A file describing the workflowsteps and their interdependencies."); System.err .println(" -templates=<inputdir/templates> # A directory containing your *.ftl template files."); System.err .println(" -protocols=<inputdir/protocols> # A directory containing the *.ftl protocol files."); System.err .println(" -parameters=<inputdir/parameters.csv> # A file that describes the parameters that are used in the protocols."); System.err.println(" -worksheet=<inputdir/worksheet.csv> # A file that describes the work to be doen."); System.err .println(" -id=<output> # An ID that may be different each time you generate."); System.err .println(" -mcdir=<.> # A directory containing molgenis_compute.sh. This may be used by a protocol that executes that script."); System.err .println("\nNo parameters are obligatory. Each parameter has its default value, as specified betweet the brackets < and >.\n"); System.err.println("#"); System.err.println("##"); System.err.println("### End of error message."); System.err.println("##"); System.err.println("#"); System.err.println("\nProgram exits with status code 1."); exiter.exit(); // systemExit(); } else { System.out.println(">> Parsed command line parameters:"); for (String p : paramMap.keySet()) System.out.println(" -" + p + "=" + paramMap.get(p)); System.out.println("\n"); } return (paramMap); }
diff --git a/src/com/codefuss/entities/Ammo.java b/src/com/codefuss/entities/Ammo.java index eb5c217..54c0bcf 100644 --- a/src/com/codefuss/entities/Ammo.java +++ b/src/com/codefuss/entities/Ammo.java @@ -1,44 +1,44 @@ package com.codefuss.entities; import com.codefuss.physics.Body; import org.newdawn.slick.geom.Vector2f; import org.newdawn.slick.util.Log; /** * * @author Martin Vium <[email protected]> */ public class Ammo extends Sprite { private int minDamage = 0; private int maxDamage = 0; public Ammo(Vector2f position, Body body) { super(position, body); } public void setDamageRange(int min, int max) { this.minDamage = min; this.maxDamage = max; } @Override public void collideVertical(Body collided) { super.collideHorizontal(collided); applyCollisionDamage(collided); } @Override public void collideHorizontal(Body collided) { super.collideHorizontal(collided); applyCollisionDamage(collided); } private void applyCollisionDamage(Body collided) { - if(collided.getEntity() instanceof Sprite && removed == false) { + if(collided.getEntity() instanceof Sprite && ! isRemoved()) { remove(); Sprite sprite = (Sprite)collided.getEntity(); sprite.applyHealth(-(int) (minDamage + Math.random() * (maxDamage - minDamage))); } } }
true
true
private void applyCollisionDamage(Body collided) { if(collided.getEntity() instanceof Sprite && removed == false) { remove(); Sprite sprite = (Sprite)collided.getEntity(); sprite.applyHealth(-(int) (minDamage + Math.random() * (maxDamage - minDamage))); } }
private void applyCollisionDamage(Body collided) { if(collided.getEntity() instanceof Sprite && ! isRemoved()) { remove(); Sprite sprite = (Sprite)collided.getEntity(); sprite.applyHealth(-(int) (minDamage + Math.random() * (maxDamage - minDamage))); } }
diff --git a/src/GUI/MainWindow.java b/src/GUI/MainWindow.java index 51d94db..c899c94 100644 --- a/src/GUI/MainWindow.java +++ b/src/GUI/MainWindow.java @@ -1,720 +1,721 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GUI; import business.Output; import java.awt.Color; import java.awt.Event; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileReader; import java.util.Scanner; import javax.swing.JFileChooser; import javax.swing.text.Document; import javax.swing.undo.*; import java.lang.Object; import controller.Controller; import deliver.Deliver; import java.awt.BorderLayout; import java.awt.Image; import java.awt.event.ActionListener; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.text.BadLocationException; import javax.swing.undo.CannotUndoException; /** * * @author Kiwi */ public class MainWindow extends javax.swing.JFrame { //Colores para letras public static final Color Red = new Color(255, 0, 0); public static final Color Black = new Color(0, 0, 0); public static final Color Gray = new Color(109, 109, 109); private Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons2/icon-kiwi.png")); public ArrayList<String> vars; //<editor-fold defaultstate="collapsed" desc=" Undo & Redo part1 "> private Document editorPaneDocument; protected UndoHandler undoHandler = new UndoHandler(); protected UndoManager undoManager = new UndoManager(); private UndoAction undoAction = null; private RedoAction redoAction = null; //</editor-fold> /** * Creates new form NewJFrame */ public MainWindow() { initComponents(); setExtendedState(JFrame.MAXIMIZED_BOTH); setIconImage(icon); vars = new ArrayList<String>(); editorPaneDocument = syntaxArea.getDocument(); editorPaneDocument.addUndoableEditListener(undoHandler); KeyStroke undoKeystroke = KeyStroke.getKeyStroke("control Z"); KeyStroke redoKeystroke = KeyStroke.getKeyStroke("control Y"); undoAction = new UndoAction(); syntaxArea.getInputMap().put(undoKeystroke, "undoKeystroke"); syntaxArea.getActionMap().put("undoKeystroke", undoAction); redoAction = new RedoAction(); syntaxArea.getInputMap().put(redoKeystroke, "redoKeystroke"); syntaxArea.getActionMap().put("redoKeystroke", redoAction); // Edit menu JMenu editMenu = new JMenu("Edit"); JMenuItem undoMenuItem = new JMenuItem(undoAction); JMenuItem redoMenuItem = new JMenuItem(redoAction); editMenu.add(undoMenuItem); editMenu.add(redoMenuItem); Deliver.setDestination(this); } public void setSyntaxText(String text) { //syntaxArea.append(text); insertText(syntaxArea, text); } public void setEventText(String text) { insertText(eventArea, text); } //<editor-fold defaultstate="collapsed" desc=" Undo & Redo part2"> class UndoHandler implements UndoableEditListener { /** * Messaged when the Document has created an edit, the edit is added to * <code>undoManager</code>, an instance of UndoManager. */ @Override public void undoableEditHappened(UndoableEditEvent e) { undoManager.addEdit(e.getEdit()); undoAction.update(); redoAction.update(); } } class UndoAction extends AbstractAction { public UndoAction() { super("Undo"); setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undoManager.undo(); } catch (CannotUndoException ex) { // TODO deal with this //ex.printStackTrace(); } update(); redoAction.update(); } protected void update() { if (undoManager.canUndo()) { setEnabled(true); putValue(Action.NAME, undoManager.getUndoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Undo"); } } } class RedoAction extends AbstractAction { public RedoAction() { super("Redo"); setEnabled(false); } public void actionPerformed(ActionEvent e) { try { undoManager.redo(); } catch (CannotRedoException ex) { // TODO deal with this ex.printStackTrace(); } update(); undoAction.update(); } protected void update() { if (undoManager.canRedo()) { setEnabled(true); putValue(Action.NAME, undoManager.getRedoPresentationName()); } else { setEnabled(false); putValue(Action.NAME, "Redo"); } } } //</editor-fold> /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); syntaxArea = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); eventArea = new javax.swing.JTextArea(); LoadEvent = new javax.swing.JButton(); LoadSyntax = new javax.swing.JButton(); SaveSyntax = new javax.swing.JButton(); NVariable = new javax.swing.JButton(); NOperation = new javax.swing.JButton(); NDataBase = new javax.swing.JButton(); NTable = new javax.swing.JButton(); deshacer = new javax.swing.JButton(); editar = new javax.swing.JToggleButton(); rehacer = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); FailureManager = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206)); jFrame1.setLocationByPlatform(true); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>"); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KiwiSyntaxManager"); setFocusCycleRoot(false); setLocationByPlatform(true); jSplitPane1.setResizeWeight(0.5); jScrollPane2.setToolTipText(""); syntaxArea.setColumns(20); syntaxArea.setRows(5); jScrollPane2.setViewportView(syntaxArea); jSplitPane1.setRightComponent(jScrollPane2); eventArea.setColumns(20); eventArea.setRows(5); jScrollPane1.setViewportView(eventArea); jSplitPane1.setLeftComponent(jScrollPane1); LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N LoadEvent.setToolTipText("Load Event"); LoadEvent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadEventActionPerformed(evt); } }); LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N LoadSyntax.setToolTipText("Load Syntax"); LoadSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadSyntaxActionPerformed(evt); } }); SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N SaveSyntax.setToolTipText("Save"); SaveSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveSyntaxActionPerformed(evt); } }); NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N NVariable.setToolTipText("New Variable"); NVariable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NVariableActionPerformed(evt); } }); NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N NOperation.setToolTipText("New Operation"); NOperation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NOperationActionPerformed(evt); } }); NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N NDataBase.setToolTipText("New DataBase"); NDataBase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NDataBaseActionPerformed(evt); } }); NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N NTable.setToolTipText("New Table"); NTable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NTableActionPerformed(evt); } }); deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N deshacer.setToolTipText("Undo"); deshacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { undoActionPerformed(evt); } }); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N editar.setToolTipText("Edit Code"); editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editarActionPerformed(evt); } }); rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N rehacer.setToolTipText("Redo"); rehacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { redoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); FailureManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N FailureManager.setToolTipText("Failure manager"); FailureManager.setEnabled(false); FailureManager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FailureManagerActionPerformed(evt); } }); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/Alcatel-LucentMini.png"))); // NOI18N + jLabel2.setIconTextGap(0); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FailureManager, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2)) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(LoadEvent, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SaveSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NVariable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NOperation, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NDataBase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(deshacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(rehacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(LoadSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FailureManager, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(1, 1, 1) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); deshacer.getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents private void LoadEventActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadEventActionPerformed // TODO add your handling code here: JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt format", "txt"); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); int seleccion = fileChooser.showOpenDialog(this); if (seleccion == JFileChooser.APPROVE_OPTION) { String storeAllString = ""; File fichero = fileChooser.getSelectedFile(); // Aquí debemos abrir y leer el fichero. Object[] what; what = new Object[1]; what[0] = fichero.toString(); try { Controller.controller(Controller.readInput, what); } catch (Exception e) { } eventArea.setCaretPosition(0); } }//GEN-LAST:event_LoadEventActionPerformed private void LoadSyntaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadSyntaxActionPerformed // TODO add your handling code here: JFileChooser fileChooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt and .stx format", "txt", "stx"); fileChooser.setAcceptAllFileFilterUsed(false); fileChooser.setFileFilter(filter); int seleccion = fileChooser.showOpenDialog(this); fileChooser.setMultiSelectionEnabled(false); if (seleccion == JFileChooser.APPROVE_OPTION) { String storeAllString = ""; File fichero = fileChooser.getSelectedFile(); // Aquí debemos abrir y leer el fichero. try { FileReader readTextFile = new FileReader(fichero.toString()); Scanner fileReaderScan = new Scanner(readTextFile); while (fileReaderScan.hasNextLine()) { String temp = fileReaderScan.nextLine() + "\n"; storeAllString = storeAllString + temp; } } catch (Exception e) { } syntaxArea.setText(storeAllString); syntaxArea.setCaretPosition(0); } }//GEN-LAST:event_LoadSyntaxActionPerformed private void NVariableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NVariableActionPerformed // TODO add your handling code here: JDialog jd = new NewVariable(this); jd.setLocationByPlatform(true); jd.setModal(true); jd.setLocationRelativeTo(this); jd.setVisible(true); }//GEN-LAST:event_NVariableActionPerformed private void undoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoActionPerformed try { undoManager.undo(); } catch (CannotUndoException cre) { JOptionPane op = new JOptionPane(); op.showMessageDialog(this, "Can't undo more", "ERROR MESSAGE", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_undoActionPerformed private void editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarActionPerformed // TODO add your handling code here: if (syntaxArea.isEditable()) { syntaxArea.setEditable(false); syntaxArea.setForeground(Gray); } else { syntaxArea.setEditable(true); syntaxArea.setForeground(Black); } }//GEN-LAST:event_editarActionPerformed private void redoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_redoActionPerformed try { undoManager.redo(); } catch (CannotRedoException cre) { JOptionPane op = new JOptionPane(); op.showMessageDialog(this, "Can't redo more", "ERROR MESSAGE", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_redoActionPerformed private void NOperationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NOperationActionPerformed JDialog no = new NewOperations(this); no.setVisible(true); }//GEN-LAST:event_NOperationActionPerformed private void SaveSyntaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveSyntaxActionPerformed JFileChooser jfc = new JFileChooser(); jfc.setMultiSelectionEnabled(false); jfc.setVisible(true); if(JFileChooser.APPROVE_OPTION == jfc.showSaveDialog(this)){ Object[] what = new Object[2]; what[0] = syntaxArea.getText(); what[1] = jfc.getSelectedFile(); Controller.controller(Controller.writeOutput, what); } /* f = new JFrame("Write a file name"); f.setLayout(new BorderLayout()); f.setVisible(true); this.tf = new JTextField("syntax"); JButton confirmButton = new JButton("Ok"); JButton defaultButton = new JButton("Default: syntax"); JButton cancelButton = new JButton("Cancel"); f.add(tf, BorderLayout.NORTH); f.add(confirmButton, BorderLayout.WEST); f.add(defaultButton, BorderLayout.CENTER); f.add(cancelButton, BorderLayout.SOUTH); f.pack(); f.setLocation(this.getLocation().x + this.getWidth()/2 - f.getWidth()/2, this.getLocation().y + this.getHeight()/2 - f.getHeight()/2); confirmButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { business.Output.publishOutput(syntaxArea.getText(), tf.getText()); f.dispose(); } }); defaultButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { business.Output.publishOutput(syntaxArea.getText(), ""); f.dispose(); } }); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { f.dispose(); } }); */ }//GEN-LAST:event_SaveSyntaxActionPerformed private void NTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NTableActionPerformed JDialog jd = new NewTable(); jd.setLocationByPlatform(true); jd.setLocationRelativeTo(this); jd.setModal(true); jd.setVisible(true); }//GEN-LAST:event_NTableActionPerformed private void NDataBaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NDataBaseActionPerformed JDialog jd = new NewBBDD(this, true); jd.setLocationByPlatform(true); jd.setLocationRelativeTo(this); jd.setVisible(true); }//GEN-LAST:event_NDataBaseActionPerformed private void FailureManagerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FailureManagerActionPerformed JDialog jd = new FailureManager(this.vars); jd.setLocationByPlatform(true); jd.setLocationRelativeTo(this); jd.setVisible(true); }//GEN-LAST:event_FailureManagerActionPerformed private JTextField oldColName; private JTextField newColName; private JTextField tf; private JFrame f; //<editor-fold defaultstate="collapsed" desc=" Make's Room "> private String preMakeRoom(javax.swing.JTextArea Area) { String bs = ""; int act = Area.getCaretPosition(); try { String sig = Area.getText(act - 1, 1); if (!sig.equalsIgnoreCase("\n")) { //Area.insert("\n", Area.getCaretPosition()); bs = "\n"; } } catch (BadLocationException ex) { } return bs; } private String postMakeRoom(javax.swing.JTextArea Area) { String bs = ""; int act = Area.getCaretPosition(); Area.setCaretPosition(Area.getDocument().getLength()); int fin = Area.getCaretPosition(); Area.setCaretPosition(act); try { String sig = Area.getText(act, 1); if (act != fin && sig.equalsIgnoreCase("\n")) { Area.setCaretPosition(Area.getCaretPosition() + 1); } else { //Area.insert("\n", Area.getCaretPosition()); bs = "\n"; } } catch (BadLocationException ex) { //Area.insert("\n", Area.getCaretPosition()); bs = "\n"; } return bs; } /** * Inserta el parametro String en el parametor JTextArea haciendo un "hueco" * en el texto, si fuera necesario * * @param Area JTextArea * @param str String */ private void insertText(javax.swing.JTextArea Area, String str) { Area.insert(preMakeRoom(Area) + str + postMakeRoom(Area), Area.getCaretPosition()); } //</editor-fold> public void addVars(String vars) { this.vars.add(vars); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainWindow().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton FailureManager; private javax.swing.JButton LoadEvent; private javax.swing.JButton LoadSyntax; private javax.swing.JButton NDataBase; private javax.swing.JButton NOperation; private javax.swing.JButton NTable; private javax.swing.JButton NVariable; private javax.swing.JButton SaveSyntax; private javax.swing.JButton deshacer; private javax.swing.JToggleButton editar; private javax.swing.JTextArea eventArea; private javax.swing.JFileChooser jFileChooser1; private javax.swing.JFrame jFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JButton rehacer; private javax.swing.JTextArea syntaxArea; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); syntaxArea = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); eventArea = new javax.swing.JTextArea(); LoadEvent = new javax.swing.JButton(); LoadSyntax = new javax.swing.JButton(); SaveSyntax = new javax.swing.JButton(); NVariable = new javax.swing.JButton(); NOperation = new javax.swing.JButton(); NDataBase = new javax.swing.JButton(); NTable = new javax.swing.JButton(); deshacer = new javax.swing.JButton(); editar = new javax.swing.JToggleButton(); rehacer = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); FailureManager = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206)); jFrame1.setLocationByPlatform(true); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>"); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KiwiSyntaxManager"); setFocusCycleRoot(false); setLocationByPlatform(true); jSplitPane1.setResizeWeight(0.5); jScrollPane2.setToolTipText(""); syntaxArea.setColumns(20); syntaxArea.setRows(5); jScrollPane2.setViewportView(syntaxArea); jSplitPane1.setRightComponent(jScrollPane2); eventArea.setColumns(20); eventArea.setRows(5); jScrollPane1.setViewportView(eventArea); jSplitPane1.setLeftComponent(jScrollPane1); LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N LoadEvent.setToolTipText("Load Event"); LoadEvent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadEventActionPerformed(evt); } }); LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N LoadSyntax.setToolTipText("Load Syntax"); LoadSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadSyntaxActionPerformed(evt); } }); SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N SaveSyntax.setToolTipText("Save"); SaveSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveSyntaxActionPerformed(evt); } }); NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N NVariable.setToolTipText("New Variable"); NVariable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NVariableActionPerformed(evt); } }); NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N NOperation.setToolTipText("New Operation"); NOperation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NOperationActionPerformed(evt); } }); NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N NDataBase.setToolTipText("New DataBase"); NDataBase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NDataBaseActionPerformed(evt); } }); NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N NTable.setToolTipText("New Table"); NTable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NTableActionPerformed(evt); } }); deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N deshacer.setToolTipText("Undo"); deshacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { undoActionPerformed(evt); } }); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N editar.setToolTipText("Edit Code"); editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editarActionPerformed(evt); } }); rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N rehacer.setToolTipText("Redo"); rehacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { redoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); FailureManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N FailureManager.setToolTipText("Failure manager"); FailureManager.setEnabled(false); FailureManager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FailureManagerActionPerformed(evt); } }); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/Alcatel-LucentMini.png"))); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FailureManager, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2)) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(LoadEvent, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SaveSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NVariable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NOperation, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NDataBase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(deshacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(rehacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(LoadSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FailureManager, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(1, 1, 1) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); deshacer.getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jFileChooser1 = new javax.swing.JFileChooser(); jFrame1 = new javax.swing.JFrame(); jLabel1 = new javax.swing.JLabel(); jSplitPane1 = new javax.swing.JSplitPane(); jScrollPane2 = new javax.swing.JScrollPane(); syntaxArea = new javax.swing.JTextArea(); jScrollPane1 = new javax.swing.JScrollPane(); eventArea = new javax.swing.JTextArea(); LoadEvent = new javax.swing.JButton(); LoadSyntax = new javax.swing.JButton(); SaveSyntax = new javax.swing.JButton(); NVariable = new javax.swing.JButton(); NOperation = new javax.swing.JButton(); NDataBase = new javax.swing.JButton(); NTable = new javax.swing.JButton(); deshacer = new javax.swing.JButton(); editar = new javax.swing.JToggleButton(); rehacer = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); FailureManager = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206)); jFrame1.setLocationByPlatform(true); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>"); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 15, Short.MAX_VALUE)) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jFrame1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(38, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("KiwiSyntaxManager"); setFocusCycleRoot(false); setLocationByPlatform(true); jSplitPane1.setResizeWeight(0.5); jScrollPane2.setToolTipText(""); syntaxArea.setColumns(20); syntaxArea.setRows(5); jScrollPane2.setViewportView(syntaxArea); jSplitPane1.setRightComponent(jScrollPane2); eventArea.setColumns(20); eventArea.setRows(5); jScrollPane1.setViewportView(eventArea); jSplitPane1.setLeftComponent(jScrollPane1); LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N LoadEvent.setToolTipText("Load Event"); LoadEvent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadEventActionPerformed(evt); } }); LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N LoadSyntax.setToolTipText("Load Syntax"); LoadSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LoadSyntaxActionPerformed(evt); } }); SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N SaveSyntax.setToolTipText("Save"); SaveSyntax.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { SaveSyntaxActionPerformed(evt); } }); NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N NVariable.setToolTipText("New Variable"); NVariable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NVariableActionPerformed(evt); } }); NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N NOperation.setToolTipText("New Operation"); NOperation.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NOperationActionPerformed(evt); } }); NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N NDataBase.setToolTipText("New DataBase"); NDataBase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NDataBaseActionPerformed(evt); } }); NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N NTable.setToolTipText("New Table"); NTable.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { NTableActionPerformed(evt); } }); deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N deshacer.setToolTipText("Undo"); deshacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { undoActionPerformed(evt); } }); editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N editar.setToolTipText("Edit Code"); editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N editar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editarActionPerformed(evt); } }); rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N rehacer.setToolTipText("Redo"); rehacer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { redoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 20, Short.MAX_VALUE) ); FailureManager.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N FailureManager.setToolTipText("Failure manager"); FailureManager.setEnabled(false); FailureManager.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { FailureManagerActionPerformed(evt); } }); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/Alcatel-LucentMini.png"))); // NOI18N jLabel2.setIconTextGap(0); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(FailureManager, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2)) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(LoadEvent, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(SaveSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NVariable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NOperation, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NDataBase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NTable, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(deshacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(rehacer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(LoadSyntax, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(FailureManager, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(1, 1, 1) .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); deshacer.getAccessibleContext().setAccessibleDescription(""); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/main/org/testng/xml/XmlTest.java b/src/main/org/testng/xml/XmlTest.java index 53e1d516..b2c6b983 100644 --- a/src/main/org/testng/xml/XmlTest.java +++ b/src/main/org/testng/xml/XmlTest.java @@ -1,472 +1,473 @@ package org.testng.xml; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.testng.TestNG; import org.testng.internal.AnnotationTypeEnum; import org.testng.reporters.XMLStringBuffer; /** * This class describes the tag &lt;test&gt; in testng.xml. * * @author <a href = "mailto:cedric&#64;beust.com">Cedric Beust</a> * @author <a href = 'mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class XmlTest implements Serializable, Cloneable { private final XmlSuite m_suite; private String m_name = TestNG.DEFAULT_COMMAND_LINE_SUITE_NAME; private Integer m_verbose; private Boolean m_isJUnit; private List<XmlClass> m_xmlClasses = new ArrayList<XmlClass>(); private List<String> m_includedGroups = new ArrayList<String>(); private List<String> m_excludedGroups = new ArrayList<String>(); private final Map<String, List<String>> m_metaGroups = new HashMap<String, List<String>>(); private Map<String, String> m_parameters = new HashMap<String, String>(); private String m_parallel; /** */ private AnnotationTypeEnum m_annotations; // BeanShell expression private String m_expression; private List<XmlMethodSelector> m_methodSelectors = new ArrayList<XmlMethodSelector>(); // test level packages private List<XmlPackage> m_xmlPackages = new ArrayList<XmlPackage>(); private String m_timeOut; /** * Constructs a <code>XmlTest</code> and adds it to suite's list of tests. * * @param suite the parent suite. */ public XmlTest(XmlSuite suite) { m_suite = suite; m_suite.getTests().add(this); } public void setXmlPackages(List<XmlPackage> packages) { m_xmlPackages = packages; } public List<XmlPackage> getXmlPackages() { return m_xmlPackages; } public List<XmlMethodSelector> getMethodSelectors() { return m_methodSelectors; } public void setMethodSelectors(List<XmlMethodSelector> methodSelectors) { m_methodSelectors = methodSelectors; } /** * Returns the suite this test is part of. * @return the suite this test is part of. */ public XmlSuite getSuite() { return m_suite; } /** * @return Returns the includedGroups. */ public List<String> getIncludedGroups() { return m_includedGroups; } /** * Sets the XML Classes. * @param classes The classes to set. * @deprecated use setXmlClasses */ public void setClassNames(List<XmlClass> classes) { m_xmlClasses = classes; } /** * @return Returns the classes. */ public List<XmlClass> getXmlClasses() { return m_xmlClasses; } /** * Sets the XML Classes. * @param classes The classes to set. */ public void setXmlClasses(List<XmlClass> classes) { m_xmlClasses = classes; } /** * @return Returns the name. */ public String getName() { return m_name; } /** * @param name The name to set. */ public void setName(String name) { m_name = name; } /** * @param i */ public void setVerbose(int v) { m_verbose = new Integer(v); } /** * @param currentIncludedGroups */ public void setIncludedGroups(List<String> g) { m_includedGroups = g; } /** * @param excludedGrousps The excludedGrousps to set. */ public void setExcludedGroups(List<String> g) { m_excludedGroups = g; } /** * @return Returns the excludedGroups. */ public List<String> getExcludedGroups() { return m_excludedGroups; } /** * @return Returns the verbose. */ public int getVerbose() { Integer result = m_verbose; if (null == result) { result = m_suite.getVerbose(); } return result.intValue(); } /** * @return Returns the isJUnit. */ public boolean isJUnit() { Boolean result = m_isJUnit; if (null == result) { result = m_suite.isJUnit(); } return result; } /** * @param isJUnit The isJUnit to set. */ public void setJUnit(boolean isJUnit) { m_isJUnit = isJUnit; } public void addMetaGroup(String name, List<String> metaGroup) { m_metaGroups.put(name, metaGroup); } /** * @return Returns the metaGroups. */ public Map<String, List<String>> getMetaGroups() { return m_metaGroups; } /** * @param currentTestParameters */ public void setParameters(Map parameters) { m_parameters = parameters; } public void addParameter(String key, String value) { m_parameters.put(key, value); } public String getParameter(String name) { String result = m_parameters.get(name); if (null == result) { result = m_suite.getParameter(name); } return result; } /** * Returns a merge of the the test parameters and its parent suite parameters. Test parameters * have precedence over suite parameters. * * @return a merge of the the test parameters and its parent suite parameters. */ public Map<String, String> getParameters() { Map<String, String> result = new HashMap<String, String>(); for (String key : getSuite().getParameters().keySet()) { result.put(key, getSuite().getParameters().get(key)); } for (String key : m_parameters.keySet()) { result.put(key, m_parameters.get(key)); } return result; } public void setParallel(String parallel) { m_parallel = parallel; } public String getParallel() { String result = null; if (null != m_parallel) { result = m_parallel; } else { result = m_suite.getParallel(); } return result; } public String getTimeOut() { String result = null; if (null != m_timeOut) { result = m_timeOut; } else { result = m_suite.getTimeOut(); } return result; } public long getTimeOut(long def) { long result = def; if (getTimeOut() != null) { result = new Long(getTimeOut()).longValue(); } return result; } public String getAnnotations() { return null != m_annotations ? m_annotations.toString() : m_suite.getAnnotations(); } public void setAnnotations(String annotations) { m_annotations = AnnotationTypeEnum.valueOf(annotations); } public void setBeanShellExpression(String expression) { m_expression = expression; } public String getExpression() { return m_expression; } public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { - for (String paramName: m_parameters.keySet()) { - Properties paramProps = new Properties(); - paramProps.setProperty("name", paramName); - paramProps.setProperty("value", m_parameters.get(paramName)); + for(Map.Entry<String, String> para: m_parameters.entrySet()) { + Properties paramProps= new Properties(); + paramProps.setProperty("name", para.getKey()); + paramProps.setProperty("value", para.getValue()); + xsb.addEmptyElement("property", paramProps); // BUGFIX: TESTNG-27 } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); } @Override public String toString() { StringBuffer result = new StringBuffer("[Test: \"" + m_name + "\"") .append(" verbose:" + m_verbose); result.append("[parameters:"); for (String k : m_parameters.keySet()) { String v = m_parameters.get(k); result.append(k + "=>" + v); } result.append("]"); result.append("[metagroups:"); for (String g : m_metaGroups.keySet()) { List<String> mg = m_metaGroups.get(g); result.append(g).append("="); for (String n : mg) { result.append(n).append(","); } } result.append("] "); result.append("[included: "); for (String g : m_includedGroups) { result.append(g).append(" "); } result.append("]"); result.append("[excluded: "); for (String g : m_excludedGroups) { result.append(g).append(""); } result.append("] "); result.append(" classes:"); for (XmlClass cl : m_xmlClasses) { result.append(cl).append(" "); } result.append("] "); return result.toString(); } static void ppp(String s) { System.out.println("[XmlTest] " + s); } /** * Clone the <TT>source</TT> <CODE>XmlTest</CODE> by including: * - test attributes * - groups definitions * - parameters * * The &lt;classes&gt; sub element is ignored for the moment. * * @param suite * @param source * @return */ @Override public Object clone() { XmlTest result = new XmlTest(getSuite()); result.setName(getName()); result.setAnnotations(getAnnotations()); result.setIncludedGroups(getIncludedGroups()); result.setExcludedGroups(getExcludedGroups()); result.setJUnit(isJUnit()); result.setParallel(getParallel()); result.setVerbose(getVerbose()); result.setParameters(getParameters()); result.setXmlPackages(getXmlPackages()); Map<String, List<String>> metagroups = getMetaGroups(); for (String groupName: metagroups.keySet()) { result.addMetaGroup(groupName, metagroups.get(groupName)); } return result; } }
true
true
public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { for (String paramName: m_parameters.keySet()) { Properties paramProps = new Properties(); paramProps.setProperty("name", paramName); paramProps.setProperty("value", m_parameters.get(paramName)); } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); }
public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { for(Map.Entry<String, String> para: m_parameters.entrySet()) { Properties paramProps= new Properties(); paramProps.setProperty("name", para.getKey()); paramProps.setProperty("value", para.getValue()); xsb.addEmptyElement("property", paramProps); // BUGFIX: TESTNG-27 } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); }
diff --git a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/search/mixin/MixinTestsSuite.java b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/search/mixin/MixinTestsSuite.java index 6e5965db..0c0c8d55 100644 --- a/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/search/mixin/MixinTestsSuite.java +++ b/tests/org.eclipse.dltk.ruby.core.tests/src/org/eclipse/dltk/ruby/tests/search/mixin/MixinTestsSuite.java @@ -1,155 +1,156 @@ /******************************************************************************* * Copyright (c) 2005, 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 * *******************************************************************************/ package org.eclipse.dltk.ruby.tests.search.mixin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.StringTokenizer; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.core.runtime.Assert; import org.eclipse.dltk.core.mixin.IMixinElement; import org.eclipse.dltk.core.mixin.MixinModel; import org.eclipse.dltk.ruby.core.RubyLanguageToolkit; import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinElementInfo; import org.eclipse.dltk.ruby.tests.Activator; public class MixinTestsSuite extends TestSuite { private final MixinModel model; public MixinTestsSuite(String testsDirectory) { super(testsDirectory); model = new MixinModel(RubyLanguageToolkit.getDefault()); final MixinTest tests = new MixinTest("Ruby Mixin Tests"); try { tests.setUpSuite(); } catch (Exception e1) { e1.printStackTrace(); } Enumeration entryPaths = Activator.getDefault().getBundle() .getEntryPaths(testsDirectory); while (entryPaths.hasMoreElements()) { final String path = (String) entryPaths.nextElement(); URL entry = Activator.getDefault().getBundle().getEntry(path); try { entry.openStream().close(); } catch (Exception e) { continue; } int pos = path.lastIndexOf('/'); final String name = (pos >= 0 ? path.substring(pos + 1) : path); String x = path.substring(0, pos); pos = x.lastIndexOf('/'); final String folder = (pos >= 0 ? x.substring(pos + 1) : x); addTest(new TestCase(name) { private Collection assertions = new ArrayList(); public void setUp() { } class GetElementAssertion implements IAssertion { private final String key; private MixinModel model; public GetElementAssertion(String key, MixinModel model) { this.key = key; this.model = model; } public void check() throws Exception { model = new MixinModel(RubyLanguageToolkit.getDefault()); IMixinElement mixinElement = model.get(key); if (mixinElement == null) { throw new AssertionFailedError("Key " + key + " not found"); } Object[] allObjects = mixinElement.getAllObjects(); if (allObjects == null && allObjects.length > 0) throw new AssertionFailedError("Key " + key + " has null or empty object set"); for (int i = 0; i < allObjects.length; i++) { if (allObjects[i] == null) throw new AssertionFailedError("Key " + key + " has null object at index " + i); RubyMixinElementInfo info = (RubyMixinElementInfo) allObjects[i]; if (info.getObject() == null) throw new AssertionFailedError("Key " + key + " has info with a null object at index " + i + " (kind=" + info.getKind() + ")"); } } } protected void runTest() throws Throwable { String content = loadContent(path); String[] lines = content.split("\n"); int lineOffset = 0; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim(); int pos = line.indexOf("##"); if (pos >= 0) { StringTokenizer tok = new StringTokenizer(line .substring(pos + 2)); String test = tok.nextToken(); if ("get".equals(test)) { String key = tok.nextToken(); assertions.add(new GetElementAssertion(key, MixinTestsSuite.this.model)); } else { - Assert.isLegal(false); +// continue; +// Assert.isLegal(false); } } lineOffset += lines[i].length() + 1; } Assert.isLegal(assertions.size() > 0); tests.executeTest(assertions); // try { // } finally { // //tests.tearDownSuite(); // } } }); } } private String loadContent(String path) throws IOException { StringBuffer buffer = new StringBuffer(); InputStream input = null; try { input = Activator.getDefault().openResource(path); InputStreamReader reader = new InputStreamReader(input); BufferedReader br = new BufferedReader(reader); char[] data = new char[10 * 1024 * 1024]; int size = br.read(data); buffer.append(data, 0, size); } finally { if (input != null) { input.close(); } } String content = buffer.toString(); return content; } }
true
true
public MixinTestsSuite(String testsDirectory) { super(testsDirectory); model = new MixinModel(RubyLanguageToolkit.getDefault()); final MixinTest tests = new MixinTest("Ruby Mixin Tests"); try { tests.setUpSuite(); } catch (Exception e1) { e1.printStackTrace(); } Enumeration entryPaths = Activator.getDefault().getBundle() .getEntryPaths(testsDirectory); while (entryPaths.hasMoreElements()) { final String path = (String) entryPaths.nextElement(); URL entry = Activator.getDefault().getBundle().getEntry(path); try { entry.openStream().close(); } catch (Exception e) { continue; } int pos = path.lastIndexOf('/'); final String name = (pos >= 0 ? path.substring(pos + 1) : path); String x = path.substring(0, pos); pos = x.lastIndexOf('/'); final String folder = (pos >= 0 ? x.substring(pos + 1) : x); addTest(new TestCase(name) { private Collection assertions = new ArrayList(); public void setUp() { } class GetElementAssertion implements IAssertion { private final String key; private MixinModel model; public GetElementAssertion(String key, MixinModel model) { this.key = key; this.model = model; } public void check() throws Exception { model = new MixinModel(RubyLanguageToolkit.getDefault()); IMixinElement mixinElement = model.get(key); if (mixinElement == null) { throw new AssertionFailedError("Key " + key + " not found"); } Object[] allObjects = mixinElement.getAllObjects(); if (allObjects == null && allObjects.length > 0) throw new AssertionFailedError("Key " + key + " has null or empty object set"); for (int i = 0; i < allObjects.length; i++) { if (allObjects[i] == null) throw new AssertionFailedError("Key " + key + " has null object at index " + i); RubyMixinElementInfo info = (RubyMixinElementInfo) allObjects[i]; if (info.getObject() == null) throw new AssertionFailedError("Key " + key + " has info with a null object at index " + i + " (kind=" + info.getKind() + ")"); } } } protected void runTest() throws Throwable { String content = loadContent(path); String[] lines = content.split("\n"); int lineOffset = 0; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim(); int pos = line.indexOf("##"); if (pos >= 0) { StringTokenizer tok = new StringTokenizer(line .substring(pos + 2)); String test = tok.nextToken(); if ("get".equals(test)) { String key = tok.nextToken(); assertions.add(new GetElementAssertion(key, MixinTestsSuite.this.model)); } else { Assert.isLegal(false); } } lineOffset += lines[i].length() + 1; } Assert.isLegal(assertions.size() > 0); tests.executeTest(assertions); // try { // } finally { // //tests.tearDownSuite(); // } } }); } }
public MixinTestsSuite(String testsDirectory) { super(testsDirectory); model = new MixinModel(RubyLanguageToolkit.getDefault()); final MixinTest tests = new MixinTest("Ruby Mixin Tests"); try { tests.setUpSuite(); } catch (Exception e1) { e1.printStackTrace(); } Enumeration entryPaths = Activator.getDefault().getBundle() .getEntryPaths(testsDirectory); while (entryPaths.hasMoreElements()) { final String path = (String) entryPaths.nextElement(); URL entry = Activator.getDefault().getBundle().getEntry(path); try { entry.openStream().close(); } catch (Exception e) { continue; } int pos = path.lastIndexOf('/'); final String name = (pos >= 0 ? path.substring(pos + 1) : path); String x = path.substring(0, pos); pos = x.lastIndexOf('/'); final String folder = (pos >= 0 ? x.substring(pos + 1) : x); addTest(new TestCase(name) { private Collection assertions = new ArrayList(); public void setUp() { } class GetElementAssertion implements IAssertion { private final String key; private MixinModel model; public GetElementAssertion(String key, MixinModel model) { this.key = key; this.model = model; } public void check() throws Exception { model = new MixinModel(RubyLanguageToolkit.getDefault()); IMixinElement mixinElement = model.get(key); if (mixinElement == null) { throw new AssertionFailedError("Key " + key + " not found"); } Object[] allObjects = mixinElement.getAllObjects(); if (allObjects == null && allObjects.length > 0) throw new AssertionFailedError("Key " + key + " has null or empty object set"); for (int i = 0; i < allObjects.length; i++) { if (allObjects[i] == null) throw new AssertionFailedError("Key " + key + " has null object at index " + i); RubyMixinElementInfo info = (RubyMixinElementInfo) allObjects[i]; if (info.getObject() == null) throw new AssertionFailedError("Key " + key + " has info with a null object at index " + i + " (kind=" + info.getKind() + ")"); } } } protected void runTest() throws Throwable { String content = loadContent(path); String[] lines = content.split("\n"); int lineOffset = 0; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim(); int pos = line.indexOf("##"); if (pos >= 0) { StringTokenizer tok = new StringTokenizer(line .substring(pos + 2)); String test = tok.nextToken(); if ("get".equals(test)) { String key = tok.nextToken(); assertions.add(new GetElementAssertion(key, MixinTestsSuite.this.model)); } else { // continue; // Assert.isLegal(false); } } lineOffset += lines[i].length() + 1; } Assert.isLegal(assertions.size() > 0); tests.executeTest(assertions); // try { // } finally { // //tests.tearDownSuite(); // } } }); } }
diff --git a/juddiv3-war/src/main/java/org/apache/juddi/webconsole/hub/UddiAdminHub.java b/juddiv3-war/src/main/java/org/apache/juddi/webconsole/hub/UddiAdminHub.java index 9c2ef1ecf..bf1f941b5 100644 --- a/juddiv3-war/src/main/java/org/apache/juddi/webconsole/hub/UddiAdminHub.java +++ b/juddiv3-war/src/main/java/org/apache/juddi/webconsole/hub/UddiAdminHub.java @@ -1,697 +1,696 @@ package org.apache.juddi.webconsole.hub; /* * Copyright 2001-2013 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.URL; import java.rmi.RemoteException; import java.util.Map; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.xml.bind.JAXB; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.ws.BindingProvider; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.api_v3.ClientSubscriptionInfoDetail; import org.apache.juddi.api_v3.DeleteClientSubscriptionInfo; import org.apache.juddi.api_v3.DeletePublisher; import org.apache.juddi.api_v3.GetAllPublisherDetail; import org.apache.juddi.api_v3.GetPublisherDetail; import org.apache.juddi.api_v3.Publisher; import org.apache.juddi.api_v3.PublisherDetail; import org.apache.juddi.api_v3.SaveClientSubscriptionInfo; import org.apache.juddi.api_v3.SavePublisher; import org.apache.juddi.api_v3.SyncSubscription; import org.apache.juddi.api_v3.SyncSubscriptionDetail; import org.apache.juddi.v3.client.ClassUtil; import org.apache.juddi.v3.client.config.ClientConfig; import org.apache.juddi.v3.client.config.UDDIClient; import org.apache.juddi.v3.client.config.UDDIClientContainer; import org.apache.juddi.v3.client.config.UDDINode; import org.apache.juddi.v3.client.transport.Transport; import org.apache.juddi.v3_service.JUDDIApiPortType; import org.apache.juddi.webconsole.AES; import org.apache.juddi.webconsole.resources.ResourceLoader; import org.uddi.api_v3.AuthToken; import org.uddi.api_v3.DeleteTModel; import org.uddi.api_v3.DiscardAuthToken; import org.uddi.api_v3.DispositionReport; import org.uddi.api_v3.GetAuthToken; import org.uddi.v3_service.DispositionReportFaultMessage; import org.uddi.v3_service.UDDISecurityPortType; /** * UddiHub - The hub acts as a single point for managing browser to uddi * services. At most 1 instance is allowed per http session. In general, all * methods in the class trigger web service call outs. All callouts also support * expired UDDI tokens and will attempt to reauthenticate and retry the request. * * @author <a href="mailto:[email protected]">Alex O'Ree</a> */ public class UddiAdminHub { /** * The logger name */ public static final String LOGGER_NAME = "org.apache.juddi"; transient AuthStyle style = null; Properties properties = null; /** * The Log4j logger. This is also referenced from the Builders class, thus * it is public */ public static final Log log = LogFactory.getLog(LOGGER_NAME); private UddiAdminHub() throws DatatypeConfigurationException { // df = DatatypeFactory.newInstance(); } /** * removes the Hub from the current http session * * @param _session */ public static void reset(HttpSession _session) { _session.removeAttribute("hub"); // token = null; } /** * This kills any authentication tokens, logs the user out and nulls out all * services */ public void die() { DiscardAuthToken da = new DiscardAuthToken(); da.setAuthInfo(token); try { security.discardAuthToken(da); } catch (Exception ex) { HandleException(ex); } token = null; security = null; juddi = null; } /** * the name of the 'node' property in the config */ public static final String PROP_CONFIG_NODE = "config.props.node"; /** * */ public static final String PROP_AUTH_TYPE = "config.props.authtype"; /** * */ public static final String PROP_AUTO_LOGOUT = "config.props.automaticLogouts.enable"; /** * */ public static final String PROP_AUTO_LOGOUT_TIMER = "config.props.automaticLogouts.duration"; /** * */ public static final String PROP_PREFIX = "config.props."; /** * * */ public static final String PROP_ADMIN_LOCALHOST_ONLY = "config.props.configLocalHostOnly"; private transient UDDISecurityPortType security = null; private transient JUDDIApiPortType juddi = null; private transient String token = null; private transient HttpSession session; private transient Transport transport = null; private transient ClientConfig clientConfig; private static final long serialVersionUID = 1L; private String nodename = "default"; private final String clientName = "juddigui"; private boolean WS_Transport = false; private boolean WS_securePorts = false; /** * This is the singleton accessor UddiHub. There should be at most 1 * instance per HTTP Session (user login) * * @param application * @param _session * @return * @throws Exception */ public static UddiAdminHub getInstance(ServletContext application, HttpSession _session) throws Exception { Object j = _session.getAttribute("hub"); if (j == null) { UddiAdminHub hub = new UddiAdminHub(application, _session); _session.setAttribute("hub", hub); return hub; } return (UddiAdminHub) j; } String locale = "en"; private UddiAdminHub(ServletContext application, HttpSession _session) throws Exception { URL prop = application.getResource("/WEB-INF/config.properties"); if (prop == null) { throw new Exception("Cannot locate the configuration file."); } session = _session; InputStream in = prop.openStream(); Properties p = new Properties(); p.load(in); in.close(); session = _session; properties = p; EnsureConfig(); } private void EnsureConfig() { if (clientConfig == null) { try { UDDIClient client = new UDDIClient(); clientConfig = client.getClientConfig(); try { style = AuthStyle.valueOf(clientConfig.getConfiguration().getString(PROP_AUTH_TYPE)); } catch (Exception ex) { log.warn("'UDDI_AUTH' is not defined in the config (" + PROP_AUTH_TYPE + ")! defaulting to UDDI_AUTH"); style = AuthStyle.UDDI_AUTH; } nodename = clientConfig.getConfiguration().getString(PROP_CONFIG_NODE); if (nodename == null || nodename.equals("")) { log.warn("'node' is not defined in the config! defaulting to 'default'"); nodename = "default"; } UDDINode uddiNode = clientConfig.getUDDINode(nodename); String clazz = uddiNode.getProxyTransport(); if (clazz.contains("JAXWSTransport")) { WS_Transport = true; } Class<?> transportClass = ClassUtil.forName(clazz, Transport.class); if (transportClass != null) { - transport = (Transport) transportClass. - getConstructor(String.class).newInstance(nodename); + transport = client.getTransport(nodename); security = transport.getUDDISecurityService(); juddi = transport.getJUDDIApiService(); if (WS_Transport) { if (uddiNode.getJuddiApiUrl().toLowerCase().startsWith("https://") && (uddiNode.getSecurityUrl() != null && uddiNode.getSecurityUrl().toLowerCase().startsWith("https://"))) { WS_securePorts = true; } } } } catch (Exception ex) { HandleException(ex); } } } /** * This function provides a basic error handling rutine that will pull out * the true error message in a UDDI fault message, returning bootstrap * stylized html error message * * @param ex * @return */ private String HandleException(Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; log.error(null, ex); return ResourceLoader.GetResource(session, "errors.uddi") + " " + ex.getMessage() + " " + f.detail.getMessage(); } if (ex instanceof RemoteException) { RemoteException f = (RemoteException) ex; log.error(null, ex); return ResourceLoader.GetResource(session, "errors.generic") + " " + ex.getMessage() + " " + f.detail.getMessage(); } log.error(null, ex); return //"<div class=\"alert alert-error\" ><h3><i class=\"icon-warning-sign\"></i> " ResourceLoader.GetResource(session, "errors.generic") + " " + StringEscapeUtils.escapeHtml(ex.getMessage()); //+ "</h3></div>"; } /** * returns true if we are using JAXWS transport AND all of the URLs start * with https:// * * @return */ public boolean isSecure() { EnsureConfig(); return WS_securePorts; } /** * gets a reference to the current juddi client config file. this is a live * instance changes can be stored to disk, usually * * @return * @throws ConfigurationException g */ public ClientConfig GetJuddiClientConfig() throws ConfigurationException { EnsureConfig(); return clientConfig; } /** * Handles all API calls to the juddi web service * * @param parameters * @return */ public String go(HttpServletRequest parameters) { try { String action = parameters.getParameter("soapaction"); if (action.equalsIgnoreCase("adminDelete_tmodel")) { return adminDelete_tmodel(parameters); } if (action.equalsIgnoreCase("delete_ClientSubscriptionInfo")) { return delete_ClientSubscriptionInfo(parameters); } if (action.equalsIgnoreCase("delete_publisher")) { delete_publisher(parameters); } if (action.equalsIgnoreCase("getAllPublisherDetail")) { return getAllPublisherDetail(parameters); } if (action.equalsIgnoreCase("get_publisherDetail")) { return get_publisherDetail(parameters); } if (action.equalsIgnoreCase("invoke_SyncSubscription")) { return invoke_SyncSubscription(parameters); } if (action.equalsIgnoreCase("save_Clerk")) { // return save_Clerk(parameters); } if (action.equalsIgnoreCase("save_ClientSubscriptionInfo")) { return save_ClientSubscriptionInfo(parameters); } if (action.equalsIgnoreCase("save_Node")) { // return save_Node(parameters); } if (action.equalsIgnoreCase("save_publisher")) { return save_publisher(parameters); } } catch (Exception ex) { } return "error!"; } public enum AuthStyle { /** * Http */ HTTP, /** * UDDI Authentication via the Security API */ UDDI_AUTH } private String GetToken() { EnsureConfig(); if (style != AuthStyle.UDDI_AUTH) { BindingProvider bp = null; Map<String, Object> context = null; bp = (BindingProvider) juddi; context = bp.getRequestContext(); context.put(BindingProvider.USERNAME_PROPERTY, session.getAttribute("username")); context.put(BindingProvider.USERNAME_PROPERTY, session.getAttribute(AES.Decrypt("password", (String) properties.get("key")))); return null; } else { if (token != null) { return token; } GetAuthToken req = new GetAuthToken(); if (session.getAttribute("username") != null && session.getAttribute("password") != null) { req.setUserID((String) session.getAttribute("username")); req.setCred(AES.Decrypt((String) session.getAttribute("password"), (String) properties.get("key"))); try { AuthToken authToken = security.getAuthToken(req); token = authToken.getAuthInfo(); } catch (Exception ex) { return HandleException(ex); } } } return token; } private void delete_publisher(HttpServletRequest parameters) throws Exception { DeletePublisher sb = new DeletePublisher(); sb.setAuthInfo(GetToken()); sb.getPublisherId().add(parameters.getParameter("delete_publisherKEY")); try { juddi.deletePublisher(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); juddi.deletePublisher(sb); } } else { throw ex; } } } private String getAllPublisherDetail(HttpServletRequest parameters) { StringBuilder ret = new StringBuilder(); GetAllPublisherDetail sb = new GetAllPublisherDetail(); sb.setAuthInfo(GetToken()); PublisherDetail d = null; try { d = juddi.getAllPublisherDetail(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { d = juddi.getAllPublisherDetail(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } if (d != null) { ret.append("<table class=\"table table-hover\"><tr><th>Name</th><th>Info</th></tr>"); for (int i = 0; i < d.getPublisher().size(); i++) { ret.append("<tr><td>").append(StringEscapeUtils.escapeHtml(d.getPublisher().get(i).getPublisherName())) .append("</td><td>"); ret.append(PrintPublisherDetail(d.getPublisher().get(i))) .append("</td></tr>"); } ret.append("</table>"); } else { ret.append("No data returned"); } return ret.toString(); } private String PrintPublisherDetail(Publisher p) { StringBuilder ret = new StringBuilder(); ret.append("Authorized Name = ").append(StringEscapeUtils.escapeHtml(p.getAuthorizedName())) .append("<br>") .append("Publisher Name = ").append(StringEscapeUtils.escapeHtml(p.getPublisherName())) .append("<br>") .append("Email = ") .append(StringEscapeUtils.escapeHtml(p.getEmailAddress())) .append("<br>") .append("Administrator = ") .append(StringEscapeUtils.escapeHtml(p.getIsAdmin())) .append("<br>") .append("Enabled = ") .append(StringEscapeUtils.escapeHtml(p.getIsEnabled())) .append("<br>") .append("Max Bindings per = ") .append(p.getMaxBindingsPerService()) .append("<br>") .append("Max Businesses = ") .append(p.getMaxBusinesses()) .append("<br>") .append("Max Services per = ") .append(p.getMaxServicePerBusiness()) .append("<br>") .append("Max tModels = ") .append(p.getMaxTModels()) .append(""); return ret.toString(); } private String get_publisherDetail(HttpServletRequest parameters) { StringBuilder ret = new StringBuilder(); GetPublisherDetail sb = new GetPublisherDetail(); sb.getPublisherId().add(parameters.getParameter("get_publisherDetailKEY")); sb.setAuthInfo(GetToken()); PublisherDetail d = null; try { d = juddi.getPublisherDetail(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { d = juddi.getPublisherDetail(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } if (d != null) { ret.append("<table class=\"table table-hover\"><tr>th>Name</th><th><th>Info</th></tr>"); for (int i = 0; i < d.getPublisher().size(); i++) { ret.append("<tr><td>").append(StringEscapeUtils.escapeHtml(d.getPublisher().get(i).getPublisherName())) .append("</td><td>"); ret.append(PrintPublisherDetail(d.getPublisher().get(i))) .append("</td></tr>"); } ret.append("</table>"); } else { ret.append("No data returned"); } return ret.toString(); } private String invoke_SyncSubscription(HttpServletRequest parameters) { StringBuilder ret = new StringBuilder(); SyncSubscription sb = new SyncSubscription(); SyncSubscriptionDetail d = null; try { StringReader sr = new StringReader(parameters.getParameter("invokeSyncSubscriptionXML").trim()); sb = (JAXB.unmarshal(sr, SyncSubscription.class)); sb.setAuthInfo(GetToken()); d = juddi.invokeSyncSubscription(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { d = juddi.invokeSyncSubscription(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } if (d != null) { ret.append("<pre>"); StringWriter sw = new StringWriter(); JAXB.marshal(d, sw); sw.append(PrettyPrintXML(sw.toString())); ret.append("</pre>"); } else { ret.append("No data returned"); } return ret.toString(); } private static String PrettyPrintXML(String input) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(input)); transformer.transform(source, result); String xmlString = result.getWriter().toString(); return (xmlString); } catch (Exception ex) { } return null; } private String save_ClientSubscriptionInfo(HttpServletRequest parameters) { StringBuilder ret = new StringBuilder(); SaveClientSubscriptionInfo sb = new SaveClientSubscriptionInfo(); ClientSubscriptionInfoDetail d = null; try { StringReader sr = new StringReader(parameters.getParameter("invokeSyncSubscriptionXML").trim()); sb = (JAXB.unmarshal(sr, SaveClientSubscriptionInfo.class)); sb.setAuthInfo(GetToken()); d = juddi.saveClientSubscriptionInfo(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { d = juddi.saveClientSubscriptionInfo(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } if (d != null) { ret.append("<pre>"); StringWriter sw = new StringWriter(); JAXB.marshal(d, sw); sw.append(PrettyPrintXML(sw.toString())); ret.append("</pre>"); } else { ret.append("No data returned"); } return ret.toString(); } private String save_publisher(HttpServletRequest parameters) { SavePublisher sb = new SavePublisher(); Publisher p = new Publisher(); p.setAuthorizedName(parameters.getParameter("savePublisherAuthorizedName")); p.setPublisherName(parameters.getParameter("savePublisherNAME")); p.setEmailAddress(parameters.getParameter("savePublisherEMAIL")); p.setIsAdmin(parameters.getParameter("savePublisherIsAdmin")); p.setIsEnabled(parameters.getParameter("savePublisherIsEnabled")); sb.getPublisher().add(p); PublisherDetail d = null; sb.setAuthInfo(GetToken()); try { p.setMaxBindingsPerService(Integer.parseInt(parameters.getParameter("savePublisherMaxBindings"))); p.setMaxServicePerBusiness(Integer.parseInt(parameters.getParameter("savePublisherMaxServices"))); p.setMaxBusinesses(Integer.parseInt(parameters.getParameter("savePublisherMaxBusiness"))); p.setMaxTModels(Integer.parseInt(parameters.getParameter("savePublisherMaxTModels"))); d = juddi.savePublisher(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { d = juddi.savePublisher(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } return "Success"; } private String adminDelete_tmodel(HttpServletRequest parameters) { DeleteTModel sb = new DeleteTModel(); sb.getTModelKey().add(parameters.getParameter("adminDelete_tmodelKEY")); sb.setAuthInfo(GetToken()); try { juddi.adminDeleteTModel(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { juddi.adminDeleteTModel(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } return "Success"; } private String delete_ClientSubscriptionInfo(HttpServletRequest parameters) { DeleteClientSubscriptionInfo sb = new DeleteClientSubscriptionInfo(); sb.getSubscriptionKey().add(parameters.getParameter("delete_ClientSubscriptionInfoKEY")); sb.setAuthInfo(GetToken()); try { juddi.deleteClientSubscriptionInfo(sb); } catch (Exception ex) { if (ex instanceof DispositionReportFaultMessage) { DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex; if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) { token = null; sb.setAuthInfo(GetToken()); try { juddi.deleteClientSubscriptionInfo(sb); } catch (Exception ex1) { return HandleException(ex); } } } else { return HandleException(ex); } } return "Success"; } /** * If false, the configuration page will be available from anywhere. * If true, it will only be accessible from the server hosting juddi-gui. * if not defined, the result is true. * @return */ public boolean isAdminLocalhostOnly() { return clientConfig.getConfiguration().getBoolean(PROP_ADMIN_LOCALHOST_ONLY, true); } }
true
true
private void EnsureConfig() { if (clientConfig == null) { try { UDDIClient client = new UDDIClient(); clientConfig = client.getClientConfig(); try { style = AuthStyle.valueOf(clientConfig.getConfiguration().getString(PROP_AUTH_TYPE)); } catch (Exception ex) { log.warn("'UDDI_AUTH' is not defined in the config (" + PROP_AUTH_TYPE + ")! defaulting to UDDI_AUTH"); style = AuthStyle.UDDI_AUTH; } nodename = clientConfig.getConfiguration().getString(PROP_CONFIG_NODE); if (nodename == null || nodename.equals("")) { log.warn("'node' is not defined in the config! defaulting to 'default'"); nodename = "default"; } UDDINode uddiNode = clientConfig.getUDDINode(nodename); String clazz = uddiNode.getProxyTransport(); if (clazz.contains("JAXWSTransport")) { WS_Transport = true; } Class<?> transportClass = ClassUtil.forName(clazz, Transport.class); if (transportClass != null) { transport = (Transport) transportClass. getConstructor(String.class).newInstance(nodename); security = transport.getUDDISecurityService(); juddi = transport.getJUDDIApiService(); if (WS_Transport) { if (uddiNode.getJuddiApiUrl().toLowerCase().startsWith("https://") && (uddiNode.getSecurityUrl() != null && uddiNode.getSecurityUrl().toLowerCase().startsWith("https://"))) { WS_securePorts = true; } } } } catch (Exception ex) { HandleException(ex); } } }
private void EnsureConfig() { if (clientConfig == null) { try { UDDIClient client = new UDDIClient(); clientConfig = client.getClientConfig(); try { style = AuthStyle.valueOf(clientConfig.getConfiguration().getString(PROP_AUTH_TYPE)); } catch (Exception ex) { log.warn("'UDDI_AUTH' is not defined in the config (" + PROP_AUTH_TYPE + ")! defaulting to UDDI_AUTH"); style = AuthStyle.UDDI_AUTH; } nodename = clientConfig.getConfiguration().getString(PROP_CONFIG_NODE); if (nodename == null || nodename.equals("")) { log.warn("'node' is not defined in the config! defaulting to 'default'"); nodename = "default"; } UDDINode uddiNode = clientConfig.getUDDINode(nodename); String clazz = uddiNode.getProxyTransport(); if (clazz.contains("JAXWSTransport")) { WS_Transport = true; } Class<?> transportClass = ClassUtil.forName(clazz, Transport.class); if (transportClass != null) { transport = client.getTransport(nodename); security = transport.getUDDISecurityService(); juddi = transport.getJUDDIApiService(); if (WS_Transport) { if (uddiNode.getJuddiApiUrl().toLowerCase().startsWith("https://") && (uddiNode.getSecurityUrl() != null && uddiNode.getSecurityUrl().toLowerCase().startsWith("https://"))) { WS_securePorts = true; } } } } catch (Exception ex) { HandleException(ex); } } }
diff --git a/test/unit/org/apache/cassandra/hadoop/fs/CassandraFileSystemTest.java b/test/unit/org/apache/cassandra/hadoop/fs/CassandraFileSystemTest.java index ea4125b..a503a75 100644 --- a/test/unit/org/apache/cassandra/hadoop/fs/CassandraFileSystemTest.java +++ b/test/unit/org/apache/cassandra/hadoop/fs/CassandraFileSystemTest.java @@ -1,192 +1,192 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.hadoop.fs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.*; import java.net.URI; import java.security.MessageDigest; import java.util.List; import java.util.Set; import java.util.concurrent.Future; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.apache.cassandra.CleanupHelper; import org.apache.cassandra.EmbeddedServer; import org.apache.cassandra.Util; import org.apache.cassandra.config.ConfigurationException; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.Table; import org.apache.cassandra.utils.FBUtilities; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.thrift.transport.TTransportException; public class CassandraFileSystemTest extends CleanupHelper { /** * Set embedded cassandra up and spawn it in a new thread. * * @throws TTransportException * @throws IOException * @throws InterruptedException */ @BeforeClass public static void setup() throws TTransportException, IOException, InterruptedException, ConfigurationException { EmbeddedServer.startBrisk(); } @Test public void testFileSystemWithoutFlush() throws Exception { testFileSystem(false); } @Test public void testFileSystemWithFlush() throws Exception { testFileSystem(true); } private void testFileSystem(boolean flush) throws Exception { CassandraFileSystem fs = new CassandraFileSystem(); fs.initialize(URI.create("cassandra://localhost:"+DatabaseDescriptor.getRpcPort()+"/"), new Configuration()); fs.mkdirs(new Path("/mytestdir")); fs.mkdirs(new Path("/mytestdir/sub1")); fs.mkdirs(new Path("/mytestdir/sub2")); fs.mkdirs(new Path("/mytestdir/sub3")); fs.mkdirs(new Path("/mytestdir/sub3/sub4")); //Create a 1MB file to sent to fs File tmp = File.createTempFile("testcfs", "input"); Writer writer = new FileWriter(tmp); char buf[] = new char[1024]; fillArray(buf); for(int i=0; i<1024; i++) writer.write(buf); writer.close(); tmp.deleteOnExit(); //Write file - fs.copyFromLocalFile(new Path("file://"+tmp.getAbsoluteFile()), new Path("/mytestdir/testfile")); + fs.copyFromLocalFile(new Path("file://"+tmp.getAbsolutePath()), new Path("/mytestdir/testfile")); if(flush) { List<Future<?>> cb = Table.open("cfs").flush(); for(Future c : cb) c.get(); } Set<Path> allPaths = fs.store.listDeepSubPaths(new Path("/mytestdir")); //Verify deep paths assertEquals(6, allPaths.size()); //verify shallow path Set<Path> thisPath = fs.store.listSubPaths(new Path("/mytestdir")); assertEquals(4, thisPath.size()); //Check file status FileStatus stat = fs.getFileStatus(new Path("/mytestdir/testfile")); - assertEquals(1024*1024, stat.getLen()); + assertEquals(tmp.getAbsoluteFile().length(), stat.getLen()); assertEquals(false, stat.isDir()); //Check block info BlockLocation[] info = fs.getFileBlockLocations(stat, 0, stat.getLen()); assertEquals(1, info.length); assertEquals(FBUtilities.getLocalAddress().getHostName(), info[0].getHosts()[0]); info = fs.getFileBlockLocations(stat, 1, 10); assertTrue(info.length == 1); info = fs.getFileBlockLocations(stat, 0, 200); assertTrue(info.length == 1); //Check dir status stat = fs.getFileStatus(new Path("/mytestdir")); assertEquals(true, stat.isDir()); //Read back the file File out = File.createTempFile("testcfs", "output"); fs.copyToLocalFile(new Path("/mytestdir/testfile"), new Path("file://"+ out.getAbsolutePath())); Reader reader = new FileReader(out); for(int i=0; i<1024; i++) { assertEquals(1024, reader.read(buf)); } assertEquals(-1,reader.read()); reader.close(); out.deleteOnExit(); // Verify the digests assertDigest(tmp, out); } private void fillArray(char[] buf) { for (int j = 0; j < buf.length; j++) { buf[j] = (char) j; } } private void assertDigest(File srcFile, File outFile) throws Exception { MessageDigest md5 = MessageDigest.getInstance("MD5"); InputStream srcFileIn = null; InputStream outFileIn = null; try { srcFileIn = new BufferedInputStream(new FileInputStream(srcFile)); byte[] expected = Util.digestInputStream(md5, srcFileIn); outFileIn = new BufferedInputStream(new FileInputStream(outFile)); byte[] actual = Util.digestInputStream(md5, outFileIn); Assert.assertArrayEquals(expected, actual); } finally { srcFileIn.close(); outFileIn.close(); } } }
false
true
private void testFileSystem(boolean flush) throws Exception { CassandraFileSystem fs = new CassandraFileSystem(); fs.initialize(URI.create("cassandra://localhost:"+DatabaseDescriptor.getRpcPort()+"/"), new Configuration()); fs.mkdirs(new Path("/mytestdir")); fs.mkdirs(new Path("/mytestdir/sub1")); fs.mkdirs(new Path("/mytestdir/sub2")); fs.mkdirs(new Path("/mytestdir/sub3")); fs.mkdirs(new Path("/mytestdir/sub3/sub4")); //Create a 1MB file to sent to fs File tmp = File.createTempFile("testcfs", "input"); Writer writer = new FileWriter(tmp); char buf[] = new char[1024]; fillArray(buf); for(int i=0; i<1024; i++) writer.write(buf); writer.close(); tmp.deleteOnExit(); //Write file fs.copyFromLocalFile(new Path("file://"+tmp.getAbsoluteFile()), new Path("/mytestdir/testfile")); if(flush) { List<Future<?>> cb = Table.open("cfs").flush(); for(Future c : cb) c.get(); } Set<Path> allPaths = fs.store.listDeepSubPaths(new Path("/mytestdir")); //Verify deep paths assertEquals(6, allPaths.size()); //verify shallow path Set<Path> thisPath = fs.store.listSubPaths(new Path("/mytestdir")); assertEquals(4, thisPath.size()); //Check file status FileStatus stat = fs.getFileStatus(new Path("/mytestdir/testfile")); assertEquals(1024*1024, stat.getLen()); assertEquals(false, stat.isDir()); //Check block info BlockLocation[] info = fs.getFileBlockLocations(stat, 0, stat.getLen()); assertEquals(1, info.length); assertEquals(FBUtilities.getLocalAddress().getHostName(), info[0].getHosts()[0]); info = fs.getFileBlockLocations(stat, 1, 10); assertTrue(info.length == 1); info = fs.getFileBlockLocations(stat, 0, 200); assertTrue(info.length == 1); //Check dir status stat = fs.getFileStatus(new Path("/mytestdir")); assertEquals(true, stat.isDir()); //Read back the file File out = File.createTempFile("testcfs", "output"); fs.copyToLocalFile(new Path("/mytestdir/testfile"), new Path("file://"+ out.getAbsolutePath())); Reader reader = new FileReader(out); for(int i=0; i<1024; i++) { assertEquals(1024, reader.read(buf)); } assertEquals(-1,reader.read()); reader.close(); out.deleteOnExit(); // Verify the digests assertDigest(tmp, out); }
private void testFileSystem(boolean flush) throws Exception { CassandraFileSystem fs = new CassandraFileSystem(); fs.initialize(URI.create("cassandra://localhost:"+DatabaseDescriptor.getRpcPort()+"/"), new Configuration()); fs.mkdirs(new Path("/mytestdir")); fs.mkdirs(new Path("/mytestdir/sub1")); fs.mkdirs(new Path("/mytestdir/sub2")); fs.mkdirs(new Path("/mytestdir/sub3")); fs.mkdirs(new Path("/mytestdir/sub3/sub4")); //Create a 1MB file to sent to fs File tmp = File.createTempFile("testcfs", "input"); Writer writer = new FileWriter(tmp); char buf[] = new char[1024]; fillArray(buf); for(int i=0; i<1024; i++) writer.write(buf); writer.close(); tmp.deleteOnExit(); //Write file fs.copyFromLocalFile(new Path("file://"+tmp.getAbsolutePath()), new Path("/mytestdir/testfile")); if(flush) { List<Future<?>> cb = Table.open("cfs").flush(); for(Future c : cb) c.get(); } Set<Path> allPaths = fs.store.listDeepSubPaths(new Path("/mytestdir")); //Verify deep paths assertEquals(6, allPaths.size()); //verify shallow path Set<Path> thisPath = fs.store.listSubPaths(new Path("/mytestdir")); assertEquals(4, thisPath.size()); //Check file status FileStatus stat = fs.getFileStatus(new Path("/mytestdir/testfile")); assertEquals(tmp.getAbsoluteFile().length(), stat.getLen()); assertEquals(false, stat.isDir()); //Check block info BlockLocation[] info = fs.getFileBlockLocations(stat, 0, stat.getLen()); assertEquals(1, info.length); assertEquals(FBUtilities.getLocalAddress().getHostName(), info[0].getHosts()[0]); info = fs.getFileBlockLocations(stat, 1, 10); assertTrue(info.length == 1); info = fs.getFileBlockLocations(stat, 0, 200); assertTrue(info.length == 1); //Check dir status stat = fs.getFileStatus(new Path("/mytestdir")); assertEquals(true, stat.isDir()); //Read back the file File out = File.createTempFile("testcfs", "output"); fs.copyToLocalFile(new Path("/mytestdir/testfile"), new Path("file://"+ out.getAbsolutePath())); Reader reader = new FileReader(out); for(int i=0; i<1024; i++) { assertEquals(1024, reader.read(buf)); } assertEquals(-1,reader.read()); reader.close(); out.deleteOnExit(); // Verify the digests assertDigest(tmp, out); }
diff --git a/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java b/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java index 035593ae..fc9829c9 100644 --- a/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java +++ b/MonTransit/src/org/montrealtransit/android/activity/FavListTab.java @@ -1,954 +1,954 @@ package org.montrealtransit.android.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.BusUtils; import org.montrealtransit.android.LocationUtils; import org.montrealtransit.android.MenuUtils; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.SensorUtils; import org.montrealtransit.android.SensorUtils.CompassListener; import org.montrealtransit.android.SubwayUtils; import org.montrealtransit.android.Utils; import org.montrealtransit.android.api.SupportFactory; import org.montrealtransit.android.data.ABikeStation; import org.montrealtransit.android.data.ABusStop; import org.montrealtransit.android.data.ASubwayStation; import org.montrealtransit.android.data.Pair; import org.montrealtransit.android.provider.BixiManager; import org.montrealtransit.android.provider.BixiStore.BikeStation; import org.montrealtransit.android.provider.DataManager; import org.montrealtransit.android.provider.DataStore; import org.montrealtransit.android.provider.DataStore.Fav; import org.montrealtransit.android.provider.StmManager; import org.montrealtransit.android.provider.StmStore.BusStop; import org.montrealtransit.android.provider.StmStore.SubwayLine; import org.montrealtransit.android.provider.StmStore.SubwayStation; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.hardware.GeomagneticField; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.location.Location; import android.location.LocationListener; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; /** * This activity list the favorite bus stops. * @author Mathieu Méa */ public class FavListTab extends Activity implements LocationListener, SensorEventListener, CompassListener { /** * The log tag. */ private static final String TAG = FavListTab.class.getSimpleName(); /** * The tracker tag. */ private static final String TRACKER_TAG = "/FavList"; /** * The favorite bike station list. */ private List<DataStore.Fav> currentBikeStationFavList; /** * The bike stations. */ private List<ABikeStation> bikeStations; /** * The favorite subway stations list. */ private List<DataStore.Fav> currentSubwayStationFavList; /** * The subway stations. */ private List<ASubwayStation> subwayStations; /** * The favorite bus stops list. */ private List<DataStore.Fav> currentBusStopFavList; /** * The bus stops. */ private List<ABusStop> busStops; /** * Store the device location. */ private Location location; /** * Is the location updates enabled? */ private boolean locationUpdatesEnabled = false; /** * The {@link Sensor#TYPE_ACCELEROMETER} values. */ private float[] accelerometerValues; /** * The {@link Sensor#TYPE_MAGNETIC_FIELD} values. */ private float[] magneticFieldValues; /** * The last compass value. */ private int lastCompassInDegree = -1; @Override protected void onCreate(Bundle savedInstanceState) { MyLog.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); // set the UI setContentView(R.layout.fav_list_tab); } /** * True if the activity has the focus, false otherwise. */ private boolean hasFocus = true; @Override public void onWindowFocusChanged(boolean hasFocus) { MyLog.v(TAG, "onWindowFocusChanged(%s)", hasFocus); // IF the activity just regained the focus DO if (!this.hasFocus && hasFocus) { onResumeWithFocus(); } this.hasFocus = hasFocus; } @Override protected void onResume() { MyLog.v(TAG, "onResume()"); // IF the activity has the focus DO if (this.hasFocus) { onResumeWithFocus(); } super.onResume(); } /** * {@link #onResume()} when activity has the focus */ public void onResumeWithFocus() { MyLog.v(TAG, "onResumeWithFocus()"); // IF location updates should be enabled DO if (!this.locationUpdatesEnabled) { new AsyncTask<Void, Void, Location>() { @Override protected Location doInBackground(Void... params) { return LocationUtils.getBestLastKnownLocation(FavListTab.this); } @Override protected void onPostExecute(Location result) { // IF there is a valid last know location DO if (result != null) { // set the new distance setLocation(result); updateDistancesWithNewLocation(); } // re-enable LocationUtils.enableLocationUpdates(FavListTab.this, FavListTab.this); FavListTab.this.locationUpdatesEnabled = true; }; }.execute(); } AnalyticsUtils.trackPageView(this, TRACKER_TAG); setUpUI(); } @Override public void onSensorChanged(SensorEvent se) { // MyLog.v(TAG, "onSensorChanged()"); checkForCompass(se, this); } /** * @see SensorUtils#checkForCompass(SensorEvent, float[], float[], CompassListener) */ public void checkForCompass(SensorEvent event, CompassListener listener) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: accelerometerValues = event.values; if (magneticFieldValues != null) { listener.onCompass(); } break; case Sensor.TYPE_MAGNETIC_FIELD: magneticFieldValues = event.values; if (accelerometerValues != null) { listener.onCompass(); } break; } } @Override public void onCompass() { // MyLog.v(TAG, "onCompass()"); if (this.accelerometerValues != null && this.magneticFieldValues != null) { updateCompass(SensorUtils.calculateOrientation(this, this.accelerometerValues, this.magneticFieldValues)); } } /** * Update the compass image(s). * @param orientation the new orientation */ private void updateCompass(float[] orientation) { // MyLog.v(TAG, "updateCompass(%s)", orientation); Location currentLocation = getLocation(); if (currentLocation != null) { int io = (int) orientation[0]; if (io != 0 && Math.abs(this.lastCompassInDegree - io) > SensorUtils.LIST_VIEW_COMPASS_DEGREE_UPDATE_THRESOLD) { this.lastCompassInDegree = io; // update bus stops compass if (this.busStops != null) { View busStopsLayout = findViewById(R.id.bus_stops_list); for (ABusStop busStop : this.busStops) { if (busStop.getLocation() == null) { continue; } // update value busStop.getCompassMatrix().reset(); busStop.getCompassMatrix().postRotate( SensorUtils.getCompassRotationInDegree(this, currentLocation, busStop.getLocation(), orientation, getLocationDeclination()), getArrowDim().first / 2, getArrowDim().second / 2); // update view View stopView = busStopsLayout.findViewWithTag(getBusStopViewTag(busStop)); if (stopView != null && !TextUtils.isEmpty(busStop.getDistanceString())) { ImageView compassImg = (ImageView) stopView.findViewById(R.id.compass); compassImg.setImageMatrix(busStop.getCompassMatrix()); compassImg.setVisibility(View.VISIBLE); } } } // update subway station compass if (this.subwayStations != null) { View subwayStationsLayout = findViewById(R.id.subway_stations_list); for (ASubwayStation subwayStation : this.subwayStations) { // update value subwayStation.getCompassMatrix().reset(); subwayStation.getCompassMatrix().postRotate( SensorUtils.getCompassRotationInDegree(this, currentLocation, subwayStation.getLocation(), orientation, getLocationDeclination()), getArrowDim().first / 2, getArrowDim().second / 2); // update view View stationView = subwayStationsLayout.findViewWithTag(getSubwayStationViewTag(subwayStation)); if (stationView != null && !TextUtils.isEmpty(subwayStation.getDistanceString())) { ImageView compassImg = (ImageView) stationView.findViewById(R.id.compass); compassImg.setImageMatrix(subwayStation.getCompassMatrix()); compassImg.setVisibility(View.VISIBLE); } } } // update bike stations compass if (this.bikeStations != null) { View bikeStationsLayout = findViewById(R.id.bike_stations_list); for (ABikeStation bikeStation : this.bikeStations) { // update value bikeStation.getCompassMatrix().reset(); bikeStation.getCompassMatrix() .postRotate( SensorUtils.getCompassRotationInDegree(this, currentLocation, bikeStation.getLocation(), orientation, getLocationDeclination()), getArrowDim().first / 2, getArrowDim().second / 2); // update view View stationView = bikeStationsLayout.findViewWithTag(getBikeStationViewTag(bikeStation)); if (stationView != null && !TextUtils.isEmpty(bikeStation.getDistanceString())) { ImageView compassImg = (ImageView) stationView.findViewById(R.id.compass); compassImg.setImageMatrix(bikeStation.getCompassMatrix()); compassImg.setVisibility(View.VISIBLE); } } } } } } private Pair<Integer, Integer> arrowDim; private Float locationDeclination; private float getLocationDeclination() { if (this.locationDeclination == null && this.location != null) { this.locationDeclination = new GeomagneticField((float) this.location.getLatitude(), (float) this.location.getLongitude(), (float) this.location.getAltitude(), this.location.getTime()).getDeclination(); } return this.locationDeclination; } public Pair<Integer, Integer> getArrowDim() { if (this.arrowDim == null) { this.arrowDim = SensorUtils.getResourceDimension(this, R.drawable.heading_arrow); } return this.arrowDim; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // MyLog.v(TAG, "onAccuracyChanged()"); } @Override protected void onPause() { MyLog.v(TAG, "onPause()"); LocationUtils.disableLocationUpdates(this, this); this.locationUpdatesEnabled = false; SensorUtils.unregisterSensorListener(this, this); super.onPause(); } /** * Refresh all the UI. */ private void setUpUI() { MyLog.v(TAG, "setUpUI()"); loadFavoritesFromDB(); } private void loadFavoritesFromDB() { MyLog.v(TAG, "loadFavoritesFromDB()"); new AsyncTask<Void, Void, Void>() { private List<DataStore.Fav> newBusStopFavList; private List<BusStop> busStopsExtendedList; private List<DataStore.Fav> newSubwayFavList; private Map<String, SubwayStation> subwayStations; private Map<String, List<SubwayLine>> otherSubwayLines; private List<DataStore.Fav> newBikeFavList; private Map<String, BikeStation> bikeStations; @Override protected Void doInBackground(Void... params) { // MyLog.v(TAG, "doInBackground()"); // BUS STOPs this.newBusStopFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP); if (FavListTab.this.currentBusStopFavList == null || !Fav.listEquals(FavListTab.this.currentBusStopFavList, this.newBusStopFavList)) { if (Utils.getCollectionSize(this.newBusStopFavList) > 0) { MyLog.d(TAG, "Loading bus stop favorites from DB..."); this.busStopsExtendedList = StmManager.findBusStopsExtendedList(getContentResolver(), Utils.extractBusStopIDsFromFavList(this.newBusStopFavList)); MyLog.d(TAG, "Loading bus stop favorites from DB... DONE"); } } // SUBWAY STATIONs this.newSubwayFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION); if (FavListTab.this.currentSubwayStationFavList == null || !Fav.listEquals(FavListTab.this.currentSubwayStationFavList, this.newSubwayFavList)) { MyLog.d(TAG, "Loading subway station favorites from DB..."); this.subwayStations = new HashMap<String, SubwayStation>(); this.otherSubwayLines = new HashMap<String, List<SubwayLine>>(); for (Fav subwayFav : this.newSubwayFavList) { SubwayStation station = StmManager.findSubwayStation(getContentResolver(), subwayFav.getFkId()); this.subwayStations.put(subwayFav.getFkId(), station); if (station != null) { this.otherSubwayLines.put(station.getId(), StmManager.findSubwayStationLinesList(getContentResolver(), station.getId())); } } MyLog.d(TAG, "Loading subway station favorites from DB... DONE"); } // BIKE STATIONs this.newBikeFavList = DataManager.findFavsByTypeList(getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BIKE_STATIONS); if (FavListTab.this.currentBikeStationFavList == null || !Fav.listEquals(FavListTab.this.currentBikeStationFavList, this.newBikeFavList)) { if (Utils.getCollectionSize(this.newBikeFavList) > 0) { MyLog.d(TAG, "Loading bike station favorites from DB..."); this.bikeStations = BixiManager.findBikeStationsMap(getContentResolver(), Utils.extractBikeStationTerminNamesFromFavList(this.newBikeFavList)); MyLog.d(TAG, "Loading bike station favorites from DB... DONE"); } } return null; } @Override protected void onPostExecute(Void result) { if (newBusStopFavList != null) { // IF favorite bus stop list was refreshed DO update the UI refreshBusStopsUI(this.newBusStopFavList, this.busStopsExtendedList); } if (newSubwayFavList != null) { // IF favorite subway station list was refreshed DO update the UI refreshSubwayStationsUI(this.newSubwayFavList, this.subwayStations, this.otherSubwayLines); } if (newBikeFavList != null) { // IF favorite bike station list was refreshed DO update the UI refreshBikeStationsUI(this.newBikeFavList, this.bikeStations); } showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); } }.execute(); } public boolean isThereAtLeastOneFavorite() { return Utils.getCollectionSize(FavListTab.this.currentBusStopFavList) > 0 || Utils.getCollectionSize(FavListTab.this.currentSubwayStationFavList) > 0 || Utils.getCollectionSize(FavListTab.this.currentBikeStationFavList) > 0; } /** * Show 'no favorite' view if necessary. */ private void showEmptyFav() { MyLog.v(TAG, "showEmptyFav()"); findViewById(R.id.loading).setVisibility(View.GONE); if (!isThereAtLeastOneFavorite()) { findViewById(R.id.lists).setVisibility(View.GONE); findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { // at least 1 favorite findViewById(R.id.empty).setVisibility(View.GONE); findViewById(R.id.lists).setVisibility(View.VISIBLE); // IF there is no favorite bus stops DO if (this.currentBusStopFavList == null || this.currentBusStopFavList.size() == 0) { findViewById(R.id.fav_bus_stops).setVisibility(View.GONE); findViewById(R.id.bus_stops_list).setVisibility(View.GONE); } // IF there is no favorite subway stations DO if (this.currentSubwayStationFavList == null || this.currentSubwayStationFavList.size() == 0) { findViewById(R.id.fav_subway_stations).setVisibility(View.GONE); findViewById(R.id.subway_stations_list).setVisibility(View.GONE); } // IF there is no favorite bike stations DO if (this.currentBikeStationFavList == null || this.currentBikeStationFavList.size() == 0) { findViewById(R.id.fav_bike_stations).setVisibility(View.GONE); findViewById(R.id.bike_stations_list).setVisibility(View.GONE); } } } /** * Refresh the favorite bus stops UI * @param newBusStopFavList the new favorite bus stops * @param busStopsExtendedList the bus stops (extended) */ private void refreshBusStopsUI(List<DataStore.Fav> newBusStopFavList, List<BusStop> busStopsExtendedList) { // MyLog.v(TAG, "refreshBusStopsUI(%s,%s)", Utils.getCollectionSize(newBusStopFavList), Utils.getCollectionSize(busStopsExtendedList)); if (this.currentBusStopFavList == null || this.currentBusStopFavList.size() != newBusStopFavList.size()) { // remove all favorite bus stop views LinearLayout busStopsLayout = (LinearLayout) findViewById(R.id.bus_stops_list); busStopsLayout.removeAllViews(); // use new favorite bus stops this.currentBusStopFavList = newBusStopFavList; this.busStops = new ArrayList<ABusStop>(); findViewById(R.id.lists).setVisibility(View.VISIBLE); findViewById(R.id.fav_bus_stops).setVisibility(View.VISIBLE); busStopsLayout.setVisibility(View.VISIBLE); // FOR EACH bus stop DO - if (this.busStops != null) { + if (busStopsExtendedList != null) { for (final BusStop busStop : busStopsExtendedList) { // list view divider if (busStopsLayout.getChildCount() > 0) { busStopsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, busStopsLayout, false)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_bus_stop_item, busStopsLayout, false); view.setTag(getBusStopViewTag(busStop)); // bus stop code ((TextView) view.findViewById(R.id.stop_code)).setText(busStop.getCode()); // bus stop place String busStopPlace = BusUtils.cleanBusStopPlace(busStop.getPlace()); ((TextView) view.findViewById(R.id.label)).setText(busStopPlace); // bus stop line number TextView lineNumberTv = (TextView) view.findViewById(R.id.line_number); lineNumberTv.setText(busStop.getLineNumber()); int color = BusUtils.getBusLineTypeBgColor(busStop.getLineTypeOrNull(), busStop.getLineNumber()); lineNumberTv.setBackgroundColor(color); // bus stop line direction int busLineDirection = BusUtils.getBusLineSimpleDirection(busStop.getDirectionId()); ((TextView) view.findViewById(R.id.line_direction)).setText(getString(busLineDirection).toUpperCase(Locale.getDefault())); // bus station distance TextView distanceTv = (TextView) view.findViewById(R.id.distance); distanceTv.setVisibility(View.GONE); distanceTv.setText(null); // compass view.findViewById(R.id.compass).setVisibility(View.GONE); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); final View theViewToDelete = v; new AlertDialog.Builder(FavListTab.this) .setTitle(getString(R.string.bus_stop_and_line_short, busStop.getCode(), busStop.getLineNumber())) .setItems( new CharSequence[] { getString(R.string.view_bus_stop), getString(R.string.view_bus_stop_line), getString(R.string.remove_fav) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case 0: Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); break; case 1: Intent intent2 = new Intent(FavListTab.this, SupportFactory.getInstance(FavListTab.this) .getBusLineInfoClass()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NUMBER, busStop.getLineNumber()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NAME, busStop.getLineNameOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_TYPE, busStop.getLineTypeOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_DIRECTION_ID, busStop.getDirectionId()); startActivity(intent2); break; case 2: // remove the view from the UI ((LinearLayout) findViewById(R.id.bus_stops_list)).removeView(theViewToDelete); // remove the favorite from the current list Iterator<Fav> it = FavListTab.this.currentBusStopFavList.iterator(); while (it.hasNext()) { DataStore.Fav fav = (DataStore.Fav) it.next(); if (fav.getFkId().equals(busStop.getCode()) && fav.getFkId2().equals(busStop.getLineNumber())) { it.remove(); break; } } // refresh empty showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP, busStop.getCode(), busStop.getLineNumber()); // delete the favorite if (findFav != null) { DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); } SupportFactory.getInstance(FavListTab.this).backupManagerDataChanged(); break; default: break; } } }).create().show(); return true; } }); this.busStops.add(new ABusStop(busStop)); busStopsLayout.addView(view); } } } } private String getBusStopViewTag(BusStop busStop) { return "busStop" + busStop.getUID(); } /** * Refresh subway station UI. * @param newSubwayFavList the new favorite subway stations list * @param stations the new favorite subway stations * @param otherLines the new favorite subway stations "other lines" */ private void refreshSubwayStationsUI(List<DataStore.Fav> newSubwayFavList, Map<String, SubwayStation> stations, Map<String, List<SubwayLine>> otherLines) { // MyLog.v(TAG, "refreshSubwayStationsUI()", Utils.getCollectionSize(newSubwayFavList), Utils.getMapSize(stations), Utils.getMapSize(otherLines)); if (this.currentSubwayStationFavList == null || this.currentSubwayStationFavList.size() != newSubwayFavList.size()) { LinearLayout subwayStationsLayout = (LinearLayout) findViewById(R.id.subway_stations_list); // remove all subway station views subwayStationsLayout.removeAllViews(); // use new favorite subway station this.currentSubwayStationFavList = newSubwayFavList; this.subwayStations = new ArrayList<ASubwayStation>(); findViewById(R.id.lists).setVisibility(View.VISIBLE); findViewById(R.id.fav_subway_stations).setVisibility(View.VISIBLE); subwayStationsLayout.setVisibility(View.VISIBLE); // FOR EACH favorite subway DO for (Fav subwayFav : this.currentSubwayStationFavList) { final SubwayStation subwayStation = stations == null ? null : stations.get(subwayFav.getFkId()); if (subwayStation != null) { List<SubwayLine> otherLinesId = otherLines.get(subwayStation.getId()); // list view divider if (subwayStationsLayout.getChildCount() > 0) { subwayStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, subwayStationsLayout, false)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_subway_station_item, subwayStationsLayout, false); view.setTag(getSubwayStationViewTag(subwayStation)); // subway station name ((TextView) view.findViewById(R.id.station_name)).setText(subwayStation.getName()); // station lines color if (otherLinesId != null && otherLinesId.size() > 0) { int subwayLineImg1 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(0).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_1)).setImageResource(subwayLineImg1); if (otherLinesId.size() > 1) { int subwayLineImg2 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(1).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_2)).setImageResource(subwayLineImg2); if (otherLinesId.size() > 2) { int subwayLineImg3 = SubwayUtils.getSubwayLineImgId(otherLinesId.get(2).getNumber()); ((ImageView) view.findViewById(R.id.subway_img_3)).setImageResource(subwayLineImg3); } else { view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } } else { view.findViewById(R.id.subway_img_1).setVisibility(View.GONE); view.findViewById(R.id.subway_img_2).setVisibility(View.GONE); view.findViewById(R.id.subway_img_3).setVisibility(View.GONE); } // subway station distance TextView distanceTv = (TextView) view.findViewById(R.id.distance); distanceTv.setVisibility(View.GONE); distanceTv.setText(null); // compass view.findViewById(R.id.compass).setVisibility(View.GONE); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, subwayStation.getId()); intent.putExtra(SubwayStationInfo.EXTRA_STATION_NAME, subwayStation.getName()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); final View theViewToDelete = v; new AlertDialog.Builder(FavListTab.this) .setTitle(getString(R.string.subway_station_with_name_short, subwayStation.getName())) .setItems(new CharSequence[] { getString(R.string.view_subway_station), getString(R.string.remove_fav) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case 0: Intent intent = new Intent(FavListTab.this, SubwayStationInfo.class); intent.putExtra(SubwayStationInfo.EXTRA_STATION_ID, subwayStation.getId()); intent.putExtra(SubwayStationInfo.EXTRA_STATION_NAME, subwayStation.getName()); startActivity(intent); break; case 1: // remove the view from the UI ((LinearLayout) findViewById(R.id.subway_stations_list)).removeView(theViewToDelete); // remove the favorite from the current list Iterator<Fav> it = FavListTab.this.currentSubwayStationFavList.iterator(); while (it.hasNext()) { DataStore.Fav fav = (DataStore.Fav) it.next(); if (fav.getFkId().equals(subwayStation.getId())) { it.remove(); break; } } // refresh empty showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); // delete the favorite Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_SUBWAY_STATION, subwayStation.getId(), null); // delete the favorite if (findFav != null) { DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); } SupportFactory.getInstance(FavListTab.this).backupManagerDataChanged(); break; default: break; } } }).create().show(); return true; } }); this.subwayStations.add(new ASubwayStation(subwayStation)); subwayStationsLayout.addView(view); } else { MyLog.w(TAG, "Can't find the favorite subway station (ID:%s)", subwayFav.getFkId()); } } } } private String getSubwayStationViewTag(SubwayStation subwayStation) { return "subwayStation" + subwayStation.getId(); } /** * Refresh bike station UI. * @param newBikeFavList the new favorite bike stations list * @param bikeStations the new favorite bike stations */ private void refreshBikeStationsUI(List<DataStore.Fav> newBikeFavList, Map<String, BikeStation> bikeStations) { // MyLog.v(TAG, "refreshBikeStationsUI(%s,%s)", Utils.getCollectionSize(newBikeFavList), Utils.getMapSize(bikeStations)); if (this.currentBikeStationFavList == null || this.currentBikeStationFavList.size() != newBikeFavList.size()) { LinearLayout bikeStationsLayout = (LinearLayout) findViewById(R.id.bike_stations_list); // remove all bike station views bikeStationsLayout.removeAllViews(); // use new favorite bike station this.currentBikeStationFavList = newBikeFavList; this.bikeStations = new ArrayList<ABikeStation>(); findViewById(R.id.lists).setVisibility(View.VISIBLE); findViewById(R.id.fav_bike_stations).setVisibility(View.VISIBLE); bikeStationsLayout.setVisibility(View.VISIBLE); // FOR EACH favorite bike DO if (bikeStations != null) { for (final BikeStation bikeStation : bikeStations.values()) { // list view divider if (bikeStationsLayout.getChildCount() > 0) { bikeStationsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, bikeStationsLayout, false)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_bike_station_item, bikeStationsLayout, false); view.setTag(getBikeStationViewTag(bikeStation)); // subway station name ((TextView) view.findViewById(R.id.station_name)).setText(Utils.cleanBikeStationName(bikeStation.getName())); // bike station distance TextView distanceTv = (TextView) view.findViewById(R.id.distance); distanceTv.setVisibility(View.GONE); distanceTv.setText(null); // compass view.findViewById(R.id.compass).setVisibility(View.GONE); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, BikeStationInfo.class); intent.putExtra(BikeStationInfo.EXTRA_STATION_TERMINAL_NAME, bikeStation.getTerminalName()); intent.putExtra(BikeStationInfo.EXTRA_STATION_NAME, bikeStation.getName()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); final View theViewToDelete = v; new AlertDialog.Builder(FavListTab.this) .setTitle(bikeStation.getName()) .setItems(new CharSequence[] { getString(R.string.view_bike_station), getString(R.string.remove_fav) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case 0: Intent intent = new Intent(FavListTab.this, BikeStationInfo.class); intent.putExtra(BikeStationInfo.EXTRA_STATION_TERMINAL_NAME, bikeStation.getTerminalName()); intent.putExtra(BikeStationInfo.EXTRA_STATION_NAME, bikeStation.getName()); startActivity(intent); break; case 1: // remove the view from the UI ((LinearLayout) findViewById(R.id.bike_stations_list)).removeView(theViewToDelete); // remove the favorite from the current list Iterator<Fav> it = FavListTab.this.currentBikeStationFavList.iterator(); while (it.hasNext()) { DataStore.Fav fav = (DataStore.Fav) it.next(); if (fav.getFkId().equals(bikeStation.getTerminalName())) { it.remove(); break; } } // refresh empty showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); // delete the favorite Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BIKE_STATIONS, bikeStation.getTerminalName(), null); // delete the favorite if (findFav != null) { DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); } SupportFactory.getInstance(FavListTab.this).backupManagerDataChanged(); break; default: break; } } }).create().show(); return true; } }); this.bikeStations.add(new ABikeStation(bikeStation)); bikeStationsLayout.addView(view); } } } } private String getBikeStationViewTag(BikeStation bikeStation) { return "bikeStation" + bikeStation.getTerminalName(); } /** * Update the distance with the latest device location. */ private void updateDistancesWithNewLocation() { Location currentLocation = getLocation(); MyLog.v(TAG, "updateDistancesWithNewLocation(%s)", currentLocation); if (currentLocation == null) { return; } boolean isDetailed = UserPreferences.getPrefDefault(this, UserPreferences.PREFS_DISTANCE, UserPreferences.PREFS_DISTANCE_DEFAULT).equals( UserPreferences.PREFS_DISTANCE_DETAILED); String distanceUnit = UserPreferences.getPrefDefault(this, UserPreferences.PREFS_DISTANCE_UNIT, UserPreferences.PREFS_DISTANCE_UNIT_DEFAULT); float accuracyInMeters = currentLocation.getAccuracy(); // update bus stops if (this.busStops != null) { View busStopsLayout = findViewById(R.id.bus_stops_list); for (ABusStop busStop : this.busStops) { if (busStop.getLocation() == null) { continue; } // update value busStop.setDistance(currentLocation.distanceTo(busStop.getLocation())); busStop.setDistanceString(Utils.getDistanceString(busStop.getDistance(), accuracyInMeters, isDetailed, distanceUnit)); // update view View stopView = busStopsLayout.findViewWithTag(getBusStopViewTag(busStop)); if (stopView != null && !TextUtils.isEmpty(busStop.getDistanceString())) { TextView distanceTv = (TextView) stopView.findViewById(R.id.distance); distanceTv.setText(busStop.getDistanceString()); distanceTv.setVisibility(View.VISIBLE); } } } // update subway stations if (this.subwayStations != null) { View subwayStationsLayout = findViewById(R.id.subway_stations_list); for (ASubwayStation subwayStation : this.subwayStations) { // update value subwayStation.setDistance(currentLocation.distanceTo(subwayStation.getLocation())); subwayStation.setDistanceString(Utils.getDistanceString(subwayStation.getDistance(), accuracyInMeters, isDetailed, distanceUnit)); // update view View stationView = subwayStationsLayout.findViewWithTag(getSubwayStationViewTag(subwayStation)); if (stationView != null && !TextUtils.isEmpty(subwayStation.getDistanceString())) { TextView distanceTv = (TextView) stationView.findViewById(R.id.distance); distanceTv.setText(subwayStation.getDistanceString()); distanceTv.setVisibility(View.VISIBLE); } } } // update bike stations if (this.bikeStations != null) { View bikeStationsLayout = findViewById(R.id.bike_stations_list); for (ABikeStation bikeStation : this.bikeStations) { // update value bikeStation.setDistance(currentLocation.distanceTo(bikeStation.getLocation())); bikeStation.setDistanceString(Utils.getDistanceString(bikeStation.getDistance(), accuracyInMeters, isDetailed, distanceUnit)); // update view View stationView = bikeStationsLayout.findViewWithTag(getBikeStationViewTag(bikeStation)); if (stationView != null && !TextUtils.isEmpty(bikeStation.getDistanceString())) { TextView distanceTv = (TextView) stationView.findViewById(R.id.distance); distanceTv.setText(bikeStation.getDistanceString()); distanceTv.setVisibility(View.VISIBLE); } } } } /** * @param newLocation the new location */ private void setLocation(Location newLocation) { if (newLocation != null) { // MyLog.d(TAG, "new location: %s.", LocationUtils.locationToString(newLocation)); if (this.location == null || LocationUtils.isMoreRelevant(this.location, newLocation)) { this.location = newLocation; SensorUtils.registerCompassListener(this, this); } } } /** * @return the location */ public Location getLocation() { if (this.location == null) { new AsyncTask<Void, Void, Location>() { @Override protected Location doInBackground(Void... params) { // MyLog.v(TAG, "doInBackground()"); return LocationUtils.getBestLastKnownLocation(FavListTab.this); } @Override protected void onPostExecute(Location result) { // MyLog.v(TAG, "onPostExecute()"); if (result != null) { FavListTab.this.setLocation(result); } // enable location updates if necessary if (!FavListTab.this.locationUpdatesEnabled) { LocationUtils.enableLocationUpdates(FavListTab.this, FavListTab.this); FavListTab.this.locationUpdatesEnabled = true; } } }.execute(); } return this.location; } @Override public void onLocationChanged(Location location) { MyLog.v(TAG, "onLocationChanged()"); this.setLocation(location); updateDistancesWithNewLocation(); } @Override public void onProviderEnabled(String provider) { MyLog.v(TAG, "onProviderEnabled(%s)", provider); } @Override public void onProviderDisabled(String provider) { MyLog.v(TAG, "onProviderDisabled(%s)", provider); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { MyLog.v(TAG, "onStatusChanged(%s, %s)", provider, status); } @Override public boolean onCreateOptionsMenu(Menu menu) { return MenuUtils.createMainMenu(this, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.handleCommonMenuActions(this, item); } }
true
true
private void refreshBusStopsUI(List<DataStore.Fav> newBusStopFavList, List<BusStop> busStopsExtendedList) { // MyLog.v(TAG, "refreshBusStopsUI(%s,%s)", Utils.getCollectionSize(newBusStopFavList), Utils.getCollectionSize(busStopsExtendedList)); if (this.currentBusStopFavList == null || this.currentBusStopFavList.size() != newBusStopFavList.size()) { // remove all favorite bus stop views LinearLayout busStopsLayout = (LinearLayout) findViewById(R.id.bus_stops_list); busStopsLayout.removeAllViews(); // use new favorite bus stops this.currentBusStopFavList = newBusStopFavList; this.busStops = new ArrayList<ABusStop>(); findViewById(R.id.lists).setVisibility(View.VISIBLE); findViewById(R.id.fav_bus_stops).setVisibility(View.VISIBLE); busStopsLayout.setVisibility(View.VISIBLE); // FOR EACH bus stop DO if (this.busStops != null) { for (final BusStop busStop : busStopsExtendedList) { // list view divider if (busStopsLayout.getChildCount() > 0) { busStopsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, busStopsLayout, false)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_bus_stop_item, busStopsLayout, false); view.setTag(getBusStopViewTag(busStop)); // bus stop code ((TextView) view.findViewById(R.id.stop_code)).setText(busStop.getCode()); // bus stop place String busStopPlace = BusUtils.cleanBusStopPlace(busStop.getPlace()); ((TextView) view.findViewById(R.id.label)).setText(busStopPlace); // bus stop line number TextView lineNumberTv = (TextView) view.findViewById(R.id.line_number); lineNumberTv.setText(busStop.getLineNumber()); int color = BusUtils.getBusLineTypeBgColor(busStop.getLineTypeOrNull(), busStop.getLineNumber()); lineNumberTv.setBackgroundColor(color); // bus stop line direction int busLineDirection = BusUtils.getBusLineSimpleDirection(busStop.getDirectionId()); ((TextView) view.findViewById(R.id.line_direction)).setText(getString(busLineDirection).toUpperCase(Locale.getDefault())); // bus station distance TextView distanceTv = (TextView) view.findViewById(R.id.distance); distanceTv.setVisibility(View.GONE); distanceTv.setText(null); // compass view.findViewById(R.id.compass).setVisibility(View.GONE); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); final View theViewToDelete = v; new AlertDialog.Builder(FavListTab.this) .setTitle(getString(R.string.bus_stop_and_line_short, busStop.getCode(), busStop.getLineNumber())) .setItems( new CharSequence[] { getString(R.string.view_bus_stop), getString(R.string.view_bus_stop_line), getString(R.string.remove_fav) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case 0: Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); break; case 1: Intent intent2 = new Intent(FavListTab.this, SupportFactory.getInstance(FavListTab.this) .getBusLineInfoClass()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NUMBER, busStop.getLineNumber()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NAME, busStop.getLineNameOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_TYPE, busStop.getLineTypeOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_DIRECTION_ID, busStop.getDirectionId()); startActivity(intent2); break; case 2: // remove the view from the UI ((LinearLayout) findViewById(R.id.bus_stops_list)).removeView(theViewToDelete); // remove the favorite from the current list Iterator<Fav> it = FavListTab.this.currentBusStopFavList.iterator(); while (it.hasNext()) { DataStore.Fav fav = (DataStore.Fav) it.next(); if (fav.getFkId().equals(busStop.getCode()) && fav.getFkId2().equals(busStop.getLineNumber())) { it.remove(); break; } } // refresh empty showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP, busStop.getCode(), busStop.getLineNumber()); // delete the favorite if (findFav != null) { DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); } SupportFactory.getInstance(FavListTab.this).backupManagerDataChanged(); break; default: break; } } }).create().show(); return true; } }); this.busStops.add(new ABusStop(busStop)); busStopsLayout.addView(view); } } } }
private void refreshBusStopsUI(List<DataStore.Fav> newBusStopFavList, List<BusStop> busStopsExtendedList) { // MyLog.v(TAG, "refreshBusStopsUI(%s,%s)", Utils.getCollectionSize(newBusStopFavList), Utils.getCollectionSize(busStopsExtendedList)); if (this.currentBusStopFavList == null || this.currentBusStopFavList.size() != newBusStopFavList.size()) { // remove all favorite bus stop views LinearLayout busStopsLayout = (LinearLayout) findViewById(R.id.bus_stops_list); busStopsLayout.removeAllViews(); // use new favorite bus stops this.currentBusStopFavList = newBusStopFavList; this.busStops = new ArrayList<ABusStop>(); findViewById(R.id.lists).setVisibility(View.VISIBLE); findViewById(R.id.fav_bus_stops).setVisibility(View.VISIBLE); busStopsLayout.setVisibility(View.VISIBLE); // FOR EACH bus stop DO if (busStopsExtendedList != null) { for (final BusStop busStop : busStopsExtendedList) { // list view divider if (busStopsLayout.getChildCount() > 0) { busStopsLayout.addView(getLayoutInflater().inflate(R.layout.list_view_divider, busStopsLayout, false)); } // create view View view = getLayoutInflater().inflate(R.layout.fav_list_tab_bus_stop_item, busStopsLayout, false); view.setTag(getBusStopViewTag(busStop)); // bus stop code ((TextView) view.findViewById(R.id.stop_code)).setText(busStop.getCode()); // bus stop place String busStopPlace = BusUtils.cleanBusStopPlace(busStop.getPlace()); ((TextView) view.findViewById(R.id.label)).setText(busStopPlace); // bus stop line number TextView lineNumberTv = (TextView) view.findViewById(R.id.line_number); lineNumberTv.setText(busStop.getLineNumber()); int color = BusUtils.getBusLineTypeBgColor(busStop.getLineTypeOrNull(), busStop.getLineNumber()); lineNumberTv.setBackgroundColor(color); // bus stop line direction int busLineDirection = BusUtils.getBusLineSimpleDirection(busStop.getDirectionId()); ((TextView) view.findViewById(R.id.line_direction)).setText(getString(busLineDirection).toUpperCase(Locale.getDefault())); // bus station distance TextView distanceTv = (TextView) view.findViewById(R.id.distance); distanceTv.setVisibility(View.GONE); distanceTv.setText(null); // compass view.findViewById(R.id.compass).setVisibility(View.GONE); // add click listener view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyLog.v(TAG, "onClick(%s)", v.getId()); Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); } }); // add context menu view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { MyLog.v(TAG, "onLongClick(%s)", v.getId()); final View theViewToDelete = v; new AlertDialog.Builder(FavListTab.this) .setTitle(getString(R.string.bus_stop_and_line_short, busStop.getCode(), busStop.getLineNumber())) .setItems( new CharSequence[] { getString(R.string.view_bus_stop), getString(R.string.view_bus_stop_line), getString(R.string.remove_fav) }, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { MyLog.v(TAG, "onClick(%s)", item); switch (item) { case 0: Intent intent = new Intent(FavListTab.this, BusStopInfo.class); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NUMBER, busStop.getLineNumber()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_NAME, busStop.getLineNameOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_LINE_TYPE, busStop.getLineTypeOrNull()); intent.putExtra(BusStopInfo.EXTRA_STOP_CODE, busStop.getCode()); intent.putExtra(BusStopInfo.EXTRA_STOP_PLACE, busStop.getPlace()); startActivity(intent); break; case 1: Intent intent2 = new Intent(FavListTab.this, SupportFactory.getInstance(FavListTab.this) .getBusLineInfoClass()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NUMBER, busStop.getLineNumber()); intent2.putExtra(BusLineInfo.EXTRA_LINE_NAME, busStop.getLineNameOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_TYPE, busStop.getLineTypeOrNull()); intent2.putExtra(BusLineInfo.EXTRA_LINE_DIRECTION_ID, busStop.getDirectionId()); startActivity(intent2); break; case 2: // remove the view from the UI ((LinearLayout) findViewById(R.id.bus_stops_list)).removeView(theViewToDelete); // remove the favorite from the current list Iterator<Fav> it = FavListTab.this.currentBusStopFavList.iterator(); while (it.hasNext()) { DataStore.Fav fav = (DataStore.Fav) it.next(); if (fav.getFkId().equals(busStop.getCode()) && fav.getFkId2().equals(busStop.getLineNumber())) { it.remove(); break; } } // refresh empty showEmptyFav(); UserPreferences.savePrefLcl(FavListTab.this, UserPreferences.PREFS_LCL_IS_FAV, isThereAtLeastOneFavorite()); // find the favorite to delete Fav findFav = DataManager.findFav(FavListTab.this.getContentResolver(), DataStore.Fav.KEY_TYPE_VALUE_BUS_STOP, busStop.getCode(), busStop.getLineNumber()); // delete the favorite if (findFav != null) { DataManager.deleteFav(FavListTab.this.getContentResolver(), findFav.getId()); } SupportFactory.getInstance(FavListTab.this).backupManagerDataChanged(); break; default: break; } } }).create().show(); return true; } }); this.busStops.add(new ABusStop(busStop)); busStopsLayout.addView(view); } } } }
diff --git a/src/mods/themike/modjam/items/ItemStaff.java b/src/mods/themike/modjam/items/ItemStaff.java index 56c1301..f01d973 100644 --- a/src/mods/themike/modjam/items/ItemStaff.java +++ b/src/mods/themike/modjam/items/ItemStaff.java @@ -1,129 +1,129 @@ package mods.themike.modjam.items; import java.util.List; import java.util.Random; import cpw.mods.fml.common.registry.LanguageRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mods.themike.modjam.ModJam; import mods.themike.modjam.rune.IRune; import mods.themike.modjam.rune.RuneRegistry; import mods.themike.modjam.utils.ColorUtils; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.Icon; import net.minecraft.world.World; public class ItemStaff extends ItemMulti { protected static String[] subNames = new String[]{"apprentice", "mage"}; private static Icon[] subIcons = new Icon[subNames.length]; public ItemStaff(int par1) { super(par1); this.hasSubtypes = true; this.setUnlocalizedName("itemStaff"); this.setCreativeTab(ModJam.tab); } @Override public Icon getIconFromDamage(int metadata) { return subIcons[metadata]; } @Override @SideOnly(Side.CLIENT) public void updateIcons(IconRegister reg) { for(int par1 = 0; par1 < subNames.length; par1++) { subIcons[par1] = reg.registerIcon("mikejam:staff" + subNames[par1]); } } @Override public void getSubItems(int ID, CreativeTabs tabs, List list) { for(int par1 = 0; par1 < subNames.length; par1++) { ItemStack stack = new ItemStack(ID, 1, par1); stack.setTagCompound(new NBTTagCompound()); list.add(stack); } } @Override public String getUnlocalizedName(ItemStack stack) { if(stack.getItemDamage() >= 0 && stack.getItemDamage() < subNames.length) { return "staff." + subNames[stack.getItemDamage()]; } return null; } @Override public boolean hasEffect(ItemStack stack) { if(stack.getItemDamage() == 1) { return true; } return false; } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean par4) { if(stack.getItemDamage() == 0) { list.add("Can bind up to Level 25."); } else { list.add("Can bind all levels."); } if(stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); if(stack.getTagCompound().getTag("item") != null && runeStack != null) { list.add(ColorUtils.applyColor(14) + LanguageRegistry.instance().getStringLocalization("rune." + RuneRegistry.getrunes()[runeStack.getItemDamage()].getName() + ".name") + "."); } } } @Override public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { super.onItemRightClick(stack, world, player); ItemStack newStack = stack.copy(); - if(!world.isRemote && !player.isSneaking() && stack.getTagCompound() != null) { + if(!world.isRemote && !player.isSneaking() && stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); - if(runeStack != null && player.experience >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17) { + if(runeStack != null && player.experienceLevel >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()) { System.out.println("Hello Runes!"); IRune rune = RuneRegistry.getrunes()[runeStack.getItemDamage()]; - player.experience = player.experience - (RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17); + player.addExperienceLevel(- RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()); rune.onUse(player); int uses = runeStack.getTagCompound().getInteger("uses"); if(uses == 1) { NBTTagCompound tag = new NBTTagCompound(); newStack.getTagCompound().setTag("item", tag); } else { runeStack.getTagCompound().setInteger("uses", uses - 1); NBTTagCompound tag = new NBTTagCompound(); runeStack.writeToNBT(tag); newStack.getTagCompound().setTag("item", tag); } } else if(runeStack != null) { player.sendChatToPlayer(ColorUtils.applyColor(14) + "Not enough XP to use this rune!"); } } if(world.isRemote && !player.isSneaking() && stack.getTagCompound() != null) { if(stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); - if(runeStack != null && player.experience >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17) { + if(runeStack != null && player.experienceLevel >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()) { player.playSound("mods.mikejam.sounds.sucess", 1.0F, 1.0F); } else if(runeStack != null) { player.playSound("mods.mikejam.sounds.failure", 1.0F, 1.0F); } } } if(player.isSneaking()) { player.openGui(ModJam.instance, 1, world, (int) player.posX, (int) player.posY, (int) player.posZ); } return newStack; } }
false
true
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { super.onItemRightClick(stack, world, player); ItemStack newStack = stack.copy(); if(!world.isRemote && !player.isSneaking() && stack.getTagCompound() != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); if(runeStack != null && player.experience >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17) { System.out.println("Hello Runes!"); IRune rune = RuneRegistry.getrunes()[runeStack.getItemDamage()]; player.experience = player.experience - (RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17); rune.onUse(player); int uses = runeStack.getTagCompound().getInteger("uses"); if(uses == 1) { NBTTagCompound tag = new NBTTagCompound(); newStack.getTagCompound().setTag("item", tag); } else { runeStack.getTagCompound().setInteger("uses", uses - 1); NBTTagCompound tag = new NBTTagCompound(); runeStack.writeToNBT(tag); newStack.getTagCompound().setTag("item", tag); } } else if(runeStack != null) { player.sendChatToPlayer(ColorUtils.applyColor(14) + "Not enough XP to use this rune!"); } } if(world.isRemote && !player.isSneaking() && stack.getTagCompound() != null) { if(stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); if(runeStack != null && player.experience >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel() * 17) { player.playSound("mods.mikejam.sounds.sucess", 1.0F, 1.0F); } else if(runeStack != null) { player.playSound("mods.mikejam.sounds.failure", 1.0F, 1.0F); } } } if(player.isSneaking()) { player.openGui(ModJam.instance, 1, world, (int) player.posX, (int) player.posY, (int) player.posZ); } return newStack; }
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { super.onItemRightClick(stack, world, player); ItemStack newStack = stack.copy(); if(!world.isRemote && !player.isSneaking() && stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); if(runeStack != null && player.experienceLevel >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()) { System.out.println("Hello Runes!"); IRune rune = RuneRegistry.getrunes()[runeStack.getItemDamage()]; player.addExperienceLevel(- RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()); rune.onUse(player); int uses = runeStack.getTagCompound().getInteger("uses"); if(uses == 1) { NBTTagCompound tag = new NBTTagCompound(); newStack.getTagCompound().setTag("item", tag); } else { runeStack.getTagCompound().setInteger("uses", uses - 1); NBTTagCompound tag = new NBTTagCompound(); runeStack.writeToNBT(tag); newStack.getTagCompound().setTag("item", tag); } } else if(runeStack != null) { player.sendChatToPlayer(ColorUtils.applyColor(14) + "Not enough XP to use this rune!"); } } if(world.isRemote && !player.isSneaking() && stack.getTagCompound() != null) { if(stack.getTagCompound().getTag("item") != null) { ItemStack runeStack = ItemStack.loadItemStackFromNBT((NBTTagCompound) stack.getTagCompound().getTag("item")); if(runeStack != null && player.experienceLevel >= RuneRegistry.getrunes()[runeStack.getItemDamage()].getLevel()) { player.playSound("mods.mikejam.sounds.sucess", 1.0F, 1.0F); } else if(runeStack != null) { player.playSound("mods.mikejam.sounds.failure", 1.0F, 1.0F); } } } if(player.isSneaking()) { player.openGui(ModJam.instance, 1, world, (int) player.posX, (int) player.posY, (int) player.posZ); } return newStack; }
diff --git a/plugins/org.chromium.sdk.tests/src/org/chromium/sdk/internal/protocol/TestProtocolParser.java b/plugins/org.chromium.sdk.tests/src/org/chromium/sdk/internal/protocol/TestProtocolParser.java index 490f7864..4b741a24 100644 --- a/plugins/org.chromium.sdk.tests/src/org/chromium/sdk/internal/protocol/TestProtocolParser.java +++ b/plugins/org.chromium.sdk.tests/src/org/chromium/sdk/internal/protocol/TestProtocolParser.java @@ -1,79 +1,79 @@ package org.chromium.sdk.internal.protocol; import java.util.List; import org.chromium.sdk.internal.JsonUtil; import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException; import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting; import org.chromium.sdk.internal.protocolparser.JsonType; import org.chromium.sdk.internal.protocolparser.dynamicimpl.JsonProtocolParser; import org.chromium.sdk.internal.tools.v8.V8ProtocolUtil; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; import org.junit.Before; import org.junit.Test; public class TestProtocolParser { private JsonProtocolParser testParser; @Before public void setUpBefore() throws Exception { testParser = new JsonProtocolParser(SimpleData.class, Cases.class); } @Test public void test1() throws JsonProtocolParseException, ParseException { // JsonProtocolParser parser = new JsonProtocolParser(Arrays.asList(CommandResponse.class)); - String sample = "{'seq':0,'request_seq':1,'type':'response','command':'version'," + - "'success':true,'body':{'V8Version':'1.3.19 (candidate)'},'refs':[],'running':true}" + String sample = ("{'seq':0,'request_seq':1,'type':'response','command':'version'," + + "'success':true,'body':{'V8Version':'1.3.19 (candidate)'},'refs':[],'running':true}") .replace('\'', '"'); JSONObject json = JsonUtil.jsonObjectFromJson(sample); JsonProtocolParser parser = V8ProtocolUtil.getV8Parser(); IncomingMessage response = parser.parse(json, IncomingMessage.class); Long l1 = response.getSeq(); MessageType type = response.getType(); CommandResponse commandResponse = response.asCommandResponse(); Long l2 = commandResponse.getRequestSeq(); boolean success = commandResponse.success(); SuccessCommandResponse successResponse = commandResponse.asSuccess(); Boolean running = successResponse.running(); Object body = successResponse.getBody(); List<?> refs = successResponse.getRefs(); SuccessCommandResponse successResponse2 = parser.parse(json, SuccessCommandResponse.class); response = null; } @Test public void testTypeOverArray() throws JsonProtocolParseException, ParseException { // JsonProtocolParser parser = new JsonProtocolParser(Arrays.asList(CommandResponse.class)); String sample = "{'a': [1, 2, 3]}".replace('\'', '"'); JSONObject json = JsonUtil.jsonObjectFromJson(sample); SimpleData simpleData = testParser.parse(json, SimpleData.class); Cases cases = simpleData.getA(); List<Object> array = cases.asList(); array = null; } @Test public void testTypeOverNumber() throws JsonProtocolParseException, ParseException { // JsonProtocolParser parser = new JsonProtocolParser(Arrays.asList(CommandResponse.class)); String sample = "{'a': 1}".replace('\'', '"'); JSONObject json = JsonUtil.jsonObjectFromJson(sample); SimpleData simpleData = testParser.parse(json, SimpleData.class); Cases cases = simpleData.getA(); long num = cases.asNumber(); num = 0; } @JsonType interface SimpleData { Cases getA(); } @JsonType(subtypesChosenManually=true) interface Cases { @JsonSubtypeCasting List<Object> asList() throws JsonProtocolParseException; @JsonSubtypeCasting long asNumber() throws JsonProtocolParseException; } }
true
true
public void test1() throws JsonProtocolParseException, ParseException { // JsonProtocolParser parser = new JsonProtocolParser(Arrays.asList(CommandResponse.class)); String sample = "{'seq':0,'request_seq':1,'type':'response','command':'version'," + "'success':true,'body':{'V8Version':'1.3.19 (candidate)'},'refs':[],'running':true}" .replace('\'', '"'); JSONObject json = JsonUtil.jsonObjectFromJson(sample); JsonProtocolParser parser = V8ProtocolUtil.getV8Parser(); IncomingMessage response = parser.parse(json, IncomingMessage.class); Long l1 = response.getSeq(); MessageType type = response.getType(); CommandResponse commandResponse = response.asCommandResponse(); Long l2 = commandResponse.getRequestSeq(); boolean success = commandResponse.success(); SuccessCommandResponse successResponse = commandResponse.asSuccess(); Boolean running = successResponse.running(); Object body = successResponse.getBody(); List<?> refs = successResponse.getRefs(); SuccessCommandResponse successResponse2 = parser.parse(json, SuccessCommandResponse.class); response = null; }
public void test1() throws JsonProtocolParseException, ParseException { // JsonProtocolParser parser = new JsonProtocolParser(Arrays.asList(CommandResponse.class)); String sample = ("{'seq':0,'request_seq':1,'type':'response','command':'version'," + "'success':true,'body':{'V8Version':'1.3.19 (candidate)'},'refs':[],'running':true}") .replace('\'', '"'); JSONObject json = JsonUtil.jsonObjectFromJson(sample); JsonProtocolParser parser = V8ProtocolUtil.getV8Parser(); IncomingMessage response = parser.parse(json, IncomingMessage.class); Long l1 = response.getSeq(); MessageType type = response.getType(); CommandResponse commandResponse = response.asCommandResponse(); Long l2 = commandResponse.getRequestSeq(); boolean success = commandResponse.success(); SuccessCommandResponse successResponse = commandResponse.asSuccess(); Boolean running = successResponse.running(); Object body = successResponse.getBody(); List<?> refs = successResponse.getRefs(); SuccessCommandResponse successResponse2 = parser.parse(json, SuccessCommandResponse.class); response = null; }
diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index 3c0a35bb..10cdbb51 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -1,675 +1,675 @@ /* * Essentials - a bukkit plugin * Copyright (C) 2011 Essentials Team * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earth2me.essentials; import com.earth2me.essentials.commands.EssentialsCommand; import java.io.*; import java.util.*; import java.util.logging.*; import org.bukkit.*; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.NotEnoughArgumentsException; import com.earth2me.essentials.register.payment.Methods; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.craftbukkit.scheduler.CraftScheduler; import org.bukkit.entity.Player; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.event.server.ServerListener; import org.bukkit.plugin.*; import org.bukkit.plugin.java.*; public class Essentials extends JavaPlugin { public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo, ceulemans and Xeology"; public static final int minBukkitBuildVersion = 812; private static final Logger logger = Logger.getLogger("Minecraft"); private Settings settings; private EssentialsPlayerListener playerListener; private EssentialsBlockListener blockListener; private EssentialsEntityListener entityListener; private JailPlayerListener jailPlayerListener; private static Essentials instance = null; private Spawn spawn; private Jail jail; private Warps warps; private Worth worth; private List<IConf> confList; public ArrayList bans = new ArrayList(); public ArrayList bannedIps = new ArrayList(); private Backup backup; private Map<String, User> users = new HashMap<String, User>(); private EssentialsTimer timer; private boolean registerFallback = true; private Methods paymentMethod = new Methods(); public Essentials() { } public static Essentials getStatic() { return instance; } public Settings getSettings() { return settings; } public void setupForTesting(Server server) throws IOException, InvalidDescriptionException { File dataFolder = File.createTempFile("essentialstest", ""); dataFolder.delete(); dataFolder.mkdir(); logger.log(Level.INFO, Util.i18n("usingTempFolderForTesting")); logger.log(Level.INFO, dataFolder.toString()); this.initialize(null, server, new PluginDescriptionFile(new FileReader(new File("src" + File.separator + "plugin.yml"))), dataFolder, null, null); settings = new Settings(dataFolder); setStatic(); } public void setStatic() { instance = this; } public void onEnable() { setStatic(); EssentialsUpgrade upgrade = new EssentialsUpgrade(this.getDescription().getVersion(), this); upgrade.beforeSettings(); confList = new ArrayList<IConf>(); settings = new Settings(this.getDataFolder()); confList.add(settings); upgrade.afterSettings(); Util.updateLocale(settings.getLocale(), this.getDataFolder()); spawn = new Spawn(getServer(), this.getDataFolder()); confList.add(spawn); warps = new Warps(getServer(), this.getDataFolder()); confList.add(warps); worth = new Worth(this.getDataFolder()); confList.add(worth); reload(); backup = new Backup(); PluginManager pm = getServer().getPluginManager(); for (Plugin plugin : pm.getPlugins()) { if (plugin.getDescription().getName().startsWith("Essentials")) { if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) { logger.log(Level.WARNING, Util.format("versionMismatch", plugin.getDescription().getName())); } } } Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion()); if (versionMatch.matches()) { int versionNumber = Integer.parseInt(versionMatch.group(4)); if (versionNumber < minBukkitBuildVersion) { logger.log(Level.WARNING, Util.i18n("notRecommendedBukkit")); } } else { logger.log(Level.INFO, Util.i18n("bukkitFormatChanged")); } ServerListener serverListener = new EssentialsPluginListener(paymentMethod); pm.registerEvent(Type.PLUGIN_ENABLE, serverListener, Priority.Low, this); pm.registerEvent(Type.PLUGIN_DISABLE, serverListener, Priority.Low, this); playerListener = new EssentialsPlayerListener(this); pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this); pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this); pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Lowest, this); if (getSettings().getNetherPortalsEnabled()) { pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this); } pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_EGG_THROW, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_BUCKET_EMPTY, playerListener, Priority.High, this); pm.registerEvent(Type.PLAYER_ANIMATION, playerListener, Priority.High, this); blockListener = new EssentialsBlockListener(this); pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Low, this); pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Lowest, this); pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Lowest, this); entityListener = new EssentialsEntityListener(this); pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this); pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); jail = new Jail(this); jailPlayerListener = new JailPlayerListener(this); confList.add(jail); pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this); pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.High, this); pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.High, this); pm.registerEvent(Type.PLAYER_INTERACT, jailPlayerListener, Priority.High, this); attachEcoListeners(); if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2) { getServer().createWorld(settings.getNetherName(), World.Environment.NETHER); } timer = new EssentialsTimer(this); getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 50); logger.info(Util.format("loadinfo", this.getDescription().getName(), this.getDescription().getVersion(), AUTHORS)); } public void onDisable() { instance = null; } public void reload() { loadBanList(); for (IConf iConf : confList) { iConf.reloadConfig(); } Util.updateLocale(settings.getLocale(), this.getDataFolder()); for (User user : users.values()) { user.reloadConfig(); } // for motd getConfiguration().load(); try { ItemDb.load(getDataFolder(), "items.csv"); } catch (Exception ex) { logger.log(Level.WARNING, Util.i18n("itemsCsvNotLoaded"), ex); } } public String[] getMotd(CommandSender sender, String def) { return getLines(sender, "motd", def); } public String[] getLines(CommandSender sender, String node, String def) { List<String> lines = (List<String>)getConfiguration().getProperty(node); if (lines == null) { return new String[0]; } String[] retval = new String[lines.size()]; if (lines == null || lines.isEmpty() || lines.get(0) == null) { try { lines = new ArrayList<String>(); // "[]" in YaML indicates empty array, so respect that if (!getConfiguration().getString(node, def).equals("[]")) { lines.add(getConfiguration().getString(node, def)); retval = new String[lines.size()]; } } catch (Throwable ex2) { logger.log(Level.WARNING, Util.format("corruptNodeInConfig", node)); return new String[0]; } } // if still empty, call it a day if (lines == null || lines.isEmpty() || lines.get(0) == null) { return new String[0]; } for (int i = 0; i < lines.size(); i++) { String m = lines.get(i); if (m == null) { continue; } m = m.replace('&', '§').replace("§§", "&"); if (sender instanceof User || sender instanceof Player) { User user = getUser(sender); m = m.replace("{PLAYER}", user.getDisplayName()); m = m.replace("{IP}", user.getAddress().toString()); m = m.replace("{BALANCE}", Double.toString(user.getMoney())); m = m.replace("{MAILS}", Integer.toString(user.getMails().size())); } m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length)); if (m.matches(".*\\{PLAYERLIST\\}.*")) { StringBuilder online = new StringBuilder(); for (Player p : getServer().getOnlinePlayers()) { if (online.length() > 0) { online.append(", "); } online.append(p.getDisplayName()); } m = m.replace("{PLAYERLIST}", online.toString()); } if (sender instanceof Player) { try { Class User = getClassLoader().loadClass("bukkit.Vandolis.User"); Object vuser = User.getConstructor(User.class).newInstance((Player)sender); m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString()); m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString()); m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString()); } catch (Throwable ex) { m = m.replace("{RED:BALANCE}", "N/A"); m = m.replace("{RED:BUYS}", "N/A"); m = m.replace("{RED:SELLS}", "N/A"); } } retval[i] = m + " "; } return retval; } @SuppressWarnings("LoggerStringConcat") public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args) { if (sender instanceof Player) { logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); } } @Override public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command"); } public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) & sender instanceof CraftPlayer) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { - if (p == this) + if (p.getDescription().getMain().contains("com.earth2me.essentials")) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { List<String> mail = user.getMails(); if (mail != null) { if (mail.size() > 0) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (getSettings().isDebug()) { logger.log(Level.WARNING, Util.format("errorCallingCommand", commandLabel), ex); } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } } public void loadBanList() { //I don't like this but it needs to be done until CB fixors File file = new File("banned-players.txt"); File ipFile = new File("banned-ips.txt"); try { if (!file.exists()) { throw new FileNotFoundException(Util.i18n("bannedPlayersFileNotFound")); } BufferedReader rx = new BufferedReader(new FileReader(file)); bans.clear(); try { for (int i = 0; rx.ready(); i++) { String line = rx.readLine().trim().toLowerCase(); if (line.startsWith("#")) { continue; } bans.add(line); } } catch (IOException io) { logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), io); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, Util.i18n("bannedPlayersFileError"), ex); } try { if (!ipFile.exists()) { throw new FileNotFoundException(Util.i18n("bannedIpsFileNotFound")); } BufferedReader rx = new BufferedReader(new FileReader(ipFile)); bannedIps.clear(); try { for (int i = 0; rx.ready(); i++) { String line = rx.readLine().trim().toLowerCase(); if (line.startsWith("#")) { continue; } bannedIps.add(line); } } catch (IOException io) { logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), io); } } catch (FileNotFoundException ex) { logger.log(Level.SEVERE, Util.i18n("bannedIpsFileError"), ex); } } private void attachEcoListeners() { PluginManager pm = getServer().getPluginManager(); EssentialsEcoBlockListener ecoBlockListener = new EssentialsEcoBlockListener(this); EssentialsEcoPlayerListener ecoPlayerListener = new EssentialsEcoPlayerListener(this); pm.registerEvent(Type.PLAYER_INTERACT, ecoPlayerListener, Priority.High, this); pm.registerEvent(Type.BLOCK_BREAK, ecoBlockListener, Priority.High, this); pm.registerEvent(Type.SIGN_CHANGE, ecoBlockListener, Priority.Monitor, this); } public CraftScheduler getScheduler() { return (CraftScheduler)this.getServer().getScheduler(); } public static Jail getJail() { return getStatic().jail; } public static Warps getWarps() { return getStatic().warps; } public static Worth getWorth() { return getStatic().worth; } public static Backup getBackup() { return getStatic().backup; } public static Spawn getSpawn() { return getStatic().spawn; } public <T> User getUser(T base) { if (base instanceof Player) { return getUser((Player)base); } return null; } private <T extends Player> User getUser(T base) { if (base == null) { return null; } if (base instanceof User) { return (User)base; } if (users.containsKey(base.getName().toLowerCase())) { return users.get(base.getName().toLowerCase()).update(base); } User u = new User(base, this); users.put(u.getName().toLowerCase(), u); return u; } public User getOfflineUser(String name) { File userFolder = new File(getDataFolder(), "userdata"); File userFile = new File(userFolder, Util.sanitizeFileName(name) + ".yml"); if (userFile.exists()) { //Users do not get offline changes saved without being reproccessed as Users! ~ Xeology :) return getUser((Player)new OfflinePlayer(name)); } return null; } public World getWorld(String name) { if (name.matches("[0-9]+")) { int id = Integer.parseInt(name); if (id < getServer().getWorlds().size()) { return getServer().getWorlds().get(id); } } World w = getServer().getWorld(name); if (w != null) { return w; } return null; } public void setRegisterFallback(boolean registerFallback) { this.registerFallback = registerFallback; } public boolean isRegisterFallbackEnabled() { return registerFallback; } public void addReloadListener(IConf listener) { confList.add(listener); } public Methods getPaymentMethod() { return paymentMethod; } public int broadcastMessage(String name, String message) { Player[] players = getServer().getOnlinePlayers(); for (Player player : players) { User u = getUser(player); if (!u.isIgnoredPlayer(name)) { player.sendMessage(message); } } return players.length; } }
true
true
public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) & sender instanceof CraftPlayer) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p == this) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { List<String> mail = user.getMails(); if (mail != null) { if (mail.size() > 0) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (getSettings().isDebug()) { logger.log(Level.WARNING, Util.format("errorCallingCommand", commandLabel), ex); } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } }
public boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath) { if ("msg".equals(commandLabel.toLowerCase()) || "r".equals(commandLabel.toLowerCase()) || "mail".equals(commandLabel.toLowerCase()) & sender instanceof CraftPlayer) { StringBuilder str = new StringBuilder(); str.append(commandLabel).append(" "); for (String a : args) { str.append(a).append(" "); } for (Player player : getServer().getOnlinePlayers()) { if (getUser(player).isSocialSpyEnabled()) { player.sendMessage(getUser(sender).getDisplayName() + " : " + str); } } } // Allow plugins to override the command via onCommand if (!getSettings().isCommandOverridden(command.getName()) && !commandLabel.startsWith("e")) { for (Plugin p : getServer().getPluginManager().getPlugins()) { if (p.getDescription().getMain().contains("com.earth2me.essentials")) { continue; } PluginDescriptionFile desc = p.getDescription(); if (desc == null) { continue; } if (desc.getName() == null) { continue; } if (!(desc.getCommands() instanceof Map)) { continue; } Map<String, Object> cmds = (Map<String, Object>)desc.getCommands(); if (!cmds.containsKey(command.getName())) { continue; } return p.onCommand(sender, command, commandLabel, args); } } try { previewCommand(sender, command, commandLabel, args); User user = sender instanceof Player ? getUser(sender) : null; // New mail notification if (user != null && !getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail") && user.isAuthorized("essentials.mail")) { List<String> mail = user.getMails(); if (mail != null) { if (mail.size() > 0) { user.sendMessage(Util.format("youHaveNewMail", mail.size())); } } } // Check for disabled commands if (getSettings().isCommandDisabled(commandLabel)) { return true; } IEssentialsCommand cmd; try { cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); } catch (Exception ex) { sender.sendMessage(Util.format("commandNotLoaded", commandLabel)); logger.log(Level.SEVERE, Util.format("commandNotLoaded", commandLabel), ex); return true; } // Check authorization if (user != null && !user.isAuthorized(cmd)) { logger.log(Level.WARNING, Util.format("deniedAccessCommand", user.getName())); user.sendMessage(Util.i18n("noAccessCommand")); return true; } // Run the command try { if (user == null) { cmd.run(getServer(), sender, commandLabel, command, args); } else { cmd.run(getServer(), user, commandLabel, command, args); } return true; } catch (NotEnoughArgumentsException ex) { sender.sendMessage(command.getDescription()); sender.sendMessage(command.getUsage().replaceAll("<command>", commandLabel)); return true; } catch (Throwable ex) { sender.sendMessage(Util.format("errorWithMessage", ex.getMessage())); if (getSettings().isDebug()) { logger.log(Level.WARNING, Util.format("errorCallingCommand", commandLabel), ex); } return true; } } catch (Throwable ex) { logger.log(Level.SEVERE, Util.format("commandFailed", commandLabel), ex); return true; } }
diff --git a/src/dvrlib/localsearch/GeneticLS.java b/src/dvrlib/localsearch/GeneticLS.java index f93be89..fc0fc03 100644 --- a/src/dvrlib/localsearch/GeneticLS.java +++ b/src/dvrlib/localsearch/GeneticLS.java @@ -1,122 +1,124 @@ /* * DvRLib - Local search * Duncan van Roermund, 2010-2012 * GeneticLS.java */ package dvrlib.localsearch; import java.util.LinkedList; public class GeneticLS<S extends Solution, E extends Comparable<E>> extends StatefulLocalSearch<GeneticProblem<S, E>, S, E, GeneticLS<S, E>.SearchState> { public class SearchState extends AbstractSearchState<GeneticProblem<S, E>, S> { protected GeneticPopulation<S> population; protected S solution = null; protected long lastImprovement; protected SearchState(GeneticProblem<S, E> problem, GeneticPopulation<S> population) { super(problem); this.population = population; } public GeneticPopulation<S> population() { return population; } @Override public S solution() { return (solution == null ? population.peekBest() : solution); } } protected final Combiner<GeneticProblem<S, E>, S> combiner; protected final int popSize, stopCount; /** * GeneticLS constructor. * @param combiner The combiner used to combine solutions when searching for a solution. * @param populationSize The default number of solutions kept in a population. * @param stopCount The number of iterations in which no better solution was found after which the algorithm will stop. */ public GeneticLS(Combiner<GeneticProblem<S, E>, S> combiner, int populationSize, int stopCount) { if(populationSize < 1) throw new IllegalArgumentException("populationSize should be > 0"); if(stopCount < 1) throw new IllegalArgumentException("stopCount should be > 0"); this.combiner = combiner; this.popSize = populationSize; this.stopCount = stopCount; } /** * Searches for an optimal solution for the given problem, which is saved and returned. * @see GeneticLS#search(GeneticLS.GLSSearchState) */ @Override protected S doSearch(GeneticProblem<S, E> problem, E bound, S solution) { return search(newState(problem, solution), bound).solution(); } /** * Searches for an optimal solution using the given search state, after which the best found solution is saved and the state is returned. * This algorithm keeps replacing the worst solution in the population by the new combined solution if it is better, until a predefined number of iterations give no improvement. * @see GeneticLS#iterate(GeneticLS.GLSSearchState, int) */ public SearchState search(SearchState state, E bound) { assert (state != null) : "State should not be null"; assert (bound != null) : "Bound should not be null"; combiner.reinitialize(); long n = stopCount; while(n > 0 && !state.problem.betterEq(state.solution(), bound)) { iterate(state, bound, n); n = stopCount - (state.iteration - state.lastImprovement); } state.solution().setIterationCount(state.iterationCount()); state.saveSolution(); return state; } /** * Does <code>n</code> iterations using the given search state, after which it is returned. * When a solution is found that is better or equal to the given bound, the search is stopped. */ @Override public SearchState iterate(SearchState state, E bound, long n) { long i = state.iterationCount(); for(long iMax = i + n; i < iMax && !state.problem.betterEq(state.solution(), bound); i++) { // Generate new solution by combining two random solutions from the population state.solution = combiner.combine(state, state.population.peekRandom(), state.population.peekRandom()); - if(state.population.contains(state.solution) || !state.problem.better(state.problem.evaluationBound(state.solution), state.population.peekWorst())) + if(state.population.contains(state.solution) || !state.problem.better(state.problem.evaluationBound(state.solution), state.population.peekWorst())) { + state.solution = null; continue; + } if(savingCriterion == LocalSearch.SavingCriterion.EveryIteration || (savingCriterion == LocalSearch.SavingCriterion.NewBest && state.problem.better(state.solution, state.population.peekBest()))) state.saveSolution(); if(state.population.add(state.solution)) { state.lastImprovement = i; if(savingCriterion == LocalSearch.SavingCriterion.EveryImprovement) state.saveSolution(); } } state.solution = null; state.iteration = i; return state; } @Override public SearchState newState(GeneticProblem<S, E> problem, S solution) { LinkedList<S> solutions = new LinkedList<S>(); solutions.add(solution); return newState(problem, solutions); } public SearchState newState(GeneticProblem<S, E> problem, Iterable<S> solutions) { GeneticPopulation<S> population = combiner.createPopulation(problem, solutions, popSize); problem.saveSolution(population.peekBest()); return new SearchState(problem, population); } }
false
true
public SearchState iterate(SearchState state, E bound, long n) { long i = state.iterationCount(); for(long iMax = i + n; i < iMax && !state.problem.betterEq(state.solution(), bound); i++) { // Generate new solution by combining two random solutions from the population state.solution = combiner.combine(state, state.population.peekRandom(), state.population.peekRandom()); if(state.population.contains(state.solution) || !state.problem.better(state.problem.evaluationBound(state.solution), state.population.peekWorst())) continue; if(savingCriterion == LocalSearch.SavingCriterion.EveryIteration || (savingCriterion == LocalSearch.SavingCriterion.NewBest && state.problem.better(state.solution, state.population.peekBest()))) state.saveSolution(); if(state.population.add(state.solution)) { state.lastImprovement = i; if(savingCriterion == LocalSearch.SavingCriterion.EveryImprovement) state.saveSolution(); } } state.solution = null; state.iteration = i; return state; }
public SearchState iterate(SearchState state, E bound, long n) { long i = state.iterationCount(); for(long iMax = i + n; i < iMax && !state.problem.betterEq(state.solution(), bound); i++) { // Generate new solution by combining two random solutions from the population state.solution = combiner.combine(state, state.population.peekRandom(), state.population.peekRandom()); if(state.population.contains(state.solution) || !state.problem.better(state.problem.evaluationBound(state.solution), state.population.peekWorst())) { state.solution = null; continue; } if(savingCriterion == LocalSearch.SavingCriterion.EveryIteration || (savingCriterion == LocalSearch.SavingCriterion.NewBest && state.problem.better(state.solution, state.population.peekBest()))) state.saveSolution(); if(state.population.add(state.solution)) { state.lastImprovement = i; if(savingCriterion == LocalSearch.SavingCriterion.EveryImprovement) state.saveSolution(); } } state.solution = null; state.iteration = i; return state; }
diff --git a/ui/simpleTogglePanel/src/main/java/org/richfaces/component/UISimpleTogglePanel.java b/ui/simpleTogglePanel/src/main/java/org/richfaces/component/UISimpleTogglePanel.java index 1417904f..e6cf6da6 100644 --- a/ui/simpleTogglePanel/src/main/java/org/richfaces/component/UISimpleTogglePanel.java +++ b/ui/simpleTogglePanel/src/main/java/org/richfaces/component/UISimpleTogglePanel.java @@ -1,341 +1,341 @@ /** * License Agreement. * * JBoss RichFaces - Ajax4jsf Component Library * * Copyright (C) 2007 Exadel, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.richfaces.component; import java.util.Iterator; import javax.el.ELException; import javax.el.ValueExpression; import javax.faces.FacesException; import javax.faces.application.FacesMessage; import javax.faces.component.ActionSource; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.FacesEvent; import javax.faces.event.PhaseId; import org.ajax4jsf.component.AjaxActionComponent; import org.ajax4jsf.component.AjaxComponent; import org.ajax4jsf.component.IterationStateHolder; import org.ajax4jsf.event.AjaxSource; import org.richfaces.component.util.MessageUtil; import org.richfaces.event.SimpleTogglePanelSwitchEvent; /** * JSF component class */ public abstract class UISimpleTogglePanel extends AjaxActionComponent implements AjaxComponent, AjaxSource, ActionSource, IterationStateHolder //public abstract class UISimpleTogglePanel extends UIInput implements AjaxComponent, AjaxSource, ActionSource { public static final String COMPONENT_FAMILY = "javax.faces.Command"; public static final String SERVER_SWITCH_TYPE = "server"; public static final String CLIENT_SWITCH_TYPE = "client"; public static final String AJAX_SWITCH_TYPE = "ajax"; @Deprecated public static final boolean COLLAPSED = false; @Deprecated public static final boolean EXPANDED = true; // private transient Boolean openedSet = null; private transient Boolean wasOpened = Boolean.FALSE; protected void setWasOpened(Boolean wasOpened) { this.wasOpened = wasOpened; } protected boolean isWasOpened() { return wasOpened; } public abstract void setSwitchType(String switchType); public abstract String getSwitchType(); public void setOpened(boolean opened) { setValue(new Boolean(opened).toString()); } public boolean isOpened() { Object value = getValue(); if (value instanceof Boolean) { return ((Boolean)value).booleanValue(); } else if (value instanceof String) { String s = (String) value; return Boolean.parseBoolean(s); } return true; } public boolean getRendersChildren() { return true; } /** * @throws NullPointerException {@inheritDoc} */ public void processDecodes(FacesContext context) { if (context == null) { throw new NullPointerException(); } // Skip processing if our rendered flag is false if (!isRendered()) { return; } setWasOpened(Boolean.valueOf(CLIENT_SWITCH_TYPE.equals(getSwitchType()) || isOpened())); if (isWasOpened()) { // Process all facets and children of this component Iterator<UIComponent> kids = getFacetsAndChildren(); while (kids.hasNext()) { UIComponent kid = kids.next(); kid.processDecodes(context); } } // Process this component itself try { decode(context); } catch (RuntimeException e) { context.renderResponse(); throw e; } } /** * @throws NullPointerException {@inheritDoc} */ public void processValidators(FacesContext context) { if (context == null) { throw new NullPointerException(); } // Skip processing if our rendered flag is false if (!isRendered()) { return; } if (isWasOpened()) { // Process all the facets and children of this component Iterator<UIComponent> kids = getFacetsAndChildren(); while (kids.hasNext()) { UIComponent kid = kids.next(); kid.processValidators(context); } } } /** * @throws NullPointerException {@inheritDoc} */ public void processUpdates(FacesContext context) { if (context == null) { throw new NullPointerException(); } // Skip processing if our rendered flag is false if (!isRendered()) { return; } if (isWasOpened()) { // Process all facets and children of this component Iterator<UIComponent> kids = getFacetsAndChildren(); while (kids.hasNext()) { UIComponent kid = kids.next(); kid.processUpdates(context); } } } @Override public void queueEvent(FacesEvent event) { if (event instanceof SimpleTogglePanelSwitchEvent && this.equals(event.getComponent())) { SimpleTogglePanelSwitchEvent switchEvent = (SimpleTogglePanelSwitchEvent) event; if (isImmediate()) { setOpened(switchEvent.isOpened()); } switchEvent.setPhaseId(PhaseId.UPDATE_MODEL_VALUES); } super.queueEvent(event); } @Override public void broadcast(FacesEvent event) throws AbortProcessingException { super.broadcast(event); if (event instanceof SimpleTogglePanelSwitchEvent) { SimpleTogglePanelSwitchEvent switchEvent = (SimpleTogglePanelSwitchEvent) event; setOpened(switchEvent.isOpened()); try { updateModel(); } catch (RuntimeException e) { getFacesContext().renderResponse(); throw e; } } } private Object value; protected Object getLocalValue() { return value; } @Override public Object getValue() { if (this.value != null) { return this.value; } ValueExpression ve = getValueExpression("value"); if (ve != null) { FacesContext context = getFacesContext(); try { return ve.getValue(context.getELContext()); } catch (ELException e) { throw new FacesException(e); } } return null; } @Override public void setValue(Object value) { this.value = value; } @Override public Object saveState(FacesContext context) { Object[] state = new Object[2]; state[0] = super.saveState(context); state[1] = this.value; return state; } @Override public void restoreState(FacesContext context, Object stateObject) { Object[] state = (Object[]) stateObject; super.restoreState(context, state[0]); this.value = state[1]; } public Object getIterationState() { Object[] state = new Object[2]; state[0] = this.value; state[1] = this.wasOpened; return state; } public void setIterationState(Object stateObject) { if (stateObject != null) { Object[] state = (Object[]) stateObject; this.value = state[0]; this.wasOpened = (Boolean) state[1]; } else { this.value = null; this.wasOpened = null; } } protected void updateModel() { Object value = getLocalValue(); if (value != null) { ValueExpression ve = getValueExpression("value"); - if (ve != null) { - FacesContext context = getFacesContext(); + FacesContext context = getFacesContext(); + if (ve != null && !ve.isReadOnly(context.getELContext())) { try { ve.setValue(context.getELContext(), value); setValue(null); } catch (ELException e) { String messageStr = e.getMessage(); Throwable result = e.getCause(); while (null != result && result.getClass().isAssignableFrom(ELException.class)) { messageStr = result.getMessage(); result = result.getCause(); } FacesMessage message; if (null == messageStr) { message = //not an UIInput, but constant is fine MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); } else { message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr); } context.getExternalContext().log(message.getSummary(), result); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (IllegalArgumentException e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (Exception e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } } } } }
true
true
protected void updateModel() { Object value = getLocalValue(); if (value != null) { ValueExpression ve = getValueExpression("value"); if (ve != null) { FacesContext context = getFacesContext(); try { ve.setValue(context.getELContext(), value); setValue(null); } catch (ELException e) { String messageStr = e.getMessage(); Throwable result = e.getCause(); while (null != result && result.getClass().isAssignableFrom(ELException.class)) { messageStr = result.getMessage(); result = result.getCause(); } FacesMessage message; if (null == messageStr) { message = //not an UIInput, but constant is fine MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); } else { message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr); } context.getExternalContext().log(message.getSummary(), result); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (IllegalArgumentException e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (Exception e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } } } }
protected void updateModel() { Object value = getLocalValue(); if (value != null) { ValueExpression ve = getValueExpression("value"); FacesContext context = getFacesContext(); if (ve != null && !ve.isReadOnly(context.getELContext())) { try { ve.setValue(context.getELContext(), value); setValue(null); } catch (ELException e) { String messageStr = e.getMessage(); Throwable result = e.getCause(); while (null != result && result.getClass().isAssignableFrom(ELException.class)) { messageStr = result.getMessage(); result = result.getCause(); } FacesMessage message; if (null == messageStr) { message = //not an UIInput, but constant is fine MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); } else { message = new FacesMessage(FacesMessage.SEVERITY_ERROR, messageStr, messageStr); } context.getExternalContext().log(message.getSummary(), result); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (IllegalArgumentException e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } catch (Exception e) { FacesMessage message = MessageUtil.getMessage(context, UIInput.UPDATE_MESSAGE_ID, new Object[] { MessageUtil.getLabel(context, this) }); context.getExternalContext().log(message.getSummary(), e); context.addMessage(getClientId(context), message); context.renderResponse(); } } } }
diff --git a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/AppleUtils.java b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/AppleUtils.java index c6d114b4..0376a42f 100644 --- a/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/AppleUtils.java +++ b/src/plugins/apple/src/com/jivesoftware/spark/plugin/apple/AppleUtils.java @@ -1,218 +1,224 @@ /** * $Revision: 22540 $ * $Date: 2005-10-10 08:44:25 -0700 (Mon, 10 Oct 2005) $ * * Copyright (C) 1999-2005 Jive Software. All rights reserved. * * This software is the proprietary information of Jive Software. * Use is subject to license terms. */ package com.jivesoftware.spark.plugin.apple; import com.apple.cocoa.application.NSApplication; import com.apple.cocoa.application.NSImage; import com.apple.cocoa.foundation.NSData; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.SparkManager; /** * Utilities for dealing with the apple dock * * @author Andrew Wright */ public final class AppleUtils { private boolean flash; private boolean usingDefaultIcon = true; public AppleUtils() { final Thread iconThread = new Thread(new Runnable() { public void run() { while (true) { if (!flash) { if (!usingDefaultIcon) { // Set default icon NSImage defaultImage = getDefaultImage(); NSApplication.sharedApplication().setApplicationIconImage(defaultImage); usingDefaultIcon = true; } + try { + Thread.sleep(100); + } + catch (InterruptedException e) { + Log.error(e); + } } else { final NSImage image = getImageForMessageCountOn(); NSApplication.sharedApplication().setApplicationIconImage(image); try { Thread.sleep(500); } catch (InterruptedException e) { } final NSImage image2 = getImageForMessageCountOff(); NSApplication.sharedApplication().setApplicationIconImage(image2); try { Thread.sleep(500); } catch (InterruptedException e) { } usingDefaultIcon = false; } } } }); iconThread.start(); } /** * Bounce the application's dock icon to get the user's attention. * * @param critical Bounce the icon repeatedly if this is true. Bounce it * only for one second (usually just one bounce) if this is false. */ public void bounceDockIcon(boolean critical) { int howMuch = (critical) ? NSApplication.UserAttentionRequestCritical : NSApplication.UserAttentionRequestInformational; final int requestID = NSApplication.sharedApplication().requestUserAttention(howMuch); // Since NSApplication.requestUserAttention() seems to ignore the // param and always bounces the dock icon continuously no matter // what, make sure it gets cancelled if appropriate. // This is Apple bug #3414391 if (!critical) { Thread cancelThread = new Thread(new Runnable() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { // ignore } NSApplication.sharedApplication().cancelUserAttentionRequest(requestID); } }); cancelThread.start(); } flash = true; } /** * Creates a {@link com.apple.cocoa.application.NSImage} from a string that points to an image in the class * * @param image classpath path of an image * @return an cocoa image object */ public static NSImage getImage(String image) { InputStream in = ApplePlugin.class.getResourceAsStream(image); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buff = new byte[10 * 1024]; int len; try { while ((len = in.read(buff)) != -1) { out.write(buff, 0, len); } in.close(); out.close(); } catch (IOException e) { Log.error(e.getMessage(), e); } NSData data = new NSData(out.toByteArray()); return new NSImage(data); } /** * Creates a {@link com.apple.cocoa.application.NSImage} from a string that points to an image in the class * * @return an cocoa image object */ public static NSImage getImage(URL url) { InputStream in = null; try { in = url.openStream(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buff = new byte[10 * 1024]; int len; try { while ((len = in.read(buff)) != -1) { out.write(buff, 0, len); } in.close(); out.close(); } catch (IOException e) { Log.error(e.getMessage(), e); } NSData data = new NSData(out.toByteArray()); return new NSImage(data); } public void resetDock() { if (flash) { flash = false; } } public static NSImage getImageForMessageCountOn() { int no = SparkManager.getChatManager().getChatContainer().getTotalNumberOfUnreadMessages(); ClassLoader loader = ApplePlugin.class.getClassLoader(); if (no > 10) { no = 10; } if (no == 0) { URL url = loader.getResource("images/Spark-Dock-256-On.png"); return getImage(url); } URL url = loader.getResource("images/Spark-Dock-256-" + no + "-On.png"); return getImage(url); } public static NSImage getImageForMessageCountOff() { int no = SparkManager.getChatManager().getChatContainer().getTotalNumberOfUnreadMessages(); ClassLoader loader = ApplePlugin.class.getClassLoader(); if (no > 10) { no = 10; } if (no == 0) { URL url = loader.getResource("images/Spark-Dock-256-On.png"); return getImage(url); } URL url = loader.getResource("images/Spark-Dock-256-" + no + "-Off.png"); return getImage(url); } public static NSImage getDefaultImage() { ClassLoader loader = ApplePlugin.class.getClassLoader(); URL url = loader.getResource("images/Spark-Dock-256-On.png"); return getImage(url); } }
true
true
public AppleUtils() { final Thread iconThread = new Thread(new Runnable() { public void run() { while (true) { if (!flash) { if (!usingDefaultIcon) { // Set default icon NSImage defaultImage = getDefaultImage(); NSApplication.sharedApplication().setApplicationIconImage(defaultImage); usingDefaultIcon = true; } } else { final NSImage image = getImageForMessageCountOn(); NSApplication.sharedApplication().setApplicationIconImage(image); try { Thread.sleep(500); } catch (InterruptedException e) { } final NSImage image2 = getImageForMessageCountOff(); NSApplication.sharedApplication().setApplicationIconImage(image2); try { Thread.sleep(500); } catch (InterruptedException e) { } usingDefaultIcon = false; } } } }); iconThread.start(); }
public AppleUtils() { final Thread iconThread = new Thread(new Runnable() { public void run() { while (true) { if (!flash) { if (!usingDefaultIcon) { // Set default icon NSImage defaultImage = getDefaultImage(); NSApplication.sharedApplication().setApplicationIconImage(defaultImage); usingDefaultIcon = true; } try { Thread.sleep(100); } catch (InterruptedException e) { Log.error(e); } } else { final NSImage image = getImageForMessageCountOn(); NSApplication.sharedApplication().setApplicationIconImage(image); try { Thread.sleep(500); } catch (InterruptedException e) { } final NSImage image2 = getImageForMessageCountOff(); NSApplication.sharedApplication().setApplicationIconImage(image2); try { Thread.sleep(500); } catch (InterruptedException e) { } usingDefaultIcon = false; } } } }); iconThread.start(); }
diff --git a/btm/src/main/java/bitronix/tm/BitronixTransactionManager.java b/btm/src/main/java/bitronix/tm/BitronixTransactionManager.java index 78ac865..6b10dd6 100644 --- a/btm/src/main/java/bitronix/tm/BitronixTransactionManager.java +++ b/btm/src/main/java/bitronix/tm/BitronixTransactionManager.java @@ -1,429 +1,434 @@ /* * Bitronix Transaction Manager * * Copyright (c) 2010, Bitronix Software. * * 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 bitronix.tm; import java.io.IOException; import java.util.*; import javax.naming.*; import javax.transaction.*; import javax.transaction.xa.XAException; import org.slf4j.*; import bitronix.tm.internal.*; import bitronix.tm.utils.*; /** * Implementation of {@link TransactionManager} and {@link UserTransaction}. * * @author lorban */ public class BitronixTransactionManager implements TransactionManager, UserTransaction, Referenceable, Service { private final static Logger log = LoggerFactory.getLogger(BitronixTransactionManager.class); private final static String MDC_GTRID_KEY = "btm-gtrid"; private final SortedMap<BitronixTransaction, ClearContextSynchronization> inFlightTransactions; private volatile boolean shuttingDown; /** * Create the {@link BitronixTransactionManager}. Open the journal, load resources and perform recovery * synchronously. The recovery service then gets scheduled for background recovery. */ public BitronixTransactionManager() { try { shuttingDown = false; logVersion(); Configuration configuration = TransactionManagerServices.getConfiguration(); configuration.buildServerIdArray(); // first call will initialize the ServerId if (log.isDebugEnabled()) { log.debug("starting BitronixTransactionManager using " + configuration); } TransactionManagerServices.getJournal().open(); TransactionManagerServices.getResourceLoader().init(); TransactionManagerServices.getRecoverer().run(); int backgroundRecoveryInterval = TransactionManagerServices.getConfiguration().getBackgroundRecoveryIntervalSeconds(); if (backgroundRecoveryInterval < 1) { throw new InitializationException("invalid configuration value for backgroundRecoveryIntervalSeconds, found '" + backgroundRecoveryInterval + "' but it must be greater than 0"); } inFlightTransactions = Collections.synchronizedSortedMap(new TreeMap<BitronixTransaction, ClearContextSynchronization>(new Comparator<BitronixTransaction>() { public int compare(BitronixTransaction t1, BitronixTransaction t2) { Long timestamp1 = t1.getResourceManager().getGtrid().extractTimestamp(); Long timestamp2 = t2.getResourceManager().getGtrid().extractTimestamp(); - return timestamp1.compareTo(timestamp2); + int compareTo = timestamp1.compareTo(timestamp2); + if (compareTo == 0) { + // if timestamps are equal, use the Uid as the tie-breaker + return t1.getGtrid().compareTo(t2.getGtrid()); + } + return compareTo; } })); if (log.isDebugEnabled()) { log.debug("recovery will run in the background every " + backgroundRecoveryInterval + " second(s)"); } Date nextExecutionDate = new Date(MonotonicClock.currentTimeMillis() + (backgroundRecoveryInterval * 1000L)); TransactionManagerServices.getTaskScheduler().scheduleRecovery(TransactionManagerServices.getRecoverer(), nextExecutionDate); } catch (IOException ex) { throw new InitializationException("cannot open disk journal", ex); } catch (Exception ex) { TransactionManagerServices.getJournal().shutdown(); TransactionManagerServices.getResourceLoader().shutdown(); throw new InitializationException("initialization failed, cannot safely start the transaction manager", ex); } } /** * Start a new transaction and bind the context to the calling thread. * @throws NotSupportedException if a transaction is already bound to the calling thread. * @throws SystemException if the transaction manager is shutting down. */ public void begin() throws NotSupportedException, SystemException { if (log.isDebugEnabled()) { log.debug("beginning a new transaction"); } if (isShuttingDown()) throw new BitronixSystemException("cannot start a new transaction, transaction manager is shutting down"); if (log.isDebugEnabled()) { dumpTransactionContexts(); } BitronixTransaction currentTx = getCurrentTransaction(); if (currentTx != null) throw new NotSupportedException("nested transactions not supported"); currentTx = createTransaction(); ThreadContext threadContext = ThreadContext.getThreadContext(); ClearContextSynchronization clearContextSynchronization = new ClearContextSynchronization(currentTx, threadContext); try { currentTx.getSynchronizationScheduler().add(clearContextSynchronization, Scheduler.ALWAYS_LAST_POSITION -1); currentTx.setActive(threadContext.getTimeout()); inFlightTransactions.put(currentTx, clearContextSynchronization); if (log.isDebugEnabled()) { log.debug("begun new transaction at " + new Date(currentTx.getResourceManager().getGtrid().extractTimestamp())); } } catch (RuntimeException ex) { clearContextSynchronization.afterCompletion(Status.STATUS_NO_TRANSACTION); throw ex; } catch (SystemException ex) { clearContextSynchronization.afterCompletion(Status.STATUS_NO_TRANSACTION); throw ex; } } public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, IllegalStateException, SystemException { BitronixTransaction currentTx = getCurrentTransaction(); if (log.isDebugEnabled()) { log.debug("committing transaction " + currentTx); } if (currentTx == null) throw new IllegalStateException("no transaction started on this thread"); currentTx.commit(); } public void rollback() throws IllegalStateException, SecurityException, SystemException { BitronixTransaction currentTx = getCurrentTransaction(); if (log.isDebugEnabled()) { log.debug("rolling back transaction " + currentTx); } if (currentTx == null) throw new IllegalStateException("no transaction started on this thread"); currentTx.rollback(); } public int getStatus() throws SystemException { BitronixTransaction currentTx = getCurrentTransaction(); if (currentTx == null) return Status.STATUS_NO_TRANSACTION; return currentTx.getStatus(); } public Transaction getTransaction() throws SystemException { return getCurrentTransaction(); } public void setRollbackOnly() throws IllegalStateException, SystemException { BitronixTransaction currentTx = getCurrentTransaction(); if (log.isDebugEnabled()) { log.debug("marking transaction as rollback only: " + currentTx); } if (currentTx == null) throw new IllegalStateException("no transaction started on this thread"); currentTx.setRollbackOnly(); } public void setTransactionTimeout(int seconds) throws SystemException { if (seconds < 0) throw new BitronixSystemException("cannot set a timeout to less than 0 second (was: " + seconds + "s)"); ThreadContext.getThreadContext().setTimeout(seconds); } public Transaction suspend() throws SystemException { BitronixTransaction currentTx = getCurrentTransaction(); if (log.isDebugEnabled()) { log.debug("suspending transaction " + currentTx); } if (currentTx == null) return null; try { currentTx.getResourceManager().suspend(); clearCurrentContextForSuspension(); inFlightTransactions.get(currentTx).threadContext = null; MDC.remove(MDC_GTRID_KEY); return currentTx; } catch (XAException ex) { throw new BitronixSystemException("cannot suspend " + currentTx + ", error=" + Decoder.decodeXAExceptionErrorCode(ex), ex); } } public void resume(Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException { if (log.isDebugEnabled()) { log.debug("resuming " + transaction); } if (transaction == null) throw new InvalidTransactionException("resumed transaction cannot be null"); if (!(transaction instanceof BitronixTransaction)) throw new InvalidTransactionException("resumed transaction must be an instance of BitronixTransaction"); BitronixTransaction tx = (BitronixTransaction) transaction; if (getCurrentTransaction() != null) throw new IllegalStateException("a transaction is already running on this thread"); try { XAResourceManager resourceManager = tx.getResourceManager(); resourceManager.resume(); ThreadContext threadContext = ThreadContext.getThreadContext(); threadContext.setTransaction(tx); inFlightTransactions.get(tx).threadContext = threadContext; MDC.put(MDC_GTRID_KEY, tx.getGtrid()); } catch (XAException ex) { throw new BitronixSystemException("cannot resume " + tx + ", error=" + Decoder.decodeXAExceptionErrorCode(ex), ex); } } /** * BitronixTransactionManager can only have a single instance per JVM so this method always returns a reference * with no special information to find back the sole instance. BitronixTransactionManagerObjectFactory will be used * by the JNDI server to get the BitronixTransactionManager instance of the JVM. * * @return an empty reference to get the BitronixTransactionManager. */ public Reference getReference() throws NamingException { return new Reference( BitronixTransactionManager.class.getName(), new StringRefAddr("TransactionManager", "BitronixTransactionManager"), BitronixTransactionManagerObjectFactory.class.getName(), null ); } /** * Return a count of the current in-flight transactions. Currently this method is only called by unit tests. * @return a count of in-flight transactions */ public int getInFlightTransactionCount() { return inFlightTransactions.size(); } /** * Return the timestamp of the oldest in-flight transaction. * @return the timestamp or Long.MIN_VALUE if there is no in-flight transaction. */ public long getOldestInFlightTransactionTimestamp() { BitronixTransaction oldestTransaction = null; long oldestTimestamp = Long.MAX_VALUE; // We're testing (isEmpty()) and accessing (first()), so we must synchronize (briefly) on the collection synchronized (inFlightTransactions) { if (inFlightTransactions.isEmpty()) { if (log.isDebugEnabled()) { log.debug("oldest in-flight transaction's timestamp: " + Long.MIN_VALUE); } return Long.MIN_VALUE; } // The inFlightTransactions map is sorted by timestamp, so the first transaction is always the oldest oldestTransaction = inFlightTransactions.firstKey(); } oldestTimestamp = oldestTransaction.getResourceManager().getGtrid().extractTimestamp(); if (log.isDebugEnabled()) { log.debug("oldest in-flight transaction's timestamp: " + oldestTimestamp); } return oldestTimestamp; } /** * Get the transaction currently registered on the current thread context. * @return the current transaction or null if no transaction has been started on the current thread. */ public BitronixTransaction getCurrentTransaction() { return ThreadContext.getThreadContext().getTransaction(); } /** * Check if the transaction manager is in the process of shutting down. * @return true if the transaction manager is in the process of shutting down. */ private boolean isShuttingDown() { return shuttingDown; } /** * Dump an overview of all running transactions as debug logs. */ public void dumpTransactionContexts() { if (!log.isDebugEnabled()) return; // We're using an iterator, so we must synchronize on the collection synchronized (inFlightTransactions) { log.debug("dumping " + inFlightTransactions.size() + " transaction context(s)"); for (BitronixTransaction tx : inFlightTransactions.keySet()) { log.debug(tx.toString()); } } } /** * Shut down the transaction manager and release all resources held by it. * <p>This call will also close the resources pools registered by the {@link bitronix.tm.resource.ResourceLoader} * like JMS and JDBC pools. The manually created ones are left untouched.</p> * <p>The Transaction Manager will wait during a configurable graceful period before forcibly killing active * transactions.</p> * After this method is called, attempts to create new transactions (via calls to * {@link javax.transaction.TransactionManager#begin()}) will be rejected with a {@link SystemException}.</p> * @see Configuration#getGracefulShutdownInterval() */ public synchronized void shutdown() { if (isShuttingDown()) { if (log.isDebugEnabled()) { log.debug("Transaction Manager has already shut down"); } return; } log.info("shutting down Bitronix Transaction Manager"); internalShutdown(); if (log.isDebugEnabled()) { log.debug("shutting down resource loader"); } TransactionManagerServices.getResourceLoader().shutdown(); if (log.isDebugEnabled()) { log.debug("shutting down executor"); } TransactionManagerServices.getExecutor().shutdown(); if (log.isDebugEnabled()) { log.debug("shutting down task scheduler"); } TransactionManagerServices.getTaskScheduler().shutdown(); if (log.isDebugEnabled()) { log.debug("shutting down journal"); } TransactionManagerServices.getJournal().shutdown(); if (log.isDebugEnabled()) { log.debug("shutting down recoverer"); } TransactionManagerServices.getRecoverer().shutdown(); if (log.isDebugEnabled()) { log.debug("shutting down configuration"); } TransactionManagerServices.getConfiguration().shutdown(); // clear references TransactionManagerServices.clear(); if (log.isDebugEnabled()) { log.debug("shutdown ran successfully"); } } private void internalShutdown() { shuttingDown = true; dumpTransactionContexts(); int seconds = TransactionManagerServices.getConfiguration().getGracefulShutdownInterval(); int txCount = 0; try { txCount = inFlightTransactions.size(); while (seconds > 0 && txCount > 0) { if (log.isDebugEnabled()) { log.debug("still " + txCount + " in-flight transactions, waiting... (" + seconds + " second(s) left)"); } try { Thread.sleep(1000); } catch (InterruptedException ex) { // ignore } seconds--; txCount = inFlightTransactions.size(); } } catch (Exception ex) { log.error("cannot get a list of in-flight transactions", ex); } if (txCount > 0) { if (log.isDebugEnabled()) { log.debug("still " + txCount + " in-flight transactions, shutting down anyway"); dumpTransactionContexts(); } } else { if (log.isDebugEnabled()) { log.debug("all transactions finished, resuming shutdown"); } } } public String toString() { return "a BitronixTransactionManager with " + inFlightTransactions.size() + " in-flight transaction(s)"; } /* * Internal impl */ /** * Output BTM version information as INFO log. */ private void logVersion() { log.info("Bitronix Transaction Manager version " + Version.getVersion()); if (log.isDebugEnabled()) { log.debug("JVM version " + System.getProperty("java.version")); } } /** * Create a new transaction on the current thread's context. * @return the created transaction. */ private BitronixTransaction createTransaction() { BitronixTransaction transaction = new BitronixTransaction(); ThreadContext.getThreadContext().setTransaction(transaction); MDC.put(MDC_GTRID_KEY, transaction.getGtrid()); return transaction; } /** * Unlink the transaction from the current thread's context. */ private void clearCurrentContextForSuspension() { if (log.isDebugEnabled()) { log.debug("clearing current thread context: " + ThreadContext.getThreadContext()); } ThreadContext.getThreadContext().clearTransaction(); } private final class ClearContextSynchronization implements Synchronization { private final BitronixTransaction currentTx; private ThreadContext threadContext; public ClearContextSynchronization(BitronixTransaction currentTx, ThreadContext threadContext) { this.currentTx = currentTx; this.threadContext = threadContext; } public void beforeCompletion() { } public void afterCompletion(int status) { if (log.isDebugEnabled()) { log.debug("clearing transaction from thread context: " + threadContext); } threadContext.clearTransaction(); if (log.isDebugEnabled()) { log.debug("removing transaction from in-flight transactions: " + currentTx); } inFlightTransactions.remove(currentTx); MDC.remove(MDC_GTRID_KEY); } public String toString() { return "a ClearContextSynchronization for " + currentTx; } } }
true
true
public BitronixTransactionManager() { try { shuttingDown = false; logVersion(); Configuration configuration = TransactionManagerServices.getConfiguration(); configuration.buildServerIdArray(); // first call will initialize the ServerId if (log.isDebugEnabled()) { log.debug("starting BitronixTransactionManager using " + configuration); } TransactionManagerServices.getJournal().open(); TransactionManagerServices.getResourceLoader().init(); TransactionManagerServices.getRecoverer().run(); int backgroundRecoveryInterval = TransactionManagerServices.getConfiguration().getBackgroundRecoveryIntervalSeconds(); if (backgroundRecoveryInterval < 1) { throw new InitializationException("invalid configuration value for backgroundRecoveryIntervalSeconds, found '" + backgroundRecoveryInterval + "' but it must be greater than 0"); } inFlightTransactions = Collections.synchronizedSortedMap(new TreeMap<BitronixTransaction, ClearContextSynchronization>(new Comparator<BitronixTransaction>() { public int compare(BitronixTransaction t1, BitronixTransaction t2) { Long timestamp1 = t1.getResourceManager().getGtrid().extractTimestamp(); Long timestamp2 = t2.getResourceManager().getGtrid().extractTimestamp(); return timestamp1.compareTo(timestamp2); } })); if (log.isDebugEnabled()) { log.debug("recovery will run in the background every " + backgroundRecoveryInterval + " second(s)"); } Date nextExecutionDate = new Date(MonotonicClock.currentTimeMillis() + (backgroundRecoveryInterval * 1000L)); TransactionManagerServices.getTaskScheduler().scheduleRecovery(TransactionManagerServices.getRecoverer(), nextExecutionDate); } catch (IOException ex) { throw new InitializationException("cannot open disk journal", ex); } catch (Exception ex) { TransactionManagerServices.getJournal().shutdown(); TransactionManagerServices.getResourceLoader().shutdown(); throw new InitializationException("initialization failed, cannot safely start the transaction manager", ex); } }
public BitronixTransactionManager() { try { shuttingDown = false; logVersion(); Configuration configuration = TransactionManagerServices.getConfiguration(); configuration.buildServerIdArray(); // first call will initialize the ServerId if (log.isDebugEnabled()) { log.debug("starting BitronixTransactionManager using " + configuration); } TransactionManagerServices.getJournal().open(); TransactionManagerServices.getResourceLoader().init(); TransactionManagerServices.getRecoverer().run(); int backgroundRecoveryInterval = TransactionManagerServices.getConfiguration().getBackgroundRecoveryIntervalSeconds(); if (backgroundRecoveryInterval < 1) { throw new InitializationException("invalid configuration value for backgroundRecoveryIntervalSeconds, found '" + backgroundRecoveryInterval + "' but it must be greater than 0"); } inFlightTransactions = Collections.synchronizedSortedMap(new TreeMap<BitronixTransaction, ClearContextSynchronization>(new Comparator<BitronixTransaction>() { public int compare(BitronixTransaction t1, BitronixTransaction t2) { Long timestamp1 = t1.getResourceManager().getGtrid().extractTimestamp(); Long timestamp2 = t2.getResourceManager().getGtrid().extractTimestamp(); int compareTo = timestamp1.compareTo(timestamp2); if (compareTo == 0) { // if timestamps are equal, use the Uid as the tie-breaker return t1.getGtrid().compareTo(t2.getGtrid()); } return compareTo; } })); if (log.isDebugEnabled()) { log.debug("recovery will run in the background every " + backgroundRecoveryInterval + " second(s)"); } Date nextExecutionDate = new Date(MonotonicClock.currentTimeMillis() + (backgroundRecoveryInterval * 1000L)); TransactionManagerServices.getTaskScheduler().scheduleRecovery(TransactionManagerServices.getRecoverer(), nextExecutionDate); } catch (IOException ex) { throw new InitializationException("cannot open disk journal", ex); } catch (Exception ex) { TransactionManagerServices.getJournal().shutdown(); TransactionManagerServices.getResourceLoader().shutdown(); throw new InitializationException("initialization failed, cannot safely start the transaction manager", ex); } }
diff --git a/src/test/java/fr/csvbang/test/writer/WriterTest.java b/src/test/java/fr/csvbang/test/writer/WriterTest.java index 1a0d523..b18f9f7 100644 --- a/src/test/java/fr/csvbang/test/writer/WriterTest.java +++ b/src/test/java/fr/csvbang/test/writer/WriterTest.java @@ -1,84 +1,85 @@ package fr.csvbang.test.writer; import java.text.SimpleDateFormat; import java.util.Calendar; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.BlockJUnit4ClassRunner; import fr.csvbang.configuration.CsvBangConfiguration; import fr.csvbang.exception.CsvBangException; import fr.csvbang.test.bean.writer.SimpleWriterBean; import fr.csvbang.util.ConfigurationUti; @RunWith(BlockJUnit4ClassRunner.class) public class WriterTest { private SimpleWriterTest<SimpleWriterBean> getSimpleWriter() throws CsvBangException{ CsvBangConfiguration conf = ConfigurationUti.loadCsvBangConfiguration(SimpleWriterBean.class); return new SimpleWriterTest<SimpleWriterBean>(conf); } @Test public void simpleTest() throws CsvBangException{ SimpleWriterTest<SimpleWriterBean> writer = getSimpleWriter(); SimpleDateFormat format = new SimpleDateFormat(SimpleWriterBean.DATE_PATTERN); SimpleWriterBean bean = new SimpleWriterBean(); Calendar c = Calendar.getInstance(); bean.setBirthday(c); bean.setId(125874); bean.setPrice(28.35); bean.setName("the name"); String result = "125874,the name,public Name: the name," + format.format(c.getTime()) + ",28.35"; SimpleWriterBean bean2 = new SimpleWriterBean(); Calendar c2 = Calendar.getInstance(); bean2.setBirthday(c2); bean2.setId(51445100); bean2.setPrice(1287.45); bean2.setName("super name"); result += "\n51445100,super name,public Name: super name," + format.format(c2.getTime()) + ",1287.45\n"; writer.write(bean); writer.write(bean2); Assert.assertEquals(result, writer.getResult()); } @Test public void simple2Test() throws CsvBangException{ SimpleWriterTest<SimpleWriterBean> writer = getSimpleWriter(); SimpleDateFormat format = new SimpleDateFormat(SimpleWriterBean.DATE_PATTERN); SimpleWriterBean bean = new SimpleWriterBean(); Calendar c = Calendar.getInstance(); bean.setBirthday(c); bean.setId(125874); bean.setName("the name"); - String result = "125874,the name,public Name: the name," + format.format(c.getTime()); + String result = "125874,the name,public Name: the name," + format.format(c.getTime()) +","; SimpleWriterBean bean2 = new SimpleWriterBean(); Calendar c2 = Calendar.getInstance(); bean2.setBirthday(c2); bean2.setPrice(1287.45); bean2.setName("super name"); - result += "\nsuper name,public Name: super name," + format.format(c2.getTime()) + ",1287.45\n"; + result += "\nsuper name,public Name: super name," + format.format(c2.getTime()) + ",1287.45"; SimpleWriterBean bean3 = new SimpleWriterBean(); - bean.setId(125874); + bean3.setId(125874); bean3.setPrice(1287.45); bean3.setName("super name"); - result += "\n125874,super name,public Name: super name," + format.format(c2.getTime()) + ",1287.45\n"; + result += "\n125874,super name,public Name: super name,no date,1287.45\n"; writer.write(bean); writer.write(bean2); + writer.write(bean3); Assert.assertEquals(result, writer.getResult()); } }
false
true
public void simple2Test() throws CsvBangException{ SimpleWriterTest<SimpleWriterBean> writer = getSimpleWriter(); SimpleDateFormat format = new SimpleDateFormat(SimpleWriterBean.DATE_PATTERN); SimpleWriterBean bean = new SimpleWriterBean(); Calendar c = Calendar.getInstance(); bean.setBirthday(c); bean.setId(125874); bean.setName("the name"); String result = "125874,the name,public Name: the name," + format.format(c.getTime()); SimpleWriterBean bean2 = new SimpleWriterBean(); Calendar c2 = Calendar.getInstance(); bean2.setBirthday(c2); bean2.setPrice(1287.45); bean2.setName("super name"); result += "\nsuper name,public Name: super name," + format.format(c2.getTime()) + ",1287.45\n"; SimpleWriterBean bean3 = new SimpleWriterBean(); bean.setId(125874); bean3.setPrice(1287.45); bean3.setName("super name"); result += "\n125874,super name,public Name: super name," + format.format(c2.getTime()) + ",1287.45\n"; writer.write(bean); writer.write(bean2); Assert.assertEquals(result, writer.getResult()); }
public void simple2Test() throws CsvBangException{ SimpleWriterTest<SimpleWriterBean> writer = getSimpleWriter(); SimpleDateFormat format = new SimpleDateFormat(SimpleWriterBean.DATE_PATTERN); SimpleWriterBean bean = new SimpleWriterBean(); Calendar c = Calendar.getInstance(); bean.setBirthday(c); bean.setId(125874); bean.setName("the name"); String result = "125874,the name,public Name: the name," + format.format(c.getTime()) +","; SimpleWriterBean bean2 = new SimpleWriterBean(); Calendar c2 = Calendar.getInstance(); bean2.setBirthday(c2); bean2.setPrice(1287.45); bean2.setName("super name"); result += "\nsuper name,public Name: super name," + format.format(c2.getTime()) + ",1287.45"; SimpleWriterBean bean3 = new SimpleWriterBean(); bean3.setId(125874); bean3.setPrice(1287.45); bean3.setName("super name"); result += "\n125874,super name,public Name: super name,no date,1287.45\n"; writer.write(bean); writer.write(bean2); writer.write(bean3); Assert.assertEquals(result, writer.getResult()); }
diff --git a/src/brutes/Brutes.java b/src/brutes/Brutes.java index 5e5d9cb..753247c 100644 --- a/src/brutes/Brutes.java +++ b/src/brutes/Brutes.java @@ -1,71 +1,71 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package brutes; import brutes.db.DatasManager; import brutes.net.Protocol; import brutes.net.client.NetworkClient; import brutes.net.server.NetworkLocalTestServer; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.sql.Connection; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.stage.Stage; /** * * @author Karl */ public class Brutes extends Application { @Override public void start(Stage stage) throws Exception { // DEBUG //(new File("bdd.db")).delete(); - Connection instance = DatasManager.getInstance("sqlite", "bdd.db"); + Connection instance = DatasManager.getInstance("sqlite", "~$bdd.db"); System.out.println(instance); new Thread(){ @Override public void run(){ try { ServerSocket sockserv = new ServerSocket (42666); System.out.println("Server up"); while(true){ Socket sockcli = sockserv.accept(); NetworkLocalTestServer n = new NetworkLocalTestServer(sockcli); try { n.read(); } catch (Exception ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } } catch (IOException ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } }.start(); ScenesContext.getInstance().setStage(stage); ScenesContext.getInstance().showLogin(); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
true
true
public void start(Stage stage) throws Exception { // DEBUG //(new File("bdd.db")).delete(); Connection instance = DatasManager.getInstance("sqlite", "bdd.db"); System.out.println(instance); new Thread(){ @Override public void run(){ try { ServerSocket sockserv = new ServerSocket (42666); System.out.println("Server up"); while(true){ Socket sockcli = sockserv.accept(); NetworkLocalTestServer n = new NetworkLocalTestServer(sockcli); try { n.read(); } catch (Exception ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } } catch (IOException ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } }.start(); ScenesContext.getInstance().setStage(stage); ScenesContext.getInstance().showLogin(); }
public void start(Stage stage) throws Exception { // DEBUG //(new File("bdd.db")).delete(); Connection instance = DatasManager.getInstance("sqlite", "~$bdd.db"); System.out.println(instance); new Thread(){ @Override public void run(){ try { ServerSocket sockserv = new ServerSocket (42666); System.out.println("Server up"); while(true){ Socket sockcli = sockserv.accept(); NetworkLocalTestServer n = new NetworkLocalTestServer(sockcli); try { n.read(); } catch (Exception ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } } catch (IOException ex) { Logger.getLogger(Brutes.class.getName()).log(Level.SEVERE, null, ex); } } }.start(); ScenesContext.getInstance().setStage(stage); ScenesContext.getInstance().showLogin(); }
diff --git a/src/org/timadorus/webapp/client/register/RegisterPanel.java b/src/org/timadorus/webapp/client/register/RegisterPanel.java index d365d18..42ce583 100644 --- a/src/org/timadorus/webapp/client/register/RegisterPanel.java +++ b/src/org/timadorus/webapp/client/register/RegisterPanel.java @@ -1,355 +1,356 @@ package org.timadorus.webapp.client.register; import org.timadorus.webapp.client.TimadorusWebApp; import org.timadorus.webapp.client.User; import org.timadorus.webapp.client.rpc.service.RegisterService; import org.timadorus.webapp.client.rpc.service.RegisterServiceAsync; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.HistoryListener; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PasswordTextBox; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; //FormPanel for Registering @SuppressWarnings("deprecation") public class RegisterPanel extends FormPanel implements HistoryListener { private final int rows = 9; private final int columns = 3; Grid grid = new Grid(rows, columns); Button submit = new Button("Registrieren"); private TextBox vornameTextBox = new TextBox(); private TextBox nachnameTextBox = new TextBox(); private TextBox geburtstagTextBox = new TextBox(); private TextBox emailTextBox = new TextBox(); private TextBox emailRepeatTextBox = new TextBox(); private TextBox usernameTextBox = new TextBox(); private PasswordTextBox passwordTextBox = new PasswordTextBox(); private PasswordTextBox passwordRepeatTextBox = new PasswordTextBox(); private HTML vornameHTML = new HTML(); private HTML nachnameHTML = new HTML(); private HTML geburtstagHTML = new HTML(); private HTML emailHTML = new HTML(); private HTML emailRepeatHTML = new HTML(); private HTML usernameHTML = new HTML(); private HTML passwordHTML = new HTML(); private HTML passwordRepeatHTML = new HTML(); private TimadorusWebApp entry; public TimadorusWebApp getEntry() { return entry; } public static final RegisterPanel getRegisterPanel(TimadorusWebApp entry) { return new RegisterPanel(entry); } private void setupHistory() { History.addHistoryListener(this); } public RegisterPanel(TimadorusWebApp timadorusWebApp) { super(); this.entry = timadorusWebApp; setupHistory(); grid.setWidget(0, 0, new Label("Vorname")); grid.setWidget(1, 0, new Label("Nachname")); grid.setWidget(2, 0, new Label("Geburtstag (dd.mm.jjjj)")); grid.setWidget(3, 0, new Label("Email")); grid.setWidget(4, 0, new Label("Email (Wiederholung)")); grid.setWidget(5, 0, new Label("Benutzername")); grid.setWidget(6, 0, new Label("Passwort")); grid.setWidget(7, 0, new Label("Passwort (Wiederholung)")); grid.setWidget(0, 1, vornameTextBox); grid.setWidget(1, 1, nachnameTextBox); grid.setWidget(2, 1, geburtstagTextBox); grid.setWidget(3, 1, emailTextBox); grid.setWidget(4, 1, emailRepeatTextBox); grid.setWidget(5, 1, usernameTextBox); grid.setWidget(6, 1, passwordTextBox); grid.setWidget(7, 1, passwordRepeatTextBox); grid.setWidget(0, 2, vornameHTML); grid.setWidget(1, 2, nachnameHTML); grid.setWidget(2, 2, geburtstagHTML); grid.setWidget(3, 2, emailHTML); grid.setWidget(4, 2, emailRepeatHTML); grid.setWidget(5, 2, usernameHTML); grid.setWidget(6, 2, passwordHTML); grid.setWidget(7, 2, passwordRepeatHTML); grid.setWidget(8, 1, submit); vornameTextBox.setText("Vorname"); nachnameTextBox.setText("Nachname"); geburtstagTextBox.setText("01.01.1980"); emailTextBox.setText("[email protected]"); emailRepeatTextBox.setText("[email protected]"); usernameTextBox.setText("Username"); passwordTextBox.setText("passwort"); passwordRepeatTextBox.setText("passwort"); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Will be triggered if the button was clicked. * * @param event The ClickEvent object */ public void onClick(ClickEvent event) { System.out.println("Submit Button geklickt"); handleEvent(); } /** * Will be triggered if the "Enter" button was hit while located in an input field. * * @param event The KeyUpEvent object */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { handleEvent(); } } private void handleEvent() { System.out.println("handle Event"); submit.setEnabled(false); setText(vornameHTML, ""); setText(nachnameHTML, ""); setText(geburtstagHTML, ""); setText(emailHTML, ""); setText(emailRepeatHTML, ""); setText(usernameHTML, ""); setText(passwordHTML, ""); setText(passwordRepeatHTML, ""); User register = new User(vornameTextBox.getText(), nachnameTextBox.getText(), geburtstagTextBox.getText(), emailTextBox.getText(), usernameTextBox.getText(), passwordTextBox.getText()); if (!register.isValid()) { if (passwordRepeatTextBox.getText().length() == 0) { registerInvalid(User.PASSWORDREPEAT_EMPTY); passwordRepeatTextBox.setFocus(true); } if (register.getPassword().length() == 0) { registerInvalid(User.PASSWORD_EMPTY); passwordTextBox.setFocus(true); } if (register.getUsername().length() == 0) { registerInvalid(User.USERNAME_EMPTY); usernameTextBox.setFocus(true); } if (emailRepeatTextBox.getText().length() == 0) { registerInvalid(User.EMAILREPEAT_EMPTY); emailRepeatTextBox.setFocus(true); } if (register.getEmail().length() == 0) { registerInvalid(User.EMAIL_EMPTY); emailTextBox.setFocus(true); } if (register.getGeburtstag().length() == 0) { registerInvalid(User.GEBURTSTAG_EMPTY); geburtstagTextBox.setFocus(true); } if (register.getVorname().length() == 0 && register.getNachname().length() == 0) { registerInvalid(User.VORNAME_NACHNAME_EMPTY); vornameTextBox.setFocus(true); } History.newItem("register"); } else if (!emailTextBox.getText().equals(emailRepeatTextBox.getText())) { registerInvalid(User.EMAIL_FAULT); } else if (!passwordTextBox.getText().equals(passwordRepeatTextBox.getText())) { registerInvalid(User.PASSWORD_FAULT); } else { sendToServer(register); } submit.setEnabled(true); } /** * Send form content to the server to add a new user object * * @param register A User object, containing the form contents */ private void sendToServer(User register) { RegisterServiceAsync registerServiceAsync = GWT.create(RegisterService.class); AsyncCallback<String> asyncCallback = new AsyncCallback<String>() { public void onSuccess(String result) { if (result != null) { String[] tmp = result.split("_"); int value = Integer.parseInt(tmp[0]); if (value == User.OK) { RootPanel.get("content").clear(); String[] href = Window.Location.getHref().split("#"); - getEntry().showDialogBox("ActivationLink", href[0] + "&activationCode=" + tmp[1]); + String linker = href[0].contains("?") ? "&" : "?"; + getEntry().showDialogBox("ActivationLink", href[0] + linker + "activationCode=" + tmp[1]); History.newItem("welcome"); } else { if (value >= User.PASSWORD_FAULT) { value -= User.PASSWORD_FAULT; } if (value >= User.USERNAME_FAULT) { value -= User.USERNAME_FAULT; registerInvalid(User.USERNAME_FAULT); } if (value >= User.EMAIL_FORMAT) { value -= User.EMAIL_FORMAT; registerInvalid(User.EMAIL_FORMAT); } if (value >= User.GEBURTSTAG_AGE) { value -= User.GEBURTSTAG_AGE; registerInvalid(User.GEBURTSTAG_AGE); } if (value >= User.GEBURTSTAG_FORMAT) { value -= User.GEBURTSTAG_FORMAT; registerInvalid(User.GEBURTSTAG_FORMAT); } if (value >= User.GEBURTSTAG_FAULT) { value -= User.GEBURTSTAG_FAULT; registerInvalid(User.GEBURTSTAG_FAULT); } submit.setEnabled(true); } } else { submit.setEnabled(true); } } public void onFailure(Throwable caught) { registerInvalid(0); System.out.println(caught); } }; registerServiceAsync.register(register, asyncCallback); } } MyHandler handler = new MyHandler(); submit.addClickHandler(handler); vornameTextBox.addKeyUpHandler(handler); nachnameTextBox.addKeyUpHandler(handler); geburtstagTextBox.addKeyUpHandler(handler); emailTextBox.addKeyUpHandler(handler); emailRepeatTextBox.addKeyUpHandler(handler); usernameTextBox.addKeyUpHandler(handler); passwordTextBox.addKeyUpHandler(handler); passwordRepeatTextBox.addKeyUpHandler(handler); setWidget(grid); setStyleName("formPanel"); } /** * If the registration was invalid, the error message will be formatted and inserted here. * * @param error An integer value representing the error message (Error code) */ public void registerInvalid(int error) { switch (error) { case User.VORNAME_NACHNAME_EMPTY: setText(vornameHTML, "Bitte ausfüllen!"); setText(nachnameHTML, "Bitte ausfüllen!"); break; case User.GEBURTSTAG_EMPTY: setText(geburtstagHTML, "Bitte ausfüllen!"); break; case User.GEBURTSTAG_AGE: setText(geburtstagHTML, "Du bist leider zu jung!"); break; case User.GEBURTSTAG_FORMAT: setText(geburtstagHTML, "Das Format ist ungültig!"); break; case User.GEBURTSTAG_FAULT: setText(geburtstagHTML, "Das Datum ist ungültig"); break; case User.EMAIL_EMPTY: setText(emailHTML, "Bitte ausfüllen!"); break; case User.EMAILREPEAT_EMPTY: setText(emailRepeatHTML, "Bitte ausfüllen!"); break; case User.EMAIL_FAULT: setText(emailHTML, "Stimmen nicht überein!"); setText(emailRepeatHTML, "Stimmen nicht überein!"); break; case User.EMAIL_FORMAT: setText(emailHTML, "Das Format ist ungültig!"); setText(emailRepeatHTML, "Das Format ist ungültig!"); break; case User.USERNAME_EMPTY: setText(usernameHTML, "Bitte ausfüllen!"); break; case User.USERNAME_FAULT: setText(usernameHTML, "Benutzername bereits vergeben!"); break; case User.PASSWORD_EMPTY: setText(passwordHTML, "Bitte ausfüllen!"); break; case User.PASSWORDREPEAT_EMPTY: setText(passwordRepeatHTML, "Bitte ausfüllen!"); break; case User.PASSWORD_FAULT: setText(passwordHTML, "Stimmen nicht überein!"); setText(passwordRepeatHTML, "Stimmen nicht überein!"); break; default: break; } } private void setText(HTML label, String message) { label.setHTML("<span class=\"error\">" + message + "</span>"); } @Override public void onHistoryChanged(String historyToken) { // if (LOGIN_STATE.equals(historyToken)) { // getEntry().loadLoginPanel(); // } else if (WELCOME_STATE.equals(historyToken)) { // getEntry().loadWelcomePanel(); // // } else if (CREATE_CHARACTER_STATE.equals(historyToken)) { // getEntry().loadCreateCharacter(); // } else if (REGISTER_STATE.equals(historyToken)) { // getEntry().loadRegisterPanel(); // } } }
true
true
public RegisterPanel(TimadorusWebApp timadorusWebApp) { super(); this.entry = timadorusWebApp; setupHistory(); grid.setWidget(0, 0, new Label("Vorname")); grid.setWidget(1, 0, new Label("Nachname")); grid.setWidget(2, 0, new Label("Geburtstag (dd.mm.jjjj)")); grid.setWidget(3, 0, new Label("Email")); grid.setWidget(4, 0, new Label("Email (Wiederholung)")); grid.setWidget(5, 0, new Label("Benutzername")); grid.setWidget(6, 0, new Label("Passwort")); grid.setWidget(7, 0, new Label("Passwort (Wiederholung)")); grid.setWidget(0, 1, vornameTextBox); grid.setWidget(1, 1, nachnameTextBox); grid.setWidget(2, 1, geburtstagTextBox); grid.setWidget(3, 1, emailTextBox); grid.setWidget(4, 1, emailRepeatTextBox); grid.setWidget(5, 1, usernameTextBox); grid.setWidget(6, 1, passwordTextBox); grid.setWidget(7, 1, passwordRepeatTextBox); grid.setWidget(0, 2, vornameHTML); grid.setWidget(1, 2, nachnameHTML); grid.setWidget(2, 2, geburtstagHTML); grid.setWidget(3, 2, emailHTML); grid.setWidget(4, 2, emailRepeatHTML); grid.setWidget(5, 2, usernameHTML); grid.setWidget(6, 2, passwordHTML); grid.setWidget(7, 2, passwordRepeatHTML); grid.setWidget(8, 1, submit); vornameTextBox.setText("Vorname"); nachnameTextBox.setText("Nachname"); geburtstagTextBox.setText("01.01.1980"); emailTextBox.setText("[email protected]"); emailRepeatTextBox.setText("[email protected]"); usernameTextBox.setText("Username"); passwordTextBox.setText("passwort"); passwordRepeatTextBox.setText("passwort"); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Will be triggered if the button was clicked. * * @param event The ClickEvent object */ public void onClick(ClickEvent event) { System.out.println("Submit Button geklickt"); handleEvent(); } /** * Will be triggered if the "Enter" button was hit while located in an input field. * * @param event The KeyUpEvent object */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { handleEvent(); } } private void handleEvent() { System.out.println("handle Event"); submit.setEnabled(false); setText(vornameHTML, ""); setText(nachnameHTML, ""); setText(geburtstagHTML, ""); setText(emailHTML, ""); setText(emailRepeatHTML, ""); setText(usernameHTML, ""); setText(passwordHTML, ""); setText(passwordRepeatHTML, ""); User register = new User(vornameTextBox.getText(), nachnameTextBox.getText(), geburtstagTextBox.getText(), emailTextBox.getText(), usernameTextBox.getText(), passwordTextBox.getText()); if (!register.isValid()) { if (passwordRepeatTextBox.getText().length() == 0) { registerInvalid(User.PASSWORDREPEAT_EMPTY); passwordRepeatTextBox.setFocus(true); } if (register.getPassword().length() == 0) { registerInvalid(User.PASSWORD_EMPTY); passwordTextBox.setFocus(true); } if (register.getUsername().length() == 0) { registerInvalid(User.USERNAME_EMPTY); usernameTextBox.setFocus(true); } if (emailRepeatTextBox.getText().length() == 0) { registerInvalid(User.EMAILREPEAT_EMPTY); emailRepeatTextBox.setFocus(true); } if (register.getEmail().length() == 0) { registerInvalid(User.EMAIL_EMPTY); emailTextBox.setFocus(true); } if (register.getGeburtstag().length() == 0) { registerInvalid(User.GEBURTSTAG_EMPTY); geburtstagTextBox.setFocus(true); } if (register.getVorname().length() == 0 && register.getNachname().length() == 0) { registerInvalid(User.VORNAME_NACHNAME_EMPTY); vornameTextBox.setFocus(true); } History.newItem("register"); } else if (!emailTextBox.getText().equals(emailRepeatTextBox.getText())) { registerInvalid(User.EMAIL_FAULT); } else if (!passwordTextBox.getText().equals(passwordRepeatTextBox.getText())) { registerInvalid(User.PASSWORD_FAULT); } else { sendToServer(register); } submit.setEnabled(true); } /** * Send form content to the server to add a new user object * * @param register A User object, containing the form contents */ private void sendToServer(User register) { RegisterServiceAsync registerServiceAsync = GWT.create(RegisterService.class); AsyncCallback<String> asyncCallback = new AsyncCallback<String>() { public void onSuccess(String result) { if (result != null) { String[] tmp = result.split("_"); int value = Integer.parseInt(tmp[0]); if (value == User.OK) { RootPanel.get("content").clear(); String[] href = Window.Location.getHref().split("#"); getEntry().showDialogBox("ActivationLink", href[0] + "&activationCode=" + tmp[1]); History.newItem("welcome"); } else { if (value >= User.PASSWORD_FAULT) { value -= User.PASSWORD_FAULT; } if (value >= User.USERNAME_FAULT) { value -= User.USERNAME_FAULT; registerInvalid(User.USERNAME_FAULT); } if (value >= User.EMAIL_FORMAT) { value -= User.EMAIL_FORMAT; registerInvalid(User.EMAIL_FORMAT); } if (value >= User.GEBURTSTAG_AGE) { value -= User.GEBURTSTAG_AGE; registerInvalid(User.GEBURTSTAG_AGE); } if (value >= User.GEBURTSTAG_FORMAT) { value -= User.GEBURTSTAG_FORMAT; registerInvalid(User.GEBURTSTAG_FORMAT); } if (value >= User.GEBURTSTAG_FAULT) { value -= User.GEBURTSTAG_FAULT; registerInvalid(User.GEBURTSTAG_FAULT); } submit.setEnabled(true); } } else { submit.setEnabled(true); } } public void onFailure(Throwable caught) { registerInvalid(0); System.out.println(caught); } }; registerServiceAsync.register(register, asyncCallback); } } MyHandler handler = new MyHandler(); submit.addClickHandler(handler); vornameTextBox.addKeyUpHandler(handler); nachnameTextBox.addKeyUpHandler(handler); geburtstagTextBox.addKeyUpHandler(handler); emailTextBox.addKeyUpHandler(handler); emailRepeatTextBox.addKeyUpHandler(handler); usernameTextBox.addKeyUpHandler(handler); passwordTextBox.addKeyUpHandler(handler); passwordRepeatTextBox.addKeyUpHandler(handler); setWidget(grid); setStyleName("formPanel"); }
public RegisterPanel(TimadorusWebApp timadorusWebApp) { super(); this.entry = timadorusWebApp; setupHistory(); grid.setWidget(0, 0, new Label("Vorname")); grid.setWidget(1, 0, new Label("Nachname")); grid.setWidget(2, 0, new Label("Geburtstag (dd.mm.jjjj)")); grid.setWidget(3, 0, new Label("Email")); grid.setWidget(4, 0, new Label("Email (Wiederholung)")); grid.setWidget(5, 0, new Label("Benutzername")); grid.setWidget(6, 0, new Label("Passwort")); grid.setWidget(7, 0, new Label("Passwort (Wiederholung)")); grid.setWidget(0, 1, vornameTextBox); grid.setWidget(1, 1, nachnameTextBox); grid.setWidget(2, 1, geburtstagTextBox); grid.setWidget(3, 1, emailTextBox); grid.setWidget(4, 1, emailRepeatTextBox); grid.setWidget(5, 1, usernameTextBox); grid.setWidget(6, 1, passwordTextBox); grid.setWidget(7, 1, passwordRepeatTextBox); grid.setWidget(0, 2, vornameHTML); grid.setWidget(1, 2, nachnameHTML); grid.setWidget(2, 2, geburtstagHTML); grid.setWidget(3, 2, emailHTML); grid.setWidget(4, 2, emailRepeatHTML); grid.setWidget(5, 2, usernameHTML); grid.setWidget(6, 2, passwordHTML); grid.setWidget(7, 2, passwordRepeatHTML); grid.setWidget(8, 1, submit); vornameTextBox.setText("Vorname"); nachnameTextBox.setText("Nachname"); geburtstagTextBox.setText("01.01.1980"); emailTextBox.setText("[email protected]"); emailRepeatTextBox.setText("[email protected]"); usernameTextBox.setText("Username"); passwordTextBox.setText("passwort"); passwordRepeatTextBox.setText("passwort"); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Will be triggered if the button was clicked. * * @param event The ClickEvent object */ public void onClick(ClickEvent event) { System.out.println("Submit Button geklickt"); handleEvent(); } /** * Will be triggered if the "Enter" button was hit while located in an input field. * * @param event The KeyUpEvent object */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { handleEvent(); } } private void handleEvent() { System.out.println("handle Event"); submit.setEnabled(false); setText(vornameHTML, ""); setText(nachnameHTML, ""); setText(geburtstagHTML, ""); setText(emailHTML, ""); setText(emailRepeatHTML, ""); setText(usernameHTML, ""); setText(passwordHTML, ""); setText(passwordRepeatHTML, ""); User register = new User(vornameTextBox.getText(), nachnameTextBox.getText(), geburtstagTextBox.getText(), emailTextBox.getText(), usernameTextBox.getText(), passwordTextBox.getText()); if (!register.isValid()) { if (passwordRepeatTextBox.getText().length() == 0) { registerInvalid(User.PASSWORDREPEAT_EMPTY); passwordRepeatTextBox.setFocus(true); } if (register.getPassword().length() == 0) { registerInvalid(User.PASSWORD_EMPTY); passwordTextBox.setFocus(true); } if (register.getUsername().length() == 0) { registerInvalid(User.USERNAME_EMPTY); usernameTextBox.setFocus(true); } if (emailRepeatTextBox.getText().length() == 0) { registerInvalid(User.EMAILREPEAT_EMPTY); emailRepeatTextBox.setFocus(true); } if (register.getEmail().length() == 0) { registerInvalid(User.EMAIL_EMPTY); emailTextBox.setFocus(true); } if (register.getGeburtstag().length() == 0) { registerInvalid(User.GEBURTSTAG_EMPTY); geburtstagTextBox.setFocus(true); } if (register.getVorname().length() == 0 && register.getNachname().length() == 0) { registerInvalid(User.VORNAME_NACHNAME_EMPTY); vornameTextBox.setFocus(true); } History.newItem("register"); } else if (!emailTextBox.getText().equals(emailRepeatTextBox.getText())) { registerInvalid(User.EMAIL_FAULT); } else if (!passwordTextBox.getText().equals(passwordRepeatTextBox.getText())) { registerInvalid(User.PASSWORD_FAULT); } else { sendToServer(register); } submit.setEnabled(true); } /** * Send form content to the server to add a new user object * * @param register A User object, containing the form contents */ private void sendToServer(User register) { RegisterServiceAsync registerServiceAsync = GWT.create(RegisterService.class); AsyncCallback<String> asyncCallback = new AsyncCallback<String>() { public void onSuccess(String result) { if (result != null) { String[] tmp = result.split("_"); int value = Integer.parseInt(tmp[0]); if (value == User.OK) { RootPanel.get("content").clear(); String[] href = Window.Location.getHref().split("#"); String linker = href[0].contains("?") ? "&" : "?"; getEntry().showDialogBox("ActivationLink", href[0] + linker + "activationCode=" + tmp[1]); History.newItem("welcome"); } else { if (value >= User.PASSWORD_FAULT) { value -= User.PASSWORD_FAULT; } if (value >= User.USERNAME_FAULT) { value -= User.USERNAME_FAULT; registerInvalid(User.USERNAME_FAULT); } if (value >= User.EMAIL_FORMAT) { value -= User.EMAIL_FORMAT; registerInvalid(User.EMAIL_FORMAT); } if (value >= User.GEBURTSTAG_AGE) { value -= User.GEBURTSTAG_AGE; registerInvalid(User.GEBURTSTAG_AGE); } if (value >= User.GEBURTSTAG_FORMAT) { value -= User.GEBURTSTAG_FORMAT; registerInvalid(User.GEBURTSTAG_FORMAT); } if (value >= User.GEBURTSTAG_FAULT) { value -= User.GEBURTSTAG_FAULT; registerInvalid(User.GEBURTSTAG_FAULT); } submit.setEnabled(true); } } else { submit.setEnabled(true); } } public void onFailure(Throwable caught) { registerInvalid(0); System.out.println(caught); } }; registerServiceAsync.register(register, asyncCallback); } } MyHandler handler = new MyHandler(); submit.addClickHandler(handler); vornameTextBox.addKeyUpHandler(handler); nachnameTextBox.addKeyUpHandler(handler); geburtstagTextBox.addKeyUpHandler(handler); emailTextBox.addKeyUpHandler(handler); emailRepeatTextBox.addKeyUpHandler(handler); usernameTextBox.addKeyUpHandler(handler); passwordTextBox.addKeyUpHandler(handler); passwordRepeatTextBox.addKeyUpHandler(handler); setWidget(grid); setStyleName("formPanel"); }
diff --git a/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/ctrl/AbstractDiscussionIterationCommand.java b/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/ctrl/AbstractDiscussionIterationCommand.java index e41ad47..063eaaa 100644 --- a/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/ctrl/AbstractDiscussionIterationCommand.java +++ b/RequirementsDiscussionAnalyzer/src/main/java/org/computer/knauss/reqtDiscussion/ui/ctrl/AbstractDiscussionIterationCommand.java @@ -1,133 +1,133 @@ package org.computer.knauss.reqtDiscussion.ui.ctrl; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import javax.swing.ProgressMonitor; import javax.swing.SwingWorker; import org.computer.knauss.reqtDiscussion.model.Discussion; import org.computer.knauss.reqtDiscussion.model.DiscussionEvent; public abstract class AbstractDiscussionIterationCommand extends AbstractCommand implements PropertyChangeListener { private static final long serialVersionUID = 1L; private ProgressMonitor progressMonitor; private ClassificationItemTask task; private HighlightRelatedDiscussions hrd; public AbstractDiscussionIterationCommand(String name) { super(name); } @Override public void actionPerformed(ActionEvent arg0) { progressMonitor = new ProgressMonitor(null, getValue(AbstractAction.NAME), null, 0, 100); progressMonitor.setProgress(0); task = new ClassificationItemTask(); task.addPropertyChangeListener(this); task.execute(); } @Override public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); progressMonitor.setProgress(progress); if (progressMonitor.isCanceled()) { task.cancel(true); } } } protected HighlightRelatedDiscussions getHRD() { if (this.hrd == null) { try { this.hrd = new HighlightRelatedDiscussions(); } catch (IOException e) { e.printStackTrace(); } } return this.hrd; } protected void preProcessingHook() { } protected void postProcessingHook() { } protected abstract void processDiscussionHook(Discussion[] d); protected DiscussionEvent[] getDiscussionEvents(Discussion[] d) { List<DiscussionEvent> ret = new LinkedList<DiscussionEvent>(); for (Discussion disc : d) { ret.addAll(Arrays.asList(disc.getDiscussionEvents())); } return ret.toArray(new DiscussionEvent[0]); } class ClassificationItemTask extends SwingWorker<Void, Void> { @Override public Void doInBackground() { preProcessingHook(); Discussion[] discussions = getDiscussionTableModel() .getDiscussions(); // Deal with complex discussions List<Discussion[]> aggregatedDiscussions; if (getVisualizationConfiguration().isAggregateDiscussions()) aggregatedDiscussions = getHRD().getAllAggregatedDiscussions( discussions); else { aggregatedDiscussions = new LinkedList<Discussion[]>(); for (Discussion d : discussions) { aggregatedDiscussions.add(new Discussion[] { d }); } } int progress = 0; - int total = discussions.length; + int total = aggregatedDiscussions.size(); setProgress(0); try { for (Discussion[] d : aggregatedDiscussions) { if (isCancelled()) { System.err.println(getClass().getSimpleName() + ": Canceled."); break; } processDiscussionHook(d); setProgress((progress++ * 100) / total); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getClass() .getSimpleName() + ": " + e.getMessage(), "Error performing " + getValue(AbstractAction.NAME), JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } // set progress to 100 to close progress monitor setProgress((progress++ * 100) / total); return null; } @Override public void done() { postProcessingHook(); } } }
true
true
public Void doInBackground() { preProcessingHook(); Discussion[] discussions = getDiscussionTableModel() .getDiscussions(); // Deal with complex discussions List<Discussion[]> aggregatedDiscussions; if (getVisualizationConfiguration().isAggregateDiscussions()) aggregatedDiscussions = getHRD().getAllAggregatedDiscussions( discussions); else { aggregatedDiscussions = new LinkedList<Discussion[]>(); for (Discussion d : discussions) { aggregatedDiscussions.add(new Discussion[] { d }); } } int progress = 0; int total = discussions.length; setProgress(0); try { for (Discussion[] d : aggregatedDiscussions) { if (isCancelled()) { System.err.println(getClass().getSimpleName() + ": Canceled."); break; } processDiscussionHook(d); setProgress((progress++ * 100) / total); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getClass() .getSimpleName() + ": " + e.getMessage(), "Error performing " + getValue(AbstractAction.NAME), JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } // set progress to 100 to close progress monitor setProgress((progress++ * 100) / total); return null; }
public Void doInBackground() { preProcessingHook(); Discussion[] discussions = getDiscussionTableModel() .getDiscussions(); // Deal with complex discussions List<Discussion[]> aggregatedDiscussions; if (getVisualizationConfiguration().isAggregateDiscussions()) aggregatedDiscussions = getHRD().getAllAggregatedDiscussions( discussions); else { aggregatedDiscussions = new LinkedList<Discussion[]>(); for (Discussion d : discussions) { aggregatedDiscussions.add(new Discussion[] { d }); } } int progress = 0; int total = aggregatedDiscussions.size(); setProgress(0); try { for (Discussion[] d : aggregatedDiscussions) { if (isCancelled()) { System.err.println(getClass().getSimpleName() + ": Canceled."); break; } processDiscussionHook(d); setProgress((progress++ * 100) / total); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getClass() .getSimpleName() + ": " + e.getMessage(), "Error performing " + getValue(AbstractAction.NAME), JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } // set progress to 100 to close progress monitor setProgress((progress++ * 100) / total); return null; }
diff --git a/library/src/com/cyrilmottier/polaris2/maps/model/Marker.java b/library/src/com/cyrilmottier/polaris2/maps/model/Marker.java index 1b56164..cc0d250 100644 --- a/library/src/com/cyrilmottier/polaris2/maps/model/Marker.java +++ b/library/src/com/cyrilmottier/polaris2/maps/model/Marker.java @@ -1,117 +1,117 @@ /* * Copyright (C) 2013 Cyril Mottier (http://cyrilmottier.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cyrilmottier.polaris2.maps.model; public final class Marker { final com.google.android.gms.maps.model.Marker mOriginal; private Marker(com.google.android.gms.maps.model.Marker original) { mOriginal = original; } /** * <strong>DO NOT USE.</strong> * <p/> * Obtain a new Circle based an original one. * * @param original * @return * @hide */ public static Marker obtain(com.google.android.gms.maps.model.Marker original) { return new Marker(original); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Marker)) { return false; } - return !mOriginal.equals(((Marker) other).mOriginal); + return mOriginal.equals(((Marker) other).mOriginal); } @Override public int hashCode() { return mOriginal.hashCode(); } public String getId() { return mOriginal.getId(); } public LatLng getPosition() { final com.google.android.gms.maps.model.LatLng original = mOriginal.getPosition(); return original == null ? null : LatLng.obtain(original); } public String getSnippet() { return mOriginal.getSnippet(); } public String getTitle() { return mOriginal.getTitle(); } public void hideInfoWindow() { mOriginal.hideInfoWindow(); } public boolean isDraggable() { return mOriginal.isDraggable(); } public boolean isInfoWindowShown() { return mOriginal.isInfoWindowShown(); } public boolean isVisible() { return mOriginal.isVisible(); } public void remove() { mOriginal.remove(); } public void setDraggable(boolean draggable) { mOriginal.setDraggable(draggable); } public void setPosition(LatLng latLng) { mOriginal.setPosition(latLng.mOriginal); } public void setSnippet(String snippet) { mOriginal.setSnippet(snippet); } public void setTitle(String title) { mOriginal.setTitle(title); } public void setVisible(boolean visible) { mOriginal.setVisible(visible); } public void showInfoWindow() { mOriginal.showInfoWindow(); } }
true
true
public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Marker)) { return false; } return !mOriginal.equals(((Marker) other).mOriginal); }
public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof Marker)) { return false; } return mOriginal.equals(((Marker) other).mOriginal); }
diff --git a/common/src/main/java/cz/incad/kramerius/virtualcollections/VirtualCollectionsManager.java b/common/src/main/java/cz/incad/kramerius/virtualcollections/VirtualCollectionsManager.java index f56324ff5..6f1fd296f 100644 --- a/common/src/main/java/cz/incad/kramerius/virtualcollections/VirtualCollectionsManager.java +++ b/common/src/main/java/cz/incad/kramerius/virtualcollections/VirtualCollectionsManager.java @@ -1,327 +1,327 @@ /* * Copyright (C) 2011 Alberto Hernandez * * 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 cz.incad.kramerius.virtualcollections; import java.io.IOException; import java.util.List; import cz.incad.kramerius.FedoraAccess; import cz.incad.kramerius.FedoraNamespaces; import cz.incad.kramerius.ProcessSubtreeException; import cz.incad.kramerius.TreeNodeProcessor; import cz.incad.kramerius.impl.FedoraAccessImpl; import cz.incad.kramerius.processes.impl.ProcessStarter; import cz.incad.kramerius.processes.utils.ProcessUtils; import cz.incad.kramerius.resourceindex.IResourceIndex; import cz.incad.kramerius.resourceindex.ResourceIndexService; import cz.incad.kramerius.utils.IOUtils; import cz.incad.kramerius.utils.conf.KConfiguration; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringEscapeUtils; import org.fedora.api.RelationshipTuple; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class VirtualCollectionsManager { private static final Logger logger = Logger.getLogger(VirtualCollectionsManager.class.getName()); static final String SPARQL_NS = "http://www.w3.org/2001/sw/DataAccess/rf1/result"; static final String TEXT_DS_PREFIX = "TEXT_"; public static VirtualCollection getVirtualCollection(FedoraAccess fedoraAccess, String collection, String[] langs) { try { IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); Document doc = g.getFedoraObjectsFromModelExt("collection", 1000, 0, "", ""); NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS(SPARQL_NS, "result"); NodeList children; Node child; String name; String pid; for (int i = 0; i < nodes.getLength(); i++) { name = null; pid = null; Node node = nodes.item(i); children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { child = children.item(j); if (child.getLocalName().equals("title")) { name = child.getFirstChild().getNodeValue(); } else if (child.getLocalName().equals("object")) { pid = ((Element) child).getAttribute("uri").replaceAll("info:fedora/", ""); } } if (name != null && pid != null && pid.equals(collection)) { VirtualCollection vc = new VirtualCollection(name, pid); for (int k = 0; k < langs.length; k++) { String text = IOUtils.readAsString(fedoraAccess.getDataStream(pid, TEXT_DS_PREFIX + langs[++k]), Charset.forName("UTF-8"), true); vc.addDescription(langs[k], text); } return vc; } } return null; } catch (Exception ex) { logger.log(Level.SEVERE, "Error getting virtual collections", ex); return null; } } public static List<VirtualCollection> getVirtualCollections(FedoraAccess fedoraAccess, String[] langs) { try { IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); - Document doc = g.getFedoraObjectsFromModelExt("collection", 1000, 0, "", ""); + Document doc = g.getFedoraObjectsFromModelExt("collection", 1000, 0, "title", ""); NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS(SPARQL_NS, "result"); NodeList children; Node child; String name; String pid; List<VirtualCollection> vcs = new ArrayList<VirtualCollection>(); for (int i = 0; i < nodes.getLength(); i++) { name = null; pid = null; Node node = nodes.item(i); children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { child = children.item(j); if (child.getLocalName().equals("title")) { name = child.getFirstChild().getNodeValue(); } else if (child.getLocalName().equals("object")) { pid = ((Element) child).getAttribute("uri").replaceAll("info:fedora/", ""); } } if (name != null && pid != null) { VirtualCollection vc = new VirtualCollection(name, pid); for (int k = 0; k < langs.length; k++) { String text = IOUtils.readAsString(fedoraAccess.getDataStream(pid, TEXT_DS_PREFIX + langs[++k]), Charset.forName("UTF-8"), true); vc.addDescription(langs[k], text); } vcs.add(vc); } } return vcs; } catch (Exception ex) { logger.log(Level.SEVERE, "Error getting virtual collections", ex); return null; } } public static void create(String label, String pid, FedoraAccess fedoraAccess) throws IOException { InputStream is = VirtualCollectionsManager.class.getResourceAsStream("vc.xml"); String s = IOUtils.readAsString(is, Charset.forName("UTF-8"), true); s = s.replaceAll("##title##", StringEscapeUtils.escapeXml(label)).replaceAll("##pid##", pid); fedoraAccess.getAPIM().ingest(s.getBytes(), "info:fedora/fedora-system:FOXML-1.1", "Create virtual collection"); } public static void delete(String pid, FedoraAccess fedoraAccess) throws Exception { removeDocumentsFromCollection(pid, fedoraAccess); fedoraAccess.getAPIM().purgeObject(pid, "Virtual collection deleted", true); startIndexer(pid, "reindexCollection", "Reindex docs in collection"); } public static void removeDocumentsFromCollection(String collection, FedoraAccess fedoraAccess) throws Exception { final String predicate = FedoraNamespaces.RDF_NAMESPACE_URI + "isMemberOfCollection"; final String fedoraColl = collection.startsWith("info:fedora/") ? collection : "info:fedora/" + collection; IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); ArrayList<String> pids = g.getObjectsInCollection(collection, 1000, 0); for(String pid : pids){ String fedoraPid = pid.startsWith("info:fedora/") ? pid : "info:fedora/" + pid; fedoraAccess.getAPIM().purgeRelationship(fedoraPid, predicate, fedoraColl, false, null); logger.log(Level.INFO, pid + " removed from collection " + collection); } } public static void modify(String pid, String label, FedoraAccess fedoraAccess) throws IOException { fedoraAccess.getAPIM().modifyObject(pid, "A", label, "K4", "Virtual collection modified"); String dcContent = "<oai_dc:dc xmlns:oai_dc=\"http://www.openarchives.org/OAI/2.0/oai_dc/\" " + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd\"> " + "<dc:title>" + StringEscapeUtils.escapeXml(label) + "</dc:title><dc:identifier>" + pid + "</dc:identifier>" + "</oai_dc:dc>"; fedoraAccess.getAPIM().modifyDatastreamByValue(pid, "DC", null, "Dublin Core Record for this object", "text/xml", null, dcContent.getBytes(), "DISABLED", null, "Virtual collection modified", true); } public static void modifyDatastream(String pid, String lang, String ds, FedoraAccess fedoraAccess, String k4url) throws IOException { String dsName = TEXT_DS_PREFIX + lang; String url = k4url + "?action=TEXT&content=" + URLEncoder.encode(ds, "UTF8"); if (!fedoraAccess.isStreamAvailable(pid, dsName)) { fedoraAccess.getAPIM().addDatastream(pid, dsName, null, "Description " + lang, false, "text/plain", null, url, "M", "A", "DISABLED", null, "Add text description"); System.out.println("Datastream added"); } else { fedoraAccess.getAPIM().modifyDatastreamByReference(pid, dsName, null, "Description " + lang, "text/plain", null, url, "DISABLED", null, "Change text description", true); } } public static boolean isInCollection(String pid, String collection, final FedoraAccess fedoraAccess) throws IOException { String fedoraPid = pid.startsWith("info:fedora/") ? pid : "info:fedora/" + pid; String fedoraColl = collection.startsWith("info:fedora/") ? collection : "info:fedora/" + collection; List<RelationshipTuple> rels = fedoraAccess.getAPIM().getRelationships(fedoraPid, FedoraNamespaces.RDF_NAMESPACE_URI + "isMemberOfCollection"); for (RelationshipTuple rel : rels) { if (rel.getObject().equals(fedoraColl)) { return true; } } return false; } public static void addToCollection(String pid, String collection, final FedoraAccess fedoraAccess) throws IOException { final String predicate = FedoraNamespaces.RDF_NAMESPACE_URI + "isMemberOfCollection"; final String fedoraColl = collection.startsWith("info:fedora/") ? collection : "info:fedora/" + collection; try { fedoraAccess.processSubtree(pid, new TreeNodeProcessor() { boolean breakProcess = false; int previousLevel = 0; @Override public boolean breakProcessing(String pid, int level) { return breakProcess; } @Override public void process(String pid, int level) throws ProcessSubtreeException { try { String fedoraPid = pid.startsWith("info:fedora/") ? pid : "info:fedora/" + pid; fedoraAccess.getAPIM().addRelationship(fedoraPid, predicate, fedoraColl, false, null); logger.log(Level.INFO, pid + " added to collection " + fedoraColl); } catch (Exception e) { throw new ProcessSubtreeException(e); } } }); } catch (ProcessSubtreeException e) { throw new IOException(e); } } public static void removeFromCollection(String pid, String collection, final FedoraAccess fedoraAccess) throws IOException { final String predicate = FedoraNamespaces.RDF_NAMESPACE_URI + "isMemberOfCollection"; final String fedoraColl = collection.startsWith("info:fedora/") ? collection : "info:fedora/" + collection; try { fedoraAccess.processSubtree(pid, new TreeNodeProcessor() { boolean breakProcess = false; int previousLevel = 0; @Override public boolean breakProcessing(String pid, int level) { return breakProcess; } @Override public void process(String pid, int level) throws ProcessSubtreeException { try { String fedoraPid = pid.startsWith("info:fedora/") ? pid : "info:fedora/" + pid; fedoraAccess.getAPIM().purgeRelationship(fedoraPid, predicate, fedoraColl, false, null); logger.log(Level.INFO, pid + " removed from collection " + fedoraColl); } catch (Exception e) { throw new ProcessSubtreeException(e); } } }); } catch (ProcessSubtreeException e) { throw new IOException(e); } } public static void removeCollections(String pid, final FedoraAccess fedoraAccess) throws Exception { final String predicate = FedoraNamespaces.RDF_NAMESPACE_URI + "isMemberOfCollection"; try { fedoraAccess.processSubtree(pid, new TreeNodeProcessor() { boolean breakProcess = false; int previousLevel = 0; @Override public boolean breakProcessing(String pid, int level) { return breakProcess; } @Override public void process(String pid, int level) throws ProcessSubtreeException { try { String fedoraPid = pid.startsWith("info:fedora/") ? pid : "info:fedora/" + pid; fedoraAccess.getAPIM().purgeRelationship(fedoraPid, predicate, null, true, null); } catch (Exception e) { throw new ProcessSubtreeException(e); } } }); } catch (ProcessSubtreeException e) { throw new IOException(e); } } public static void startIndexer(String pid, String action, String title) throws Exception{ String base = ProcessUtils.getLrServlet(); if (base == null || pid == null) { logger.severe("Cannot start long running process"); return; } String url = base + "?action=start&def=reindex&out=text&params="+action+"," + URLEncoder.encode(pid, "UTF8") + "," + URLEncoder.encode(title, "UTF8") + "&token=" + System.getProperty(ProcessStarter.TOKEN_KEY); logger.info("indexer URL:" + url); try { ProcessStarter.httpGet(url); } catch (Exception e) { logger.severe("Error starting indexer for " + pid + ":" + e); } } public static void main(String[] args) throws Exception { logger.log(Level.INFO, "process args: {0}", Arrays.toString(args)); FedoraAccess fa = new FedoraAccessImpl(KConfiguration.getInstance()); String action = args[0]; String pid = args[1]; String collection = args[2]; if (action.equals("remove")) { ProcessStarter.updateName("Remove " + pid + " from collection " + collection); VirtualCollectionsManager.removeFromCollection(pid, collection, fa); startIndexer(pid, "fromKrameriusModel", "Reindex doc "+pid); } else if (action.equals("add")) { ProcessStarter.updateName("Add " + pid + " to collection " + collection); VirtualCollectionsManager.addToCollection(pid, collection, fa); startIndexer(pid, "fromKrameriusModel", "Reindex doc "+pid); }else if (action.equals("removecollection")) { ProcessStarter.updateName("Remove collection " + collection); VirtualCollectionsManager.delete(collection, fa); }else{ logger.log(Level.INFO, "Unsupported action: {0}", action); return; } logger.log(Level.INFO, "Finished"); } }
true
true
public static List<VirtualCollection> getVirtualCollections(FedoraAccess fedoraAccess, String[] langs) { try { IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); Document doc = g.getFedoraObjectsFromModelExt("collection", 1000, 0, "", ""); NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS(SPARQL_NS, "result"); NodeList children; Node child; String name; String pid; List<VirtualCollection> vcs = new ArrayList<VirtualCollection>(); for (int i = 0; i < nodes.getLength(); i++) { name = null; pid = null; Node node = nodes.item(i); children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { child = children.item(j); if (child.getLocalName().equals("title")) { name = child.getFirstChild().getNodeValue(); } else if (child.getLocalName().equals("object")) { pid = ((Element) child).getAttribute("uri").replaceAll("info:fedora/", ""); } } if (name != null && pid != null) { VirtualCollection vc = new VirtualCollection(name, pid); for (int k = 0; k < langs.length; k++) { String text = IOUtils.readAsString(fedoraAccess.getDataStream(pid, TEXT_DS_PREFIX + langs[++k]), Charset.forName("UTF-8"), true); vc.addDescription(langs[k], text); } vcs.add(vc); } } return vcs; } catch (Exception ex) { logger.log(Level.SEVERE, "Error getting virtual collections", ex); return null; } }
public static List<VirtualCollection> getVirtualCollections(FedoraAccess fedoraAccess, String[] langs) { try { IResourceIndex g = ResourceIndexService.getResourceIndexImpl(); Document doc = g.getFedoraObjectsFromModelExt("collection", 1000, 0, "title", ""); NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS(SPARQL_NS, "result"); NodeList children; Node child; String name; String pid; List<VirtualCollection> vcs = new ArrayList<VirtualCollection>(); for (int i = 0; i < nodes.getLength(); i++) { name = null; pid = null; Node node = nodes.item(i); children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { child = children.item(j); if (child.getLocalName().equals("title")) { name = child.getFirstChild().getNodeValue(); } else if (child.getLocalName().equals("object")) { pid = ((Element) child).getAttribute("uri").replaceAll("info:fedora/", ""); } } if (name != null && pid != null) { VirtualCollection vc = new VirtualCollection(name, pid); for (int k = 0; k < langs.length; k++) { String text = IOUtils.readAsString(fedoraAccess.getDataStream(pid, TEXT_DS_PREFIX + langs[++k]), Charset.forName("UTF-8"), true); vc.addDescription(langs[k], text); } vcs.add(vc); } } return vcs; } catch (Exception ex) { logger.log(Level.SEVERE, "Error getting virtual collections", ex); return null; } }
diff --git a/app/repo/Repository.java b/app/repo/Repository.java index 61f325c..ecdbc93 100644 --- a/app/repo/Repository.java +++ b/app/repo/Repository.java @@ -1,101 +1,101 @@ package repo; import java.util.*; import models.*; /** * Class that contains many general functions for the system. */ public class Repository { /** * Checks if the given username/password is valid * @param username the username * @param password the password * @return true if the username/password are valid */ public static boolean login(String username, String password){ User tmp = User.find("byUsernameAndPassword", username, encodePassword(password)).first(); if(tmp != null) return true; else return false; } /** * Searches for exams within the given dates * @param first the beginning of the date range * @param last the end of the test range * @return a list of all the results */ public static List<Exam> searchByDate(Date first, Date last){ //Check for null if( first == null || last == null){ return new ArrayList<Exam>(0); } List<Exam> exams = Exam.findAll(); List<Exam> toRet = new ArrayList<Exam>(exams.size()); //Manually compare them all for(Exam cur: exams){ - if( (cur.getDate().after(first) || cur.getDate().equals(last)) - && (cur.getDate().before(last) || cur.getDate().equals(last)) ) + if( cur.getDate().compareTo(first) >= 0 + && cur.getDate().compareTo(last) <= 0 ) toRet.add(cur); } return toRet; } /** * Gets all the exams for a given patient * @param patientId the patient's ID * @return a list of all their exams */ //Maybe search by name? Im thinking a dropdown for this public static List<Exam> searchByPatient(Long patientId){ Patient patient = User.findById(patientId); if(patient != null) return patient.getExams(); else return new ArrayList<Exam>(0); } /** * Gets all the exams by a given physician * @param physicianId the physician's ID * @return a list of all their exams */ public static List<Exam> searchByPhysician(Long physicianId){ Physician physician = Physician.findById(physicianId); if(physician != null) return physician.getExams(); else return new ArrayList<Exam>(0); } /** * Encodes the given string * @param plaintext the string to encode * @return the encoded string */ public static String encodePassword(String plaintext){ //TODO: Come up with some encoding process return plaintext; } /** * Decodes the given string * @param encoded the encoded string * @return the decoded string */ public static String decodePassword(String encoded){ //TODO: Come up with the decoding process return encoded; } }
true
true
public static List<Exam> searchByDate(Date first, Date last){ //Check for null if( first == null || last == null){ return new ArrayList<Exam>(0); } List<Exam> exams = Exam.findAll(); List<Exam> toRet = new ArrayList<Exam>(exams.size()); //Manually compare them all for(Exam cur: exams){ if( (cur.getDate().after(first) || cur.getDate().equals(last)) && (cur.getDate().before(last) || cur.getDate().equals(last)) ) toRet.add(cur); } return toRet; }
public static List<Exam> searchByDate(Date first, Date last){ //Check for null if( first == null || last == null){ return new ArrayList<Exam>(0); } List<Exam> exams = Exam.findAll(); List<Exam> toRet = new ArrayList<Exam>(exams.size()); //Manually compare them all for(Exam cur: exams){ if( cur.getDate().compareTo(first) >= 0 && cur.getDate().compareTo(last) <= 0 ) toRet.add(cur); } return toRet; }
diff --git a/edu/wisc/ssec/mcidasv/data/hydra/Statistics.java b/edu/wisc/ssec/mcidasv/data/hydra/Statistics.java index 3179aabfc..7ab306b47 100644 --- a/edu/wisc/ssec/mcidasv/data/hydra/Statistics.java +++ b/edu/wisc/ssec/mcidasv/data/hydra/Statistics.java @@ -1,209 +1,209 @@ package edu.wisc.ssec.mcidasv.data.hydra; import visad.*; import java.rmi.RemoteException; import org.apache.commons.math.stat.descriptive.DescriptiveStatistics; import org.apache.commons.math.stat.correlation.PearsonsCorrelation; import org.apache.commons.math.stat.correlation.Covariance; public class Statistics { DescriptiveStatistics[] descriptiveStats = null; double[][] values_x; int rngTupLen; int numPoints; int[] numGoodPoints; MathType statType; PearsonsCorrelation pCorrelation = null; public Statistics(FlatField fltFld) throws VisADException, RemoteException { double[][] rngVals = fltFld.getValues(false); values_x = rngVals; rngTupLen = rngVals.length; numPoints = fltFld.getDomainSet().getLength(); numGoodPoints = new int[rngTupLen]; for (int k=0; k<rngTupLen; k++) { values_x[k] = removeMissing(rngVals[k]); numGoodPoints[k] = values_x[k].length; } descriptiveStats = new DescriptiveStatistics[rngTupLen]; for (int k=0; k<rngTupLen; k++) { descriptiveStats[k] = new DescriptiveStatistics(values_x[k]); } MathType rangeType = ((FunctionType)fltFld.getType()).getRange(); if (rangeType instanceof RealTupleType) { RealType[] rttypes = ((TupleType)rangeType).getRealComponents(); if (rngTupLen > 1) { statType = new RealTupleType(rttypes); } else { - statType = (RealType) rangeType; + statType = (RealType) rttypes[0]; } } else if (rangeType instanceof RealType) { statType = (RealType) rangeType; } else { throw new VisADException("incoming type must be RealTupleType or RealType"); } pCorrelation = new PearsonsCorrelation(); } public int numPoints() { return numPoints; } private double[] removeMissing(double[] vals) { int num = vals.length; int cnt = 0; int[] good = new int[num]; for (int k=0; k<num; k++) { if ( !(Double.isNaN(vals[k])) ) { good[cnt] = k; cnt++; } } if (cnt == num) { return vals; } double[] newVals = new double[cnt]; for (int k=0; k<cnt; k++) { newVals[k] = vals[good[k]]; } return newVals; } public Data mean() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getMean(); } return makeStat(stats); } public Data geometricMean() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getGeometricMean(); } return makeStat(stats); } public Data max() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getMax(); } return makeStat(stats); } public Data min() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getMin(); } return makeStat(stats); } public Data median() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getPercentile(50.0); } return makeStat(stats); } public Data variance() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getVariance(); } return makeStat(stats); } public Data kurtosis() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getKurtosis(); } return makeStat(stats); } public Data standardDeviation() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getStandardDeviation(); } return makeStat(stats); } public Data skewness() throws VisADException, RemoteException { double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { stats[k] = descriptiveStats[k].getSkewness(); } return makeStat(stats); } public Data correlation(FlatField fltFld) throws VisADException, RemoteException { double[][] values_y = fltFld.getValues(false); if ((values_y.length != rngTupLen) || (values_y[0].length != numPoints)) { throw new VisADException("both fields must have same numPoints and range tuple length"); } double[] stats = new double[rngTupLen]; for (int k=0; k<rngTupLen; k++) { double[][] newVals = removeMissingAND(values_x[k], values_y[k]); stats[k] = pCorrelation.correlation(newVals[0], newVals[1]); } return makeStat(stats); } private Data makeStat(double[] stats) throws VisADException, RemoteException { if (statType instanceof RealType) { return new Real((RealType)statType, stats[0]); } else if (statType instanceof RealTupleType) { return new RealTuple((RealTupleType)statType, stats); } return null; } private double[][] removeMissingAND(double[] vals_x, double[] vals_y) { int cnt = 0; int[] good = new int[vals_x.length]; for (int k=0; k<vals_x.length; k++) { if ( !(Double.isNaN(vals_x[k])) && !(Double.isNaN(vals_y[k])) ) { good[cnt] = k; cnt++; } } if (cnt == vals_x.length) { return new double[][] {vals_x, vals_y}; } else { double[] newVals_x = new double[cnt]; double[] newVals_y = new double[cnt]; for (int k=0; k<cnt; k++) { newVals_x[k] = vals_x[good[k]]; newVals_y[k] = vals_y[good[k]]; } return new double[][] {newVals_x, newVals_y}; } } }
true
true
public Statistics(FlatField fltFld) throws VisADException, RemoteException { double[][] rngVals = fltFld.getValues(false); values_x = rngVals; rngTupLen = rngVals.length; numPoints = fltFld.getDomainSet().getLength(); numGoodPoints = new int[rngTupLen]; for (int k=0; k<rngTupLen; k++) { values_x[k] = removeMissing(rngVals[k]); numGoodPoints[k] = values_x[k].length; } descriptiveStats = new DescriptiveStatistics[rngTupLen]; for (int k=0; k<rngTupLen; k++) { descriptiveStats[k] = new DescriptiveStatistics(values_x[k]); } MathType rangeType = ((FunctionType)fltFld.getType()).getRange(); if (rangeType instanceof RealTupleType) { RealType[] rttypes = ((TupleType)rangeType).getRealComponents(); if (rngTupLen > 1) { statType = new RealTupleType(rttypes); } else { statType = (RealType) rangeType; } } else if (rangeType instanceof RealType) { statType = (RealType) rangeType; } else { throw new VisADException("incoming type must be RealTupleType or RealType"); } pCorrelation = new PearsonsCorrelation(); }
public Statistics(FlatField fltFld) throws VisADException, RemoteException { double[][] rngVals = fltFld.getValues(false); values_x = rngVals; rngTupLen = rngVals.length; numPoints = fltFld.getDomainSet().getLength(); numGoodPoints = new int[rngTupLen]; for (int k=0; k<rngTupLen; k++) { values_x[k] = removeMissing(rngVals[k]); numGoodPoints[k] = values_x[k].length; } descriptiveStats = new DescriptiveStatistics[rngTupLen]; for (int k=0; k<rngTupLen; k++) { descriptiveStats[k] = new DescriptiveStatistics(values_x[k]); } MathType rangeType = ((FunctionType)fltFld.getType()).getRange(); if (rangeType instanceof RealTupleType) { RealType[] rttypes = ((TupleType)rangeType).getRealComponents(); if (rngTupLen > 1) { statType = new RealTupleType(rttypes); } else { statType = (RealType) rttypes[0]; } } else if (rangeType instanceof RealType) { statType = (RealType) rangeType; } else { throw new VisADException("incoming type must be RealTupleType or RealType"); } pCorrelation = new PearsonsCorrelation(); }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaThreadActionFilter.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaThreadActionFilter.java index b3dcaa007..8bcd5424b 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaThreadActionFilter.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaThreadActionFilter.java @@ -1,48 +1,50 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jdt.debug.core.IJavaExceptionBreakpoint; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.ui.IActionFilter; /** * Filter which determines if actions relevant to an IJavaThread should * be displayed. This filter is provided to the platform by JDIDebugUIAdapterFactory. */ public class JavaThreadActionFilter implements IActionFilter { public boolean testAttribute(Object target, String name, String value) { if (target instanceof IJavaThread) { if (name.equals("TerminateEvaluationActionFilter") //$NON-NLS-1$ && value.equals("supportsTerminateEvaluation")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; return thread.isPerformingEvaluation(); } else if (name.equals("ExcludeExceptionLocationFilter") //$NON-NLS-1$ && value.equals("suspendedAtException")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; IBreakpoint[] breakpoints= thread.getBreakpoints(); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint= breakpoints[i]; try { - return breakpoint.isRegistered() && breakpoint instanceof IJavaExceptionBreakpoint; + if (breakpoint.isRegistered() && breakpoint instanceof IJavaExceptionBreakpoint) { + return true; + } } catch (CoreException e) { } } } } return false; } }
true
true
public boolean testAttribute(Object target, String name, String value) { if (target instanceof IJavaThread) { if (name.equals("TerminateEvaluationActionFilter") //$NON-NLS-1$ && value.equals("supportsTerminateEvaluation")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; return thread.isPerformingEvaluation(); } else if (name.equals("ExcludeExceptionLocationFilter") //$NON-NLS-1$ && value.equals("suspendedAtException")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; IBreakpoint[] breakpoints= thread.getBreakpoints(); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint= breakpoints[i]; try { return breakpoint.isRegistered() && breakpoint instanceof IJavaExceptionBreakpoint; } catch (CoreException e) { } } } } return false; }
public boolean testAttribute(Object target, String name, String value) { if (target instanceof IJavaThread) { if (name.equals("TerminateEvaluationActionFilter") //$NON-NLS-1$ && value.equals("supportsTerminateEvaluation")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; return thread.isPerformingEvaluation(); } else if (name.equals("ExcludeExceptionLocationFilter") //$NON-NLS-1$ && value.equals("suspendedAtException")) { //$NON-NLS-1$ IJavaThread thread = (IJavaThread) target; IBreakpoint[] breakpoints= thread.getBreakpoints(); for (int i = 0; i < breakpoints.length; i++) { IBreakpoint breakpoint= breakpoints[i]; try { if (breakpoint.isRegistered() && breakpoint instanceof IJavaExceptionBreakpoint) { return true; } } catch (CoreException e) { } } } } return false; }
diff --git a/android/PasswordGenerator/src/info/ilyaraz/passwordgenerator/ClueEditor.java b/android/PasswordGenerator/src/info/ilyaraz/passwordgenerator/ClueEditor.java index 4f32582..494f506 100644 --- a/android/PasswordGenerator/src/info/ilyaraz/passwordgenerator/ClueEditor.java +++ b/android/PasswordGenerator/src/info/ilyaraz/passwordgenerator/ClueEditor.java @@ -1,45 +1,45 @@ package info.ilyaraz.passwordgenerator; import java.security.MessageDigest; import info.ilyaraz.passwordgenerator.domain.ClueData; import info.ilyaraz.passwordgenerator.util.Callback1; import info.ilyaraz.passwordgenerator.util.Closure; import info.ilyaraz.passwordgenerator.util.Constants; import info.ilyaraz.passwordgenerator.util.StringCallback; import android.app.Activity; import android.app.AlertDialog; import android.content.ContextWrapper; import android.content.DialogInterface; import android.content.SharedPreferences; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; public class ClueEditor { public static void editClue(String clueId, final Activity context, final Callback1<ClueData> onSuccess, final Closure onFailure) { final SharedPreferences settings = context.getSharedPreferences(Constants.STORAGE_NAMESPACE, 0); LayoutInflater inflater = context.getLayoutInflater(); - View dialogLayout = inflater.inflate(R.layout.add_clue, (ViewGroup) context.getCurrentFocus()); + View dialogLayout = inflater.inflate(R.layout.add_clue, null); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(dialogLayout); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onSuccess.Run(new ClueData()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onFailure.Run(); } }); builder.show(); } }
true
true
public static void editClue(String clueId, final Activity context, final Callback1<ClueData> onSuccess, final Closure onFailure) { final SharedPreferences settings = context.getSharedPreferences(Constants.STORAGE_NAMESPACE, 0); LayoutInflater inflater = context.getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.add_clue, (ViewGroup) context.getCurrentFocus()); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(dialogLayout); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onSuccess.Run(new ClueData()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onFailure.Run(); } }); builder.show(); }
public static void editClue(String clueId, final Activity context, final Callback1<ClueData> onSuccess, final Closure onFailure) { final SharedPreferences settings = context.getSharedPreferences(Constants.STORAGE_NAMESPACE, 0); LayoutInflater inflater = context.getLayoutInflater(); View dialogLayout = inflater.inflate(R.layout.add_clue, null); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(dialogLayout); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onSuccess.Run(new ClueData()); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { onFailure.Run(); } }); builder.show(); }
diff --git a/webmacro/src/org/webmacro/engine/ListBuilder.java b/webmacro/src/org/webmacro/engine/ListBuilder.java index 3f9db360..a81964df 100755 --- a/webmacro/src/org/webmacro/engine/ListBuilder.java +++ b/webmacro/src/org/webmacro/engine/ListBuilder.java @@ -1,113 +1,113 @@ /* * Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted under the terms of either of the following * Open Source licenses: * * The GNU General Public License, version 2, or any later version, as * published by the Free Software Foundation * (http://www.fsf.org/copyleft/gpl.html); * * or * * The Semiotek Public License (http://webmacro.org/LICENSE.) * * This software is provided "as is", with NO WARRANTY, not even the * implied warranties of fitness to purpose, or merchantability. You * assume all risks and liabilities associated with its use. * * See www.webmacro.org for more information on the WebMacro project. */ package org.webmacro.engine; import java.io.*; import java.util.*; import org.webmacro.Context; import org.webmacro.FastWriter; import org.webmacro.Macro; import org.webmacro.PropertyException; /** * ListBuilder is used for building argument lists to function calls * or array initializers. If all of the arguments are compile-time * constants, the build() method returns an Object[], otherwise it * returns a ListMacro. */ public final class ListBuilder extends Vector implements Builder { public final Object[] buildAsArray(BuildContext bc) throws BuildException { Object c[] = new Object[size()]; for (int i = 0; i < c.length; i++) { Object elem = elementAt(i); c[i] = (elem instanceof Builder) ? ((Builder) elem).build(bc) : elem; } return c; } public final Object build(BuildContext bc) throws BuildException { boolean isMacro = false; Object[] c = buildAsArray(bc); for (int i = 0; i < c.length; i++) if (c[i] instanceof Macro) isMacro = true; return (isMacro) ? (Object) new ListMacro(c) : c; } } /** * A list is a sequence of terms. It's used in two common cases: * the items in an array initializer; and the arguments to a * method call. */ class ListMacro implements Macro { final private Object[] _content; // the list data /** * create a new list */ ListMacro(Object[] content) { _content = content; } public void write(FastWriter out, Context context) throws PropertyException, IOException { out.write(evaluate(context).toString()); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < _content.length; i++) { if (i != 0) { sb.append(", "); } - sb.append(_content[i].toString()); + sb.append(_content[i] == null ? "null" : _content[i].toString()); } sb.append(")"); return sb.toString(); } public Object evaluate(Context context) throws PropertyException { Object[] ret = new Object[_content.length]; for (int i = 0; i < _content.length; i++) { Object m = _content[i]; if (m instanceof Macro) { m = ((Macro) m).evaluate(context); } ret[i] = m; } return ret; } }
true
true
public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < _content.length; i++) { if (i != 0) { sb.append(", "); } sb.append(_content[i].toString()); } sb.append(")"); return sb.toString(); }
public String toString() { StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < _content.length; i++) { if (i != 0) { sb.append(", "); } sb.append(_content[i] == null ? "null" : _content[i].toString()); } sb.append(")"); return sb.toString(); }
diff --git a/src/test/pleocmd/pipe/PipeTest.java b/src/test/pleocmd/pipe/PipeTest.java index de93aaf..94844fe 100644 --- a/src/test/pleocmd/pipe/PipeTest.java +++ b/src/test/pleocmd/pipe/PipeTest.java @@ -1,254 +1,254 @@ package test.pleocmd.pipe; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.Test; import pleocmd.Log; import pleocmd.cfg.Configuration; import pleocmd.exc.ConfigurationException; import pleocmd.exc.PipeException; import pleocmd.pipe.Pipe; import pleocmd.pipe.PipeFeedback; import pleocmd.pipe.in.Input; import pleocmd.pipe.in.StaticInput; import pleocmd.pipe.out.FileOutput; import pleocmd.pipe.out.InternalCommandOutput; import pleocmd.pipe.out.Output; import pleocmd.pipe.out.PrintType; import test.pleocmd.Testcases; public class PipeTest extends Testcases { @Test public final void testPipeAllData() throws Exception { PipeFeedback fb; final Pipe p = new Pipe(new Configuration()); Log.consoleOut("Test empty pipe"); p.reset(); fb = testSimplePipe(null, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0); Log.consoleOut("Test simple pipe"); fb = testSimplePipe("SC|SLEEP|100\nSC|ECHO|Echo working\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test bad input"); fb = testSimplePipe("SC|HELP", -1, -1, 0, 0, 0, 0, 1, 0, 0, 0); Log.consoleOut("Test unknown command"); fb = testSimplePipe("UNKNOWN|0|6.5|Hello\n", -1, -1, 1, 0, 0, 1, 0, 0, 0, 0); Log.consoleOut("Test executing rest of queue after close"); fb = testSimplePipe("SC|SLEEP|500\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|ECHO|End\n", 500, -1, 7, 0, 7, 0, 0, 0, 0, 0); Log.consoleOut("Test interrupt"); fb = testSimplePipe("[P-10]SC|SLEEP|10000\nSC|ECHO|HighPrio\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n", -1, 9000, 10, 0, -1, 0, 0, 1, -1, 0); assertTrue(fb.getDataOutputCount() == 9 || fb.getDataOutputCount() == 10); assertTrue(fb.getDropCount() <= 1); Log.consoleOut("Test low priority drop"); fb = testSimplePipe("SC|SLEEP|400\n[P-10]SC|SLEEP|30000\n", 400, 25000, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test high priority queue clearing"); fb = testSimplePipe("SC|SLEEP|10000\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "[P05]SC|ECHO|HighPrio\n", -1, -1, 23, 0, -1, 0, 0, 1, -1, 0); assertTrue("Expected 1 output and 22 drops (slow computer) or " + "2 outputs and 21 drops (fast computer): ", fb .getDataOutputCount() == 2 && fb.getDropCount() == 21 || fb.getDataOutputCount() == 1 && fb.getDropCount() == 22); Log.consoleOut("Test timed execution (need to wait)"); fb = testSimplePipe( "SC|SLEEP|400\n[T600msP10]SC|ECHO|Timed HighPrio\n", 600, 950, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (short delay)"); fb = testSimplePipe("SC|SLEEP|100\n[T50ms]SC|ECHO|Short Delay\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (long delay)"); fb = testSimplePipe("SC|SLEEP|500\n[T0ms]SC|ECHO|Long Delay\n", 500, -1, 2, 0, 2, 0, 0, 0, 0, 1); Log.consoleOut("Test timed execution combined " + "with low priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP-99]SC|ECHO|PrintedToo\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with low priority (dropped)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP-99]SC|FAIL|Dropped\n", 1000, -1, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test timed execution combined " + "with high priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with high priority (interrupted)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 1, 0, 0); Log.consoleOut("Test continuing after temporary error"); fb = testSimplePipe("SC|FAIL\nSC|SLEEP|500\n", 500, -1, 2, 0, 2, 1, 0, 0, 0, 0); Log.consoleOut("Test complex situation"); fb = testSimplePipe("[T100ms]SC|ECHO|1\n" + "SC|FAIL|UnknownCommand\n" + "[T300msP10]SC|ECHO|2\n" + "[P10T300ms]SC|ECHO|3\n" + "[P05T400ms]SC|ECHO|4\n" + "[P05T400ms]SC|SLEEP|600\n" + "[T400ms]SC|FAIL|Drop\n" + "SC|FAIL|Drop\n" + "InvalidInputßßß\n" + "SC|FAIL|Drop\n" + "[T550ms]SC|FAIL|Drop\n" + "[T600msP05]SC|ECHO|I'm late\n" + "[P05]SC|ECHO|5\n" + "[T1100msP05]SC|ECHO|6\n" + "[T1200ms]SC|SLEEP|300\n" + "[P99T1350ms]SC|ECHO|7\n", 1350, -1, 15, 0, 11, 2, 0, 1, 4, 1); Log.consoleOut("Test timing"); testSimplePipe("SC|ECHO|$ELAPSED=0?\n" + "[T150ms]SC|SLEEP|200\n" + "SC|ECHO|$ELAPSED=350?\n" + "[T450msP10]SC|ECHO|$ELAPSED=450?\n" + "[T550ms]SC|ECHO|$ELAPSED=550?\n" + "[T650ms]SC|ECHO|$ELAPSED=650?\n" + "[T700ms]SC|ECHO|$ELAPSED=700?\n" + "[T750ms]SC|ECHO|$ELAPSED=750?\n" + "[T775ms]SC|ECHO|$ELAPSED=775?\n" + "[T800ms]SC|ECHO|$ELAPSED=800?\n" + "[T825ms]SC|ECHO|$ELAPSED=825?\n" + "[T850ms]SC|ECHO|$ELAPSED=850?\n" + "[T860ms]SC|ECHO|$ELAPSED=860?\n" + "[T870ms]SC|ECHO|$ELAPSED=870?\n" + "[T880ms]SC|ECHO|$ELAPSED=880?\n" + "[T1000ms]SC|ECHO|$ELAPSED=1000?\n" + "SC|ECHO|$ELAPSED=1000+<10?\n" + "SC|ECHO|$ELAPSED=1000+<20?\n" + "SC|ECHO|$ELAPSED=1000+<30?\n", 450, -1, 19, 0, 19, 0, 0, 0, 0, 0); Log.consoleOut("Test error handling (two inputs, first one fails)"); Input in1, in2; Output out1, out2; p.reset(); p.addInput(in1 = new StaticInput("FAILURE")); p.addInput(in2 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new InternalCommandOutput()); in1.connectToPipePart(out1); in2.connectToPipePart(out1); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); Log.consoleOut("Test error handling (converter fails)"); Log.consoleOut("TODO"); // TODO ENH converter fails => output unconverted Log.consoleOut("Test error handling (sole output fails)"); final File tmpFile = File.createTempFile("PipeTest", null); p.reset(); p.addInput(in1 = new StaticInput("[T1s]\n[T8sP10]\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); in1.connectToPipePart(out1); tmpFile.delete(); tmpFile.mkdir(); - fb = testSimplePipe(p, 1000, 7000, 2, 0, 0, 0, 1, 0, 0, 0); + fb = testSimplePipe(p, 0, 900, 2, 0, 0, 0, 1, 0, 0, 0); tmpFile.delete(); Log.consoleOut("Test error handling (two outputs, first one fails)"); p.reset(); p.addInput(in1 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); p.addOutput(out2 = new InternalCommandOutput()); in1.connectToPipePart(out1); in1.connectToPipePart(out2); tmpFile.mkdir(); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); tmpFile.delete(); } // CS_IGNORE_NEXT this many parameters are ok here - only a test case private PipeFeedback testSimplePipe(final Object input, final long minTime, final long maxTime, final int dataIn, final int dataCvt, final int dataOut, final int tempErr, final int permErr, final int intrCnt, final int dropCnt, final int behindCnt) throws PipeException, InterruptedException, ConfigurationException { // create pipe final Pipe pipe; if (input instanceof Pipe) pipe = (Pipe) input; else pipe = new Pipe(new Configuration()); if (input instanceof String) { final StaticInput in; final InternalCommandOutput out; pipe.reset(); pipe.addInput(in = new StaticInput((String) input)); pipe.addOutput(out = new InternalCommandOutput()); in.connectToPipePart(out); } // execute pipe pipe.configure(); pipe.pipeAllData(); // print log Log.consoleOut(pipe.getFeedback().toString()); if (input instanceof String) Log.consoleOut("Finished Pipe containing '%s'", ((String) input) .replaceAll("\n(.)", "; $1").replace("\n", "")); else Log.consoleOut("Finished Pipe"); Log.consoleOut(""); // check result final PipeFeedback fb = pipe.getFeedback(); if (permErr != -1) assertEquals("Permanent Error Count is wrong: ", permErr, fb .getPermanentErrors().size()); if (tempErr != -1) assertEquals("Temporary Error Count is wrong: ", tempErr, fb .getTemporaryErrors().size()); if (intrCnt != -1) assertEquals("Interrupt Count is wrong: ", intrCnt, fb .getInterruptionCount()); if (dropCnt != -1) assertEquals("Drop Count is wrong: ", dropCnt, fb.getDropCount()); if (behindCnt != -1) assertEquals("Behind Count is wrong: ", behindCnt, fb .getSignificantBehindCount()); if (dataIn != -1) assertEquals("Data Input Count is wrong: ", dataIn, fb .getDataInputCount()); if (dataCvt != -1) assertEquals("Data Conversion Count is wrong: ", dataCvt, fb .getDataConvertedCount()); if (dataOut != -1) assertEquals("Data Output Count is wrong: ", dataOut, fb .getDataOutputCount()); if (minTime != -1) assertTrue("Took not long enough", fb.getElapsed() >= minTime); if (maxTime != -1) assertTrue("Took too long", fb.getElapsed() <= maxTime); return fb; } }
true
true
public final void testPipeAllData() throws Exception { PipeFeedback fb; final Pipe p = new Pipe(new Configuration()); Log.consoleOut("Test empty pipe"); p.reset(); fb = testSimplePipe(null, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0); Log.consoleOut("Test simple pipe"); fb = testSimplePipe("SC|SLEEP|100\nSC|ECHO|Echo working\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test bad input"); fb = testSimplePipe("SC|HELP", -1, -1, 0, 0, 0, 0, 1, 0, 0, 0); Log.consoleOut("Test unknown command"); fb = testSimplePipe("UNKNOWN|0|6.5|Hello\n", -1, -1, 1, 0, 0, 1, 0, 0, 0, 0); Log.consoleOut("Test executing rest of queue after close"); fb = testSimplePipe("SC|SLEEP|500\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|ECHO|End\n", 500, -1, 7, 0, 7, 0, 0, 0, 0, 0); Log.consoleOut("Test interrupt"); fb = testSimplePipe("[P-10]SC|SLEEP|10000\nSC|ECHO|HighPrio\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n", -1, 9000, 10, 0, -1, 0, 0, 1, -1, 0); assertTrue(fb.getDataOutputCount() == 9 || fb.getDataOutputCount() == 10); assertTrue(fb.getDropCount() <= 1); Log.consoleOut("Test low priority drop"); fb = testSimplePipe("SC|SLEEP|400\n[P-10]SC|SLEEP|30000\n", 400, 25000, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test high priority queue clearing"); fb = testSimplePipe("SC|SLEEP|10000\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "[P05]SC|ECHO|HighPrio\n", -1, -1, 23, 0, -1, 0, 0, 1, -1, 0); assertTrue("Expected 1 output and 22 drops (slow computer) or " + "2 outputs and 21 drops (fast computer): ", fb .getDataOutputCount() == 2 && fb.getDropCount() == 21 || fb.getDataOutputCount() == 1 && fb.getDropCount() == 22); Log.consoleOut("Test timed execution (need to wait)"); fb = testSimplePipe( "SC|SLEEP|400\n[T600msP10]SC|ECHO|Timed HighPrio\n", 600, 950, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (short delay)"); fb = testSimplePipe("SC|SLEEP|100\n[T50ms]SC|ECHO|Short Delay\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (long delay)"); fb = testSimplePipe("SC|SLEEP|500\n[T0ms]SC|ECHO|Long Delay\n", 500, -1, 2, 0, 2, 0, 0, 0, 0, 1); Log.consoleOut("Test timed execution combined " + "with low priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP-99]SC|ECHO|PrintedToo\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with low priority (dropped)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP-99]SC|FAIL|Dropped\n", 1000, -1, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test timed execution combined " + "with high priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with high priority (interrupted)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 1, 0, 0); Log.consoleOut("Test continuing after temporary error"); fb = testSimplePipe("SC|FAIL\nSC|SLEEP|500\n", 500, -1, 2, 0, 2, 1, 0, 0, 0, 0); Log.consoleOut("Test complex situation"); fb = testSimplePipe("[T100ms]SC|ECHO|1\n" + "SC|FAIL|UnknownCommand\n" + "[T300msP10]SC|ECHO|2\n" + "[P10T300ms]SC|ECHO|3\n" + "[P05T400ms]SC|ECHO|4\n" + "[P05T400ms]SC|SLEEP|600\n" + "[T400ms]SC|FAIL|Drop\n" + "SC|FAIL|Drop\n" + "InvalidInputßßß\n" + "SC|FAIL|Drop\n" + "[T550ms]SC|FAIL|Drop\n" + "[T600msP05]SC|ECHO|I'm late\n" + "[P05]SC|ECHO|5\n" + "[T1100msP05]SC|ECHO|6\n" + "[T1200ms]SC|SLEEP|300\n" + "[P99T1350ms]SC|ECHO|7\n", 1350, -1, 15, 0, 11, 2, 0, 1, 4, 1); Log.consoleOut("Test timing"); testSimplePipe("SC|ECHO|$ELAPSED=0?\n" + "[T150ms]SC|SLEEP|200\n" + "SC|ECHO|$ELAPSED=350?\n" + "[T450msP10]SC|ECHO|$ELAPSED=450?\n" + "[T550ms]SC|ECHO|$ELAPSED=550?\n" + "[T650ms]SC|ECHO|$ELAPSED=650?\n" + "[T700ms]SC|ECHO|$ELAPSED=700?\n" + "[T750ms]SC|ECHO|$ELAPSED=750?\n" + "[T775ms]SC|ECHO|$ELAPSED=775?\n" + "[T800ms]SC|ECHO|$ELAPSED=800?\n" + "[T825ms]SC|ECHO|$ELAPSED=825?\n" + "[T850ms]SC|ECHO|$ELAPSED=850?\n" + "[T860ms]SC|ECHO|$ELAPSED=860?\n" + "[T870ms]SC|ECHO|$ELAPSED=870?\n" + "[T880ms]SC|ECHO|$ELAPSED=880?\n" + "[T1000ms]SC|ECHO|$ELAPSED=1000?\n" + "SC|ECHO|$ELAPSED=1000+<10?\n" + "SC|ECHO|$ELAPSED=1000+<20?\n" + "SC|ECHO|$ELAPSED=1000+<30?\n", 450, -1, 19, 0, 19, 0, 0, 0, 0, 0); Log.consoleOut("Test error handling (two inputs, first one fails)"); Input in1, in2; Output out1, out2; p.reset(); p.addInput(in1 = new StaticInput("FAILURE")); p.addInput(in2 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new InternalCommandOutput()); in1.connectToPipePart(out1); in2.connectToPipePart(out1); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); Log.consoleOut("Test error handling (converter fails)"); Log.consoleOut("TODO"); // TODO ENH converter fails => output unconverted Log.consoleOut("Test error handling (sole output fails)"); final File tmpFile = File.createTempFile("PipeTest", null); p.reset(); p.addInput(in1 = new StaticInput("[T1s]\n[T8sP10]\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); in1.connectToPipePart(out1); tmpFile.delete(); tmpFile.mkdir(); fb = testSimplePipe(p, 1000, 7000, 2, 0, 0, 0, 1, 0, 0, 0); tmpFile.delete(); Log.consoleOut("Test error handling (two outputs, first one fails)"); p.reset(); p.addInput(in1 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); p.addOutput(out2 = new InternalCommandOutput()); in1.connectToPipePart(out1); in1.connectToPipePart(out2); tmpFile.mkdir(); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); tmpFile.delete(); }
public final void testPipeAllData() throws Exception { PipeFeedback fb; final Pipe p = new Pipe(new Configuration()); Log.consoleOut("Test empty pipe"); p.reset(); fb = testSimplePipe(null, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0); Log.consoleOut("Test simple pipe"); fb = testSimplePipe("SC|SLEEP|100\nSC|ECHO|Echo working\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test bad input"); fb = testSimplePipe("SC|HELP", -1, -1, 0, 0, 0, 0, 1, 0, 0, 0); Log.consoleOut("Test unknown command"); fb = testSimplePipe("UNKNOWN|0|6.5|Hello\n", -1, -1, 1, 0, 0, 1, 0, 0, 0, 0); Log.consoleOut("Test executing rest of queue after close"); fb = testSimplePipe("SC|SLEEP|500\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|ECHO|End\n", 500, -1, 7, 0, 7, 0, 0, 0, 0, 0); Log.consoleOut("Test interrupt"); fb = testSimplePipe("[P-10]SC|SLEEP|10000\nSC|ECHO|HighPrio\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n" + "SC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\nSC|SLEEP|1\n", -1, 9000, 10, 0, -1, 0, 0, 1, -1, 0); assertTrue(fb.getDataOutputCount() == 9 || fb.getDataOutputCount() == 10); assertTrue(fb.getDropCount() <= 1); Log.consoleOut("Test low priority drop"); fb = testSimplePipe("SC|SLEEP|400\n[P-10]SC|SLEEP|30000\n", 400, 25000, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test high priority queue clearing"); fb = testSimplePipe("SC|SLEEP|10000\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "SC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\nSC|FAIL\n" + "[P05]SC|ECHO|HighPrio\n", -1, -1, 23, 0, -1, 0, 0, 1, -1, 0); assertTrue("Expected 1 output and 22 drops (slow computer) or " + "2 outputs and 21 drops (fast computer): ", fb .getDataOutputCount() == 2 && fb.getDropCount() == 21 || fb.getDataOutputCount() == 1 && fb.getDropCount() == 22); Log.consoleOut("Test timed execution (need to wait)"); fb = testSimplePipe( "SC|SLEEP|400\n[T600msP10]SC|ECHO|Timed HighPrio\n", 600, 950, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (short delay)"); fb = testSimplePipe("SC|SLEEP|100\n[T50ms]SC|ECHO|Short Delay\n", 100, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution (long delay)"); fb = testSimplePipe("SC|SLEEP|500\n[T0ms]SC|ECHO|Long Delay\n", 500, -1, 2, 0, 2, 0, 0, 0, 0, 1); Log.consoleOut("Test timed execution combined " + "with low priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP-99]SC|ECHO|PrintedToo\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with low priority (dropped)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP-99]SC|FAIL|Dropped\n", 1000, -1, 2, 0, 1, 0, 0, 0, 1, 0); Log.consoleOut("Test timed execution combined " + "with high priority (executed)"); fb = testSimplePipe("[T500ms]SC|ECHO|Printed\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 0, 0, 0); Log.consoleOut("Test timed execution combined " + "with high priority (interrupted)"); fb = testSimplePipe("[T500ms]SC|SLEEP|500\n" + "[T900msP33]SC|ECHO|HighPrio\n", 900, -1, 2, 0, 2, 0, 0, 1, 0, 0); Log.consoleOut("Test continuing after temporary error"); fb = testSimplePipe("SC|FAIL\nSC|SLEEP|500\n", 500, -1, 2, 0, 2, 1, 0, 0, 0, 0); Log.consoleOut("Test complex situation"); fb = testSimplePipe("[T100ms]SC|ECHO|1\n" + "SC|FAIL|UnknownCommand\n" + "[T300msP10]SC|ECHO|2\n" + "[P10T300ms]SC|ECHO|3\n" + "[P05T400ms]SC|ECHO|4\n" + "[P05T400ms]SC|SLEEP|600\n" + "[T400ms]SC|FAIL|Drop\n" + "SC|FAIL|Drop\n" + "InvalidInputßßß\n" + "SC|FAIL|Drop\n" + "[T550ms]SC|FAIL|Drop\n" + "[T600msP05]SC|ECHO|I'm late\n" + "[P05]SC|ECHO|5\n" + "[T1100msP05]SC|ECHO|6\n" + "[T1200ms]SC|SLEEP|300\n" + "[P99T1350ms]SC|ECHO|7\n", 1350, -1, 15, 0, 11, 2, 0, 1, 4, 1); Log.consoleOut("Test timing"); testSimplePipe("SC|ECHO|$ELAPSED=0?\n" + "[T150ms]SC|SLEEP|200\n" + "SC|ECHO|$ELAPSED=350?\n" + "[T450msP10]SC|ECHO|$ELAPSED=450?\n" + "[T550ms]SC|ECHO|$ELAPSED=550?\n" + "[T650ms]SC|ECHO|$ELAPSED=650?\n" + "[T700ms]SC|ECHO|$ELAPSED=700?\n" + "[T750ms]SC|ECHO|$ELAPSED=750?\n" + "[T775ms]SC|ECHO|$ELAPSED=775?\n" + "[T800ms]SC|ECHO|$ELAPSED=800?\n" + "[T825ms]SC|ECHO|$ELAPSED=825?\n" + "[T850ms]SC|ECHO|$ELAPSED=850?\n" + "[T860ms]SC|ECHO|$ELAPSED=860?\n" + "[T870ms]SC|ECHO|$ELAPSED=870?\n" + "[T880ms]SC|ECHO|$ELAPSED=880?\n" + "[T1000ms]SC|ECHO|$ELAPSED=1000?\n" + "SC|ECHO|$ELAPSED=1000+<10?\n" + "SC|ECHO|$ELAPSED=1000+<20?\n" + "SC|ECHO|$ELAPSED=1000+<30?\n", 450, -1, 19, 0, 19, 0, 0, 0, 0, 0); Log.consoleOut("Test error handling (two inputs, first one fails)"); Input in1, in2; Output out1, out2; p.reset(); p.addInput(in1 = new StaticInput("FAILURE")); p.addInput(in2 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new InternalCommandOutput()); in1.connectToPipePart(out1); in2.connectToPipePart(out1); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); Log.consoleOut("Test error handling (converter fails)"); Log.consoleOut("TODO"); // TODO ENH converter fails => output unconverted Log.consoleOut("Test error handling (sole output fails)"); final File tmpFile = File.createTempFile("PipeTest", null); p.reset(); p.addInput(in1 = new StaticInput("[T1s]\n[T8sP10]\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); in1.connectToPipePart(out1); tmpFile.delete(); tmpFile.mkdir(); fb = testSimplePipe(p, 0, 900, 2, 0, 0, 0, 1, 0, 0, 0); tmpFile.delete(); Log.consoleOut("Test error handling (two outputs, first one fails)"); p.reset(); p.addInput(in1 = new StaticInput("SC|ECHO|Second is working\n")); p.addOutput(out1 = new FileOutput(tmpFile, PrintType.Ascii)); p.addOutput(out2 = new InternalCommandOutput()); in1.connectToPipePart(out1); in1.connectToPipePart(out2); tmpFile.mkdir(); fb = testSimplePipe(p, -1, -1, 1, 0, 1, 0, 1, 0, 0, 0); tmpFile.delete(); }
diff --git a/src/com/morphoss/acal/database/cachemanager/requests/CRObjectsInMonthByDay.java b/src/com/morphoss/acal/database/cachemanager/requests/CRObjectsInMonthByDay.java index 1d14236..df1a82f 100644 --- a/src/com/morphoss/acal/database/cachemanager/requests/CRObjectsInMonthByDay.java +++ b/src/com/morphoss/acal/database/cachemanager/requests/CRObjectsInMonthByDay.java @@ -1,146 +1,148 @@ package com.morphoss.acal.database.cachemanager.requests; import java.util.ArrayList; import java.util.HashMap; import java.util.TimeZone; import android.content.ContentValues; import android.util.Log; import com.morphoss.acal.Constants; import com.morphoss.acal.acaltime.AcalDateRange; import com.morphoss.acal.acaltime.AcalDateTime; import com.morphoss.acal.database.cachemanager.CacheManager; import com.morphoss.acal.database.cachemanager.CacheManager.CacheTableManager; import com.morphoss.acal.database.cachemanager.CacheObject; import com.morphoss.acal.database.cachemanager.CacheProcessingException; import com.morphoss.acal.database.cachemanager.CacheRequestWithResponse; import com.morphoss.acal.database.cachemanager.CacheResponse; import com.morphoss.acal.database.cachemanager.CacheResponseListener; /** * A CacheRequest that returns a Map CacheObjects that occur in the specified month. * The Map Keys are Days of the Month, the values are lists of events. * * To get the result you should pass in a CacheResponseListenr of the type ArrayList&lt;CacheObject&gt; * If you don't care about the result (e.g. your forcing a window size change) you may pass a null callback. * * @author Chris Noldus * */ public class CRObjectsInMonthByDay extends CacheRequestWithResponse<HashMap<Short,ArrayList<CacheObject>>> { private int month; private int year; private String objectType = null; public static final String TAG = "aCal CRObjectsInMonthByDay"; //metrics private long construct =-1; private long pstart=-1; private long qstart=-1; private long qend=-1; private long pend=-1; /** * Request all for the month provided. Pass the result to the callback provided * @param month * @param year * @param callBack */ public CRObjectsInMonthByDay(int month, int year, CacheResponseListener<HashMap<Short,ArrayList<CacheObject>>> callBack) { super(callBack); construct = System.currentTimeMillis(); this.month = month; this.year = year; } /** * Request all VEVENT CacheObjects for the month provided. Pass the result to the callback provided * @param month * @param year * @param callBack */ public static CRObjectsInMonthByDay EventsInMonthByDay(int month, int year, CacheResponseListener<HashMap<Short,ArrayList<CacheObject>>> callBack) { CRObjectsInMonthByDay result = new CRObjectsInMonthByDay(month,year,callBack); result.objectType = CacheTableManager.RESOURCE_TYPE_VEVENT; return result; } @Override public void process(CacheTableManager processor) throws CacheProcessingException { pstart = System.currentTimeMillis(); final HashMap<Short,ArrayList<CacheObject>> result = new HashMap<Short,ArrayList<CacheObject>>(); AcalDateTime start = new AcalDateTime( year, month, 1, 0, 0, 0, TimeZone.getDefault().getID()); AcalDateTime end = start.clone().addMonths(1).applyLocalTimeZone(); AcalDateRange range = new AcalDateRange(start,end); if (!processor.checkWindow(range)) { //Wait give up - caller can decide to rerequest or wait for cachechanged notification this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); return; } qstart = System.currentTimeMillis(); ArrayList<ContentValues> data = processor.queryInRange(range,objectType); qend = System.currentTimeMillis(); int daysInMonth = start.getActualMaximum(AcalDateTime.DAY_OF_MONTH); for (ContentValues value : data ) { try { CacheObject co = CacheObject.fromContentValues(value); start = co.getStartDateTime(); end = co.getEndDateTime().addSeconds(-1); if ( start == null ) start = end; if ( start == null ) continue; if ( end == null ) end = start; + if (start.getMonth() < month) start.setMonthDay(1); + if (end.getMonth() > month) end.setMonthDay(-1); for( short dayOfMonth = start.getMonthDay() ; dayOfMonth <= (end.getMonthDay() < start.getMonthDay() ? daysInMonth : end.getMonthDay()) ; dayOfMonth++ ) { if ( !result.containsKey(dayOfMonth) ) result.put(dayOfMonth, new ArrayList<CacheObject>()); result.get(dayOfMonth).add(co); } } catch( Exception e) { Log.w(TAG,Log.getStackTraceString(e)); } } this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); } private void printMetrics() { long total = pend-construct; long process = pend-pstart; long queuetime = pstart-construct; long query = qend-qstart; if ( CacheManager.DEBUG ) Log.println(Constants.LOGD, TAG, String.format("Metrics: Queue Time:%5d, Process Time:%5d, Query Time:%4d, Total Time:%6d", queuetime, process, query, total) ); } /** * This class represents the response from a CRObjectsInMonthByDay Request. It will be passed to the callback if one was provided. * @author Chris Noldus * * @param <E> */ public class CREventsInMonthByDayResponse<E extends HashMap<Short,ArrayList<CacheObject>>> implements CacheResponse<HashMap<Short,ArrayList<CacheObject>>> { private HashMap<Short,ArrayList<CacheObject>> result; public CREventsInMonthByDayResponse(HashMap<Short,ArrayList<CacheObject>> result) { this.result = result; } public HashMap<Short,ArrayList<CacheObject>> result() { return this.result; } } }
true
true
public void process(CacheTableManager processor) throws CacheProcessingException { pstart = System.currentTimeMillis(); final HashMap<Short,ArrayList<CacheObject>> result = new HashMap<Short,ArrayList<CacheObject>>(); AcalDateTime start = new AcalDateTime( year, month, 1, 0, 0, 0, TimeZone.getDefault().getID()); AcalDateTime end = start.clone().addMonths(1).applyLocalTimeZone(); AcalDateRange range = new AcalDateRange(start,end); if (!processor.checkWindow(range)) { //Wait give up - caller can decide to rerequest or wait for cachechanged notification this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); return; } qstart = System.currentTimeMillis(); ArrayList<ContentValues> data = processor.queryInRange(range,objectType); qend = System.currentTimeMillis(); int daysInMonth = start.getActualMaximum(AcalDateTime.DAY_OF_MONTH); for (ContentValues value : data ) { try { CacheObject co = CacheObject.fromContentValues(value); start = co.getStartDateTime(); end = co.getEndDateTime().addSeconds(-1); if ( start == null ) start = end; if ( start == null ) continue; if ( end == null ) end = start; for( short dayOfMonth = start.getMonthDay() ; dayOfMonth <= (end.getMonthDay() < start.getMonthDay() ? daysInMonth : end.getMonthDay()) ; dayOfMonth++ ) { if ( !result.containsKey(dayOfMonth) ) result.put(dayOfMonth, new ArrayList<CacheObject>()); result.get(dayOfMonth).add(co); } } catch( Exception e) { Log.w(TAG,Log.getStackTraceString(e)); } } this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); }
public void process(CacheTableManager processor) throws CacheProcessingException { pstart = System.currentTimeMillis(); final HashMap<Short,ArrayList<CacheObject>> result = new HashMap<Short,ArrayList<CacheObject>>(); AcalDateTime start = new AcalDateTime( year, month, 1, 0, 0, 0, TimeZone.getDefault().getID()); AcalDateTime end = start.clone().addMonths(1).applyLocalTimeZone(); AcalDateRange range = new AcalDateRange(start,end); if (!processor.checkWindow(range)) { //Wait give up - caller can decide to rerequest or wait for cachechanged notification this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); return; } qstart = System.currentTimeMillis(); ArrayList<ContentValues> data = processor.queryInRange(range,objectType); qend = System.currentTimeMillis(); int daysInMonth = start.getActualMaximum(AcalDateTime.DAY_OF_MONTH); for (ContentValues value : data ) { try { CacheObject co = CacheObject.fromContentValues(value); start = co.getStartDateTime(); end = co.getEndDateTime().addSeconds(-1); if ( start == null ) start = end; if ( start == null ) continue; if ( end == null ) end = start; if (start.getMonth() < month) start.setMonthDay(1); if (end.getMonth() > month) end.setMonthDay(-1); for( short dayOfMonth = start.getMonthDay() ; dayOfMonth <= (end.getMonthDay() < start.getMonthDay() ? daysInMonth : end.getMonthDay()) ; dayOfMonth++ ) { if ( !result.containsKey(dayOfMonth) ) result.put(dayOfMonth, new ArrayList<CacheObject>()); result.get(dayOfMonth).add(co); } } catch( Exception e) { Log.w(TAG,Log.getStackTraceString(e)); } } this.postResponse(new CREventsInMonthByDayResponse<HashMap<Short,ArrayList<CacheObject>>>(result)); pend = System.currentTimeMillis(); printMetrics(); }
diff --git a/src/com/ronx/coupon/server/Starter.java b/src/com/ronx/coupon/server/Starter.java index 54a0844..3691c07 100644 --- a/src/com/ronx/coupon/server/Starter.java +++ b/src/com/ronx/coupon/server/Starter.java @@ -1,50 +1,52 @@ package com.ronx.coupon.server; import com.ronx.coupon.entity.CouponSite; import com.ronx.coupon.service.CouponWebService; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import javax.xml.ws.Endpoint; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Starter { public static void main(String[] args) { CouponSite pokupon = null; try { pokupon = new CouponSite(new PropertiesConfiguration("properties/pokupon.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } int numConnections = 1000; CouponWebService couponService = new CouponWebService(); couponService.setCouponSite(pokupon); int pocessorsNum = Runtime.getRuntime().availableProcessors(); - ThreadPoolExecutor executor = new ThreadPoolExecutor(pocessorsNum, 5, 10L, TimeUnit.NANOSECONDS, new SynchronousQueue< Runnable >()); + ThreadPoolExecutor executor = new ThreadPoolExecutor( + pocessorsNum, 5, 10L, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(5, true), new ThreadPoolExecutor.CallerRunsPolicy() + ); CouponServer server; { server = new CouponServer(executor); server.runServer(); } ServerController serverController = new ServerController(server); // ExecutorService threads = Executors.newFixedThreadPool(numConnections); Endpoint endpoint; { endpoint = Endpoint.publish("http://localhost:8888/WS/coupon", couponService); endpoint.setExecutor(executor); } return; } }
true
true
public static void main(String[] args) { CouponSite pokupon = null; try { pokupon = new CouponSite(new PropertiesConfiguration("properties/pokupon.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } int numConnections = 1000; CouponWebService couponService = new CouponWebService(); couponService.setCouponSite(pokupon); int pocessorsNum = Runtime.getRuntime().availableProcessors(); ThreadPoolExecutor executor = new ThreadPoolExecutor(pocessorsNum, 5, 10L, TimeUnit.NANOSECONDS, new SynchronousQueue< Runnable >()); CouponServer server; { server = new CouponServer(executor); server.runServer(); } ServerController serverController = new ServerController(server); // ExecutorService threads = Executors.newFixedThreadPool(numConnections); Endpoint endpoint; { endpoint = Endpoint.publish("http://localhost:8888/WS/coupon", couponService); endpoint.setExecutor(executor); } return; }
public static void main(String[] args) { CouponSite pokupon = null; try { pokupon = new CouponSite(new PropertiesConfiguration("properties/pokupon.properties")); } catch (ConfigurationException e) { e.printStackTrace(); } int numConnections = 1000; CouponWebService couponService = new CouponWebService(); couponService.setCouponSite(pokupon); int pocessorsNum = Runtime.getRuntime().availableProcessors(); ThreadPoolExecutor executor = new ThreadPoolExecutor( pocessorsNum, 5, 10L, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<Runnable>(5, true), new ThreadPoolExecutor.CallerRunsPolicy() ); CouponServer server; { server = new CouponServer(executor); server.runServer(); } ServerController serverController = new ServerController(server); // ExecutorService threads = Executors.newFixedThreadPool(numConnections); Endpoint endpoint; { endpoint = Endpoint.publish("http://localhost:8888/WS/coupon", couponService); endpoint.setExecutor(executor); } return; }
diff --git a/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/PersistenceBundleExtender.java b/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/PersistenceBundleExtender.java index 10fbb96..7aaa6c9 100644 --- a/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/PersistenceBundleExtender.java +++ b/org.eclipse.gemini.jpa/src/org/eclipse/gemini/jpa/PersistenceBundleExtender.java @@ -1,372 +1,376 @@ /******************************************************************************* * Copyright (c) 2010 Oracle. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php. * You may elect to redistribute this code under either of these licenses. * * Contributors: * mkeith - Gemini JPA work ******************************************************************************/ package org.eclipse.gemini.jpa; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.Manifest; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleEvent; import org.osgi.framework.Constants; import org.osgi.framework.SynchronousBundleListener; import org.osgi.service.packageadmin.PackageAdmin; import org.eclipse.gemini.jpa.provider.OSGiJpaProvider; import static org.eclipse.gemini.jpa.GeminiUtil.*; /** * This extender can be used by a provider to listen for persistence unit * bundles and assign them to this provider if the unit is able to be assigned. */ public class PersistenceBundleExtender implements SynchronousBundleListener { /*================*/ /* Instance state */ /*================*/ // The provider associated with this extender OSGiJpaProvider osgiJpaProvider; // Utility class PersistenceUnitBundleUtil util; // Persistence units by bundle Map<Bundle, List<PUnitInfo>> unitsByBundle = Collections.synchronizedMap(new HashMap<Bundle, List<PUnitInfo>>()); // Just keep the bundle ids to prevent hard references to the bundles Set<Long> lazyBundles = new HashSet<Long>(); Set<Long> refreshingBundles = new HashSet<Long>(); /*==============*/ /* Constructors */ /*==============*/ public PersistenceBundleExtender() {} public PersistenceBundleExtender(OSGiJpaProvider provider) { this.osgiJpaProvider = provider; this.util = new PersistenceUnitBundleUtil(); } /*================================*/ /* API methods called by provider */ /*================================*/ /** * Start listening for bundle events to indicate the presence of * persistence unit bundles. */ public void startListening() { debug("GeminiExtender listening"); osgiJpaProvider.getBundleContext().addBundleListener(this); } /** * Stop listening to bundle events. */ public void stopListening() { debug("GeminiExtender no longer listening"); osgiJpaProvider.getBundleContext().removeBundleListener(this); } /** * Look for persistence unit bundles that are already installed. */ public void lookForExistingBundles() { // Look at the bundles that are already installed Bundle[] activeBundles = osgiJpaProvider.getBundleContext().getBundles(); debug("GeminiExtender looking at existing bundles: ", activeBundles); // Check if any are p-unit bundles for (Bundle b : activeBundles) { if (isPersistenceUnitBundle(b)) { // We found a persistence unit bundle. // Refresh it so it will go through the resolving state again and client // bundles that are waiting for the EMF service will get one if ((b.getState() != Bundle.INSTALLED) && (b.getState() != Bundle.UNINSTALLED)) { addToRefreshingBundles(b); PackageAdmin admin = getPackageAdmin(osgiJpaProvider.getBundleContext()); debug("GeminiExtender refreshing packages of bundle ", b); admin.refreshPackages(new Bundle[] { b }); } } } } /** * Generate a set of anchor interfaces for the packages in the p-units. * Create a fragment for them and install the fragment, attaching it to the * persistence unit bundle. * * @param b the persistence unit bundle * @param infos the collection of metadata for all of the persistence units * * @return The bundle object of the installed fragment */ public Bundle generateAndInstallFragment(Bundle b, Collection<PUnitInfo> infos) { debug("GeminiExtender generating fragment"); List<String> packageNames = util.uniquePackages(infos); List<byte[]> generatedClasses = util.generateAnchorInterfaces(packageNames, osgiJpaProvider.getAnchorClassName()); Manifest manifest = util.generateFragmentManifest(b); byte[] fragment = util.createFragment(manifest, packageNames, osgiJpaProvider.getAnchorClassName(), generatedClasses); debug("GeminiExtender finished generating fragment"); Bundle installedFragment = util.installFragment(b, osgiJpaProvider.getBundle(), fragment); debug("GeminiExtender installed fragment bundle: ", installedFragment); return installedFragment; } public Map<Bundle, List<PUnitInfo>> clearAllPUnitInfos() { Map<Bundle, List<PUnitInfo>> pUnitInfos = unitsByBundle; unitsByBundle = null; lazyBundles = null; refreshingBundles = null; return pUnitInfos; } /*============================*/ /* Additional Support Methods */ /*============================*/ /** * Go through the p-units in a given bundle and assign the ones that do * not have a provider, or have a provider specified as this one. * * @param b the bundle to look for p-units in */ public void tryAssigningPersistenceUnitsInBundle(Bundle b) { debug("GeminiExtender tryAssigningPersistenceUnitsInBundle: ", b); // If we have already assigned it then bail if (isAssigned(b)) { warning("Attempted to assign a bundle that was already assigned: ", b.toString()); return; } // Look for all of the persistence descriptor files in the bundle List<PersistenceDescriptorInfo> descriptorInfos = util.persistenceDescriptorInfos(b); // Do a partial parse of the descriptors Set<PUnitInfo> pUnitInfos = util.persistenceUnitInfoFromXmlFiles(descriptorInfos); // Cycle through each p-unit info and see if a provider was specified for (PUnitInfo info : pUnitInfos) { if ((info.getProvider() == null) || (osgiJpaProvider.getProviderClassName().equals(info.getProvider()))) { // We can be the provider; claim the p-unit and add it to our list info.setBundle(b); info.setAssignedProvider(osgiJpaProvider); addToBundleUnits(unitsByBundle, b, info); } } // If we found any that were for us then let the provider know List<PUnitInfo> unitsFound = unitsByBundle.get(b); if ((unitsFound != null) && (unitsFound.size() != 0)) { osgiJpaProvider.assignPersistenceUnitsInBundle(b, unitsByBundle.get(b)); } } /** * Unassign all of the p-units in a given bundle. * * @param b the bundle the p-units are in */ public void unassignPersistenceUnitsInBundle(Bundle b) { debug("GeminiExtender unassignPersistenceUnitsInBundle: ", b); List<PUnitInfo> infos = unitsByBundle.get(b); unitsByBundle.remove(b); removeFromLazyBundles(b); osgiJpaProvider.unassignPersistenceUnitsInBundle(b, infos); // Uninitialize the state of the p-unit for (PUnitInfo info : infos) { info.setAssignedProvider(null); info.setBundle(null); } } /** * Register the p-units of a given bundle. * * @param b the bundle the p-units are in */ public void registerPersistenceUnitsInBundle(Bundle b) { debug("GeminiExtender registerPersistenceUnitsInBundle: ", b); if (!isAssigned(b)) { warning("Register called on bundle " + b.getSymbolicName(), " but bundle was not assigned"); return; } if (areCompatibleBundles(b, osgiJpaProvider.getBundle())) { debug("GeminiExtender provider compatible with bundle: ", b); osgiJpaProvider.registerPersistenceUnits(unitsByBundle.get(b)); } else { warning("Cannot support bundle " + b.getSymbolicName() + " because it is not JPA-compatible with the assigned provider " + osgiJpaProvider.getProviderClassName() + ". This is because the " + "persistence unit bundle has resolved to a different javax.persistence " + "than the provider. \nTo fix this, uninstall one of the javax.persistence " + "bundles so that both the persistence unit bundle and the provider resolve " + "to the same javax.persistence package."); unassignPersistenceUnitsInBundle(b); // No point in updating/refreshing. // (It would likely just re-resolve to the same JPA interface package.) } } /** * Unregister the p-units of a given bundle. * * @param b the bundle the p-units are in */ public void unregisterPersistenceUnitsInBundle(Bundle b) { debug("GeminiExtender unregisterPersistenceUnitsInBundle: ", b); if (!isAssigned(b)) { warning("Unregister called on bundle " + b.getSymbolicName(), " but bundle was not assigned"); return; } osgiJpaProvider.unregisterPersistenceUnits(unitsByBundle.get(b)); } /*========================*/ /* BundleListener methods */ /*========================*/ public void bundleChanged(BundleEvent event) { // Only continue if it is a persistence unit bundle Bundle b = event.getBundle(); debug("Extender - bundle event, ", event); if (!isPersistenceUnitBundle(b)) return; // Process each event int eventType = event.getType(); if (eventType == BundleEvent.INSTALLED) { tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.LAZY_ACTIVATION) { if (isAssigned(b)) { lazyBundles.add(b.getBundleId()); registerPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.STARTING) { if (isAssigned(b)) { if (!isLazy(b)) { registerPersistenceUnitsInBundle(b); } } } else if (eventType == BundleEvent.STOPPING) { if (isAssigned(b)) { + // Fix for bug #342996 + if (isLazy(b)) { + removeFromLazyBundles(b); + } unregisterPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UNINSTALLED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UPDATED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.UNRESOLVED) { if (isRefreshing(b)) { // assign refreshing bundles tryAssigningPersistenceUnitsInBundle(b); removeFromRefreshingBundles(b); } } else { // RESOLVED, STARTED, STOPPED // Do nothing. } } /*================*/ /* Helper methods */ /*================*/ protected boolean isAssigned(Bundle b) { return unitsByBundle.containsKey(b); } protected boolean isLazy(Bundle b) { return lazyBundles.contains(b.getBundleId()); } protected boolean addToLazyBundles(Bundle b) { return lazyBundles.add(b.getBundleId()); } protected boolean removeFromLazyBundles(Bundle b) { return lazyBundles.remove(b.getBundleId()); } protected boolean isRefreshing(Bundle b) { return refreshingBundles.contains(b.getBundleId()); } protected void addToRefreshingBundles(Bundle b) { refreshingBundles.add(b.getBundleId()); } protected void removeFromRefreshingBundles(Bundle b) { refreshingBundles.remove(b.getBundleId()); } protected void addToBundleUnits(Map<Bundle,List<PUnitInfo>> map, Bundle b, PUnitInfo info) { if (!map.containsKey(b)) map.put(b, new ArrayList<PUnitInfo>()); map.get(b).add(info); } public boolean isPersistenceUnitBundle(Bundle b) { return b.getHeaders().get("Meta-Persistence") != null; } public boolean isLazyActivatedBundle(Bundle b) { String policy = (String) b.getHeaders().get(Constants.BUNDLE_ACTIVATIONPOLICY); return (policy != null) && (policy.equals(Constants.ACTIVATION_LAZY)); } /** * Return whether or not the persistence unit bundle * has a consistent JPA interface class space with the provider bundle. * This method must be called after both bundles have been resolved. */ public boolean areCompatibleBundles(Bundle pUnitBundle, Bundle providerBundle) { try { debug("GeminiExtender checking bundle compatibility of: ", pUnitBundle); Class<?> pUnitClass = pUnitBundle.loadClass("javax.persistence.Entity"); Class<?> providerClass = providerBundle.loadClass("javax.persistence.Entity"); return pUnitClass.getClassLoader() == providerClass.getClassLoader(); } catch (ClassNotFoundException cnfEx) { // If one of the bundles does not have the class in its class space // then by definition the two are consistent w.r.t. that package return true; } } public void stop(BundleContext context) throws Exception { } public void start(BundleContext context) throws Exception { } }
true
true
public void bundleChanged(BundleEvent event) { // Only continue if it is a persistence unit bundle Bundle b = event.getBundle(); debug("Extender - bundle event, ", event); if (!isPersistenceUnitBundle(b)) return; // Process each event int eventType = event.getType(); if (eventType == BundleEvent.INSTALLED) { tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.LAZY_ACTIVATION) { if (isAssigned(b)) { lazyBundles.add(b.getBundleId()); registerPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.STARTING) { if (isAssigned(b)) { if (!isLazy(b)) { registerPersistenceUnitsInBundle(b); } } } else if (eventType == BundleEvent.STOPPING) { if (isAssigned(b)) { unregisterPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UNINSTALLED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UPDATED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.UNRESOLVED) { if (isRefreshing(b)) { // assign refreshing bundles tryAssigningPersistenceUnitsInBundle(b); removeFromRefreshingBundles(b); } } else { // RESOLVED, STARTED, STOPPED // Do nothing. } }
public void bundleChanged(BundleEvent event) { // Only continue if it is a persistence unit bundle Bundle b = event.getBundle(); debug("Extender - bundle event, ", event); if (!isPersistenceUnitBundle(b)) return; // Process each event int eventType = event.getType(); if (eventType == BundleEvent.INSTALLED) { tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.LAZY_ACTIVATION) { if (isAssigned(b)) { lazyBundles.add(b.getBundleId()); registerPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.STARTING) { if (isAssigned(b)) { if (!isLazy(b)) { registerPersistenceUnitsInBundle(b); } } } else if (eventType == BundleEvent.STOPPING) { if (isAssigned(b)) { // Fix for bug #342996 if (isLazy(b)) { removeFromLazyBundles(b); } unregisterPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UNINSTALLED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } } else if (eventType == BundleEvent.UPDATED) { if (isAssigned(b)) { unassignPersistenceUnitsInBundle(b); } tryAssigningPersistenceUnitsInBundle(b); } else if (eventType == BundleEvent.UNRESOLVED) { if (isRefreshing(b)) { // assign refreshing bundles tryAssigningPersistenceUnitsInBundle(b); removeFromRefreshingBundles(b); } } else { // RESOLVED, STARTED, STOPPED // Do nothing. } }
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1479Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1479Test.java index a631694b6..5498b4fed 100644 --- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1479Test.java +++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1479Test.java @@ -1,92 +1,92 @@ /******************************************************************************* * 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.jsf.vpe.jsf.test.jbide; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.WorkspaceJob; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.wst.xml.core.internal.provisional.format.FormatProcessorXML; import org.jboss.tools.jsf.vpe.jsf.test.JsfAllTests; import org.jboss.tools.jst.jsp.jspeditor.JSPMultiPageEditor; import org.jboss.tools.vpe.ui.test.TestUtil; import org.jboss.tools.vpe.ui.test.VpeTest; /** * @author Max Areshkau * * test for JBIDE-1479 * */ public class JBIDE1479Test extends VpeTest { public static final String TEST_PAGE_NAME = "JBIDE/1479/employee.xhtml"; //$NON-NLS-1$ public JBIDE1479Test(String name) { super(name); } public void testJBIDE1479() throws Throwable { // wait setException(null); // get test page path final IFile file = (IFile) TestUtil.getComponentPath( TEST_PAGE_NAME, JsfAllTests.IMPORT_PROJECT_NAME); assertNotNull("Could not open specified file " + TEST_PAGE_NAME, //$NON-NLS-1$ file); IEditorInput input = new FileEditorInput(file); assertNotNull("Editor input is null", input); //$NON-NLS-1$ JSPMultiPageEditor part = openEditor(input); - TestUtil.waitForIdle(); + TestUtil.waitForIdle(120*1000); assertNotNull(part); Job job = new WorkspaceJob("Test JBIDE-1479"){ //$NON-NLS-1$ public IStatus runInWorkspace(IProgressMonitor monitor) { try { new FormatProcessorXML().formatFile(file); }catch (Throwable exception){ /* * Here we test JBIDE-1479, if eclipse crashed we won't get any * exception, so we just ignore it's. */ } return Status.OK_STATUS; } }; job.setPriority(Job.SHORT); job.schedule(0L); job.join(); TestUtil.waitForIdle(15*1000*60); TestUtil.delay(1000L); closeEditors(); /* * we ignore this code, because we are testint JBIDE-1479, * it's test fot crash of eclipse.And if we modifying content from non-ui thread, we almost * always will get SWTException 'access violation'. */ // if(getException()!=null) { // throw getException(); // } } }
true
true
public void testJBIDE1479() throws Throwable { // wait setException(null); // get test page path final IFile file = (IFile) TestUtil.getComponentPath( TEST_PAGE_NAME, JsfAllTests.IMPORT_PROJECT_NAME); assertNotNull("Could not open specified file " + TEST_PAGE_NAME, //$NON-NLS-1$ file); IEditorInput input = new FileEditorInput(file); assertNotNull("Editor input is null", input); //$NON-NLS-1$ JSPMultiPageEditor part = openEditor(input); TestUtil.waitForIdle(); assertNotNull(part); Job job = new WorkspaceJob("Test JBIDE-1479"){ //$NON-NLS-1$ public IStatus runInWorkspace(IProgressMonitor monitor) { try { new FormatProcessorXML().formatFile(file); }catch (Throwable exception){ /* * Here we test JBIDE-1479, if eclipse crashed we won't get any * exception, so we just ignore it's. */ } return Status.OK_STATUS; } }; job.setPriority(Job.SHORT); job.schedule(0L); job.join(); TestUtil.waitForIdle(15*1000*60); TestUtil.delay(1000L); closeEditors(); /* * we ignore this code, because we are testint JBIDE-1479, * it's test fot crash of eclipse.And if we modifying content from non-ui thread, we almost * always will get SWTException 'access violation'. */ // if(getException()!=null) { // throw getException(); // } }
public void testJBIDE1479() throws Throwable { // wait setException(null); // get test page path final IFile file = (IFile) TestUtil.getComponentPath( TEST_PAGE_NAME, JsfAllTests.IMPORT_PROJECT_NAME); assertNotNull("Could not open specified file " + TEST_PAGE_NAME, //$NON-NLS-1$ file); IEditorInput input = new FileEditorInput(file); assertNotNull("Editor input is null", input); //$NON-NLS-1$ JSPMultiPageEditor part = openEditor(input); TestUtil.waitForIdle(120*1000); assertNotNull(part); Job job = new WorkspaceJob("Test JBIDE-1479"){ //$NON-NLS-1$ public IStatus runInWorkspace(IProgressMonitor monitor) { try { new FormatProcessorXML().formatFile(file); }catch (Throwable exception){ /* * Here we test JBIDE-1479, if eclipse crashed we won't get any * exception, so we just ignore it's. */ } return Status.OK_STATUS; } }; job.setPriority(Job.SHORT); job.schedule(0L); job.join(); TestUtil.waitForIdle(15*1000*60); TestUtil.delay(1000L); closeEditors(); /* * we ignore this code, because we are testint JBIDE-1479, * it's test fot crash of eclipse.And if we modifying content from non-ui thread, we almost * always will get SWTException 'access violation'. */ // if(getException()!=null) { // throw getException(); // } }
diff --git a/src/savant/util/swing/ProgressPanel.java b/src/savant/util/swing/ProgressPanel.java index a38382cb..5898d170 100644 --- a/src/savant/util/swing/ProgressPanel.java +++ b/src/savant/util/swing/ProgressPanel.java @@ -1,83 +1,84 @@ /* * Copyright 2010-2011 University of Toronto * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package savant.util.swing; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import savant.view.icon.SavantIconFactory; /** * Dorky little class which puts up a progress-bar. Used when it is taking a while * to render a GraphPane load a track. * * @author tarkvara */ public class ProgressPanel extends JPanel { private JButton cancelButton; private JLabel message; /** * Create a new ProgressPanel. The bar is indeterminate because we have no idea * how long a track will take to load. * @param cancellationListener if non-null, a Cancel button will be added which will fire this listener */ public ProgressPanel(ActionListener cancellationListener) { super(new GridBagLayout()); setOpaque(false); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(12, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; gbc.gridwidth = 1; JProgressBar bar = new JProgressBar(); bar.setIndeterminate(true); Dimension prefSize = bar.getPreferredSize(); prefSize.width = 240; bar.setPreferredSize(prefSize); add(bar, gbc); if (cancellationListener != null) { cancelButton = new JButton(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_LIGHT)); + cancelButton.setContentAreaFilled(false); cancelButton.setBorderPainted(false); cancelButton.setRolloverIcon(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_DARK)); cancelButton.addActionListener(cancellationListener); gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 0.0; add(cancelButton, gbc); } message = new JLabel(); gbc.insets = new Insets(3, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; add(message, gbc); } public void setMessage(String msg) { message.setText(msg); } }
true
true
public ProgressPanel(ActionListener cancellationListener) { super(new GridBagLayout()); setOpaque(false); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(12, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; gbc.gridwidth = 1; JProgressBar bar = new JProgressBar(); bar.setIndeterminate(true); Dimension prefSize = bar.getPreferredSize(); prefSize.width = 240; bar.setPreferredSize(prefSize); add(bar, gbc); if (cancellationListener != null) { cancelButton = new JButton(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_LIGHT)); cancelButton.setBorderPainted(false); cancelButton.setRolloverIcon(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_DARK)); cancelButton.addActionListener(cancellationListener); gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 0.0; add(cancelButton, gbc); } message = new JLabel(); gbc.insets = new Insets(3, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; add(message, gbc); }
public ProgressPanel(ActionListener cancellationListener) { super(new GridBagLayout()); setOpaque(false); GridBagConstraints gbc = new GridBagConstraints(); gbc.insets = new Insets(12, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; gbc.gridwidth = 1; JProgressBar bar = new JProgressBar(); bar.setIndeterminate(true); Dimension prefSize = bar.getPreferredSize(); prefSize.width = 240; bar.setPreferredSize(prefSize); add(bar, gbc); if (cancellationListener != null) { cancelButton = new JButton(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_LIGHT)); cancelButton.setContentAreaFilled(false); cancelButton.setBorderPainted(false); cancelButton.setRolloverIcon(SavantIconFactory.getInstance().getIcon(SavantIconFactory.StandardIcon.CLOSE_DARK)); cancelButton.addActionListener(cancellationListener); gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 0.0; add(cancelButton, gbc); } message = new JLabel(); gbc.insets = new Insets(3, 0, 3, 0); gbc.fill = GridBagConstraints.HORIZONTAL; add(message, gbc); }
diff --git a/MCS_TicTacToe/src/UI/GameBoardDisplay.java b/MCS_TicTacToe/src/UI/GameBoardDisplay.java index f0870f2..8e1769f 100644 --- a/MCS_TicTacToe/src/UI/GameBoardDisplay.java +++ b/MCS_TicTacToe/src/UI/GameBoardDisplay.java @@ -1,395 +1,395 @@ //BEGIN FILE GameBoardDisplay.java package UI; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import model.*; /** * The UI for a game session * @author Mustache Cash Stash * @version 0.9 */ //BEGIN CLASS GameBoardDisplay public class GameBoardDisplay extends JPanel implements ActionListener { public static String initialUser1, initialUser2, initialModeName; /** * Builds and then draws the UI for a session of TTT * @param user1 The name of player 1 * @param user2 The name of player 2 * @param modeName The mode to display on the window. */ //BEGIN CONSTRUCTOR public GameBoardDisplay(String user1, String user2, String modeName) public GameBoardDisplay(String user1, String user2, String modeName) { // keep track of the initial usernames and game mode in case if we to restart the game initialUser1 = user1; initialUser2 = user2; initialModeName = modeName; boardModel = new GameboardImp(); setLayout(new BorderLayout()); // This is the window that will be shown boardFrame = constructFrame(modeName); // get players String[] players = Game.getPlayers(user1, user2); player1 = players[0]; player2 = players[1]; // create a header that holds the image JPanel header = new JPanel(); header.add(new JLabel(new ImageIcon("bg.png"))); header.setBackground(Color.BLACK); boardPanel = constructBoardPannel(); cells = constructCells(); boardPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); - // create 3 buttons + // create buttons JButton button1 = new JButton("Restart Game"); JButton button2 = new JButton("Quit Game"); // set action command to buttons button1.setActionCommand("restart"); button2.setActionCommand("quit"); // set action listeners to buttons button1.addActionListener(this); button2.addActionListener(this); // add the board label to the lower side of the window buttonsPanel = new JPanel(); buttonsPanel.setLayout(new GridLayout(7,1)); buttonsPanel.setBackground(Color.BLACK); buttonsPanel.setPreferredSize(new Dimension(300, 100)); buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); gameStatus = new JLabel(player1 + "'s Turn"); gameStatus.setFont(new Font("Serif", Font.BOLD, 18)); gameStatus.setForeground(Color.WHITE); gameStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add a label to the top of the window JLabel title = new JLabel(player1 + " vs " + player2); title.setFont(new Font("Serif", Font.BOLD, 28)); title.setForeground(Color.ORANGE); buttonsPanel.add(title); buttonsPanel.add(gameStatus); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(button1); buttonsPanel.add(button2); moveStatus = new JLabel("Ready to play!"); moveStatus.setFont(new Font("Serif", Font.BOLD, 18)); moveStatus.setForeground(Color.CYAN); moveStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add all the parts to the window add(header, BorderLayout.NORTH); add(boardPanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.EAST); add(moveStatus, BorderLayout.SOUTH); boardFrame.setVisible(true); setBackground(Color.BLACK); } //END CONSTRUCTOR public GameBoardDisplay(String user1, String user2, String modeName) /** * actionPerformed * * Listens to actions and act accordingly * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent event) { // get the action of the button String command = event.getActionCommand(); // if the restart game button is clicked if(command.equalsIgnoreCase("restart")) { new GameBoardDisplay(initialUser1, initialUser2, initialModeName); boardFrame.dispose(); } // if the quit game button is clicked else { boardFrame.dispose(); } } /** * A request from a client to place a piece on the Gameboard at a certain position. * Passes this request to the model * @param xPosition The x (horizontal) coordinate of the requested space to occupy * @param yPosition The y (vertical) coordinate of the requested space to occupy * @return Whether the move request was successful in updating the Gameboard. */ //BEGIN METHOD public boolean attemptMove(int xPosition, int yPosition) public boolean attemptMove(int xPosition, int yPosition) { boolean result = false; if(boardModel.getResult() == GameResult.PENDING) { if(boardModel.xsTurn()) { result = boardModel.requestMove(xPosition, yPosition, PlaceValue.X); if(result) { displayNewPiece(xPosition, yPosition, xPiece); } } else if(boardModel.osTurn()) { result = boardModel.requestMove(xPosition, yPosition, PlaceValue.O); if(result) { displayNewPiece(xPosition, yPosition, oPiece); } } } GameResult status = boardModel.getResult(); if (status == GameResult.PENDING) { if(boardModel.xsTurn()) { displayNewGameStatus(player1 + "'s Turn"); } else { displayNewGameStatus(player2 + "'s Turn"); } } else if (status == GameResult.CAT) { displayNewGameStatus("Cat's game!"); } else if (status == GameResult.OWIN) { displayNewGameStatus(player2 + " Wins!"); } else if (status == GameResult.XWIN) { displayNewGameStatus(player1 + " Wins!"); } return result; } //END METHOD public boolean attemptMove(int xPosition, int yPosition) static final long serialVersionUID = 0L; // to shut up Eclipse /** * Draws the selected Icon at the selected location on the board. * Called whenever a new piece is placed * @param xPosition The x (horizontal) coordinate of the requested space to occupy * @param yPosition The y (vertical) coordinate of the requested space to occupy * @param piece The Icon to draw at the selected space */ //BEGIN METHOD private void displayNewPiece(int xPosition, int yPosition, Icon piece) private void displayNewPiece(int xPosition, int yPosition, Icon piece) { cells[xPosition][yPosition].setIcon(piece); boardPanel.revalidate(); } //END METHOD private void displayNewPiece(int xPosition, int yPosition, Icon piece) /** * Draw the selected message at the bottom of the board * This space is used to display the status of a move. * Called whenever a successful move occurs * @param message the new move status message to display. */ //BEGIN METHOD private void displayNewMoveStatus(String message) private void displayNewMoveStatus(String message) { moveStatus.setText(message); boardPanel.revalidate(); } //END METHOD private void displayNewMoveStatus(String message) /** * Draw the selected message on the side of the board. * This space is used to display the status of the game. * Called whenever a successful move occurs. * @param message the new game status message to display */ //BEGIN METHOD private void displayNewGameStatus(String message) private void displayNewGameStatus(String message) { gameStatus.setText(message); boardPanel.revalidate(); } //END METHOD private void displayNewGameStatus(String message) /** * Construct the JPanel containing the cells * @return The panel constructed */ //BEGIN METHOD private JPanel constructBoardPannel() private JPanel constructBoardPannel() { JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3,3)); panel.setBackground(Color.BLACK); panel.setPreferredSize(new Dimension(300, 300)); return panel; } //END METHOD private JPanel constructBoardPannel() /** * Construct the content JFrame for the window * @param modeName The mode (single/multiplayer) used as part of the window title * @return The frame constructed */ //BEGIN METHOD private JFrame constructFrame(String modeName) private JFrame constructFrame(String modeName) { JFrame frame = new JFrame ("Tic Tac Toe - " + modeName + " Mode"); // set the size of the window frame.setSize(700, 600); // Place the window in the middle of the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension gameFrame2Size = frame.getSize(); if (gameFrame2Size.height > screenSize.height) { gameFrame2Size.height = screenSize.height; } if (gameFrame2Size.width > screenSize.width) { gameFrame2Size.width = screenSize.width; } frame.setLocation((screenSize.width - gameFrame2Size.width) / 2, (screenSize.height - gameFrame2Size.height) / 2); // set close operation frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set window not resizable frame.setResizable(true); frame.setIconImage(new ImageIcon("mord.png").getImage()); //If we want favicon for our window. // show the window frame.setContentPane(this); return frame; } //END METHOD private JFrame constructFrame(String modeName) /** * Constructs the JLabel cells that represent individual board spaces in the UI * @return the array of game spaces */ //BEGIN METHOD private JLabel[][] constructCells() private JLabel[][] constructCells() { JLabel[][] cellArray = new JLabel[3][3]; Border whiteLine = BorderFactory.createLineBorder(Color.WHITE); //create cells JLabel cell_00 = new JLabel (); cell_00.setBorder(whiteLine); cellArray[0][0] = cell_00; JLabel cell_01 = new JLabel (); cell_01.setBorder(whiteLine); cellArray[0][1] = cell_01; JLabel cell_02 = new JLabel (); cell_02.setBorder(whiteLine); cellArray[0][2] = cell_02; JLabel cell_10 = new JLabel (); cell_10.setBorder(whiteLine); cellArray[1][0] = cell_10; JLabel cell_11 = new JLabel (); cell_11.setBorder(whiteLine); cellArray[1][1] = cell_11; JLabel cell_12 = new JLabel (); cell_12.setBorder(whiteLine); cellArray[1][2] = cell_12; JLabel cell_20 = new JLabel (); cell_20.setBorder(whiteLine); cellArray[2][0] = cell_20; JLabel cell_21 = new JLabel (); cell_21.setBorder(whiteLine); cellArray[2][1] = cell_21; JLabel cell_22 = new JLabel (); cell_22.setBorder(whiteLine); cellArray[2][2] = cell_22; // create a listener for all cells MouseListener listener00 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(0,0))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener01 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(0,1))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener02 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(0,2))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener10 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(1,0))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener11 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(1,1))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener12 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(1,2))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener20 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(2,0))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener21 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(2,1))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; MouseListener listener22 = new MouseAdapter(){public void mouseClicked(MouseEvent event){if(attemptMove(2,2))displayNewMoveStatus("Good move!"); else displayNewMoveStatus("Can't place a piece there!");}}; // link listeners to cells cell_00.addMouseListener(listener00); cell_01.addMouseListener(listener01); cell_02.addMouseListener(listener02); cell_10.addMouseListener(listener10); cell_11.addMouseListener(listener11); cell_12.addMouseListener(listener12); cell_20.addMouseListener(listener20); cell_21.addMouseListener(listener21); cell_22.addMouseListener(listener22); // add cells to the board boardPanel.add(cell_00); boardPanel.add(cell_01); boardPanel.add(cell_02); boardPanel.add(cell_10); boardPanel.add(cell_11); boardPanel.add(cell_12); boardPanel.add(cell_20); boardPanel.add(cell_21); boardPanel.add(cell_22); return cellArray; } //END METHOD private JLabel[][] constructCells() private static Icon xPiece = new ImageIcon("X.png"); private static Icon oPiece = new ImageIcon("O.png"); private Gameboard boardModel; private JLabel[][] cells; private JPanel boardPanel; private JFrame boardFrame; private JLabel moveStatus; private JPanel buttonsPanel; private JLabel gameStatus; private String player1; private String player2; } //END CLASS GameBoardDisplay //END FILE GameBoardDisplay.java
true
true
public GameBoardDisplay(String user1, String user2, String modeName) { // keep track of the initial usernames and game mode in case if we to restart the game initialUser1 = user1; initialUser2 = user2; initialModeName = modeName; boardModel = new GameboardImp(); setLayout(new BorderLayout()); // This is the window that will be shown boardFrame = constructFrame(modeName); // get players String[] players = Game.getPlayers(user1, user2); player1 = players[0]; player2 = players[1]; // create a header that holds the image JPanel header = new JPanel(); header.add(new JLabel(new ImageIcon("bg.png"))); header.setBackground(Color.BLACK); boardPanel = constructBoardPannel(); cells = constructCells(); boardPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); // create 3 buttons JButton button1 = new JButton("Restart Game"); JButton button2 = new JButton("Quit Game"); // set action command to buttons button1.setActionCommand("restart"); button2.setActionCommand("quit"); // set action listeners to buttons button1.addActionListener(this); button2.addActionListener(this); // add the board label to the lower side of the window buttonsPanel = new JPanel(); buttonsPanel.setLayout(new GridLayout(7,1)); buttonsPanel.setBackground(Color.BLACK); buttonsPanel.setPreferredSize(new Dimension(300, 100)); buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); gameStatus = new JLabel(player1 + "'s Turn"); gameStatus.setFont(new Font("Serif", Font.BOLD, 18)); gameStatus.setForeground(Color.WHITE); gameStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add a label to the top of the window JLabel title = new JLabel(player1 + " vs " + player2); title.setFont(new Font("Serif", Font.BOLD, 28)); title.setForeground(Color.ORANGE); buttonsPanel.add(title); buttonsPanel.add(gameStatus); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(button1); buttonsPanel.add(button2); moveStatus = new JLabel("Ready to play!"); moveStatus.setFont(new Font("Serif", Font.BOLD, 18)); moveStatus.setForeground(Color.CYAN); moveStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add all the parts to the window add(header, BorderLayout.NORTH); add(boardPanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.EAST); add(moveStatus, BorderLayout.SOUTH); boardFrame.setVisible(true); setBackground(Color.BLACK); }
public GameBoardDisplay(String user1, String user2, String modeName) { // keep track of the initial usernames and game mode in case if we to restart the game initialUser1 = user1; initialUser2 = user2; initialModeName = modeName; boardModel = new GameboardImp(); setLayout(new BorderLayout()); // This is the window that will be shown boardFrame = constructFrame(modeName); // get players String[] players = Game.getPlayers(user1, user2); player1 = players[0]; player2 = players[1]; // create a header that holds the image JPanel header = new JPanel(); header.add(new JLabel(new ImageIcon("bg.png"))); header.setBackground(Color.BLACK); boardPanel = constructBoardPannel(); cells = constructCells(); boardPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); // create buttons JButton button1 = new JButton("Restart Game"); JButton button2 = new JButton("Quit Game"); // set action command to buttons button1.setActionCommand("restart"); button2.setActionCommand("quit"); // set action listeners to buttons button1.addActionListener(this); button2.addActionListener(this); // add the board label to the lower side of the window buttonsPanel = new JPanel(); buttonsPanel.setLayout(new GridLayout(7,1)); buttonsPanel.setBackground(Color.BLACK); buttonsPanel.setPreferredSize(new Dimension(300, 100)); buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); gameStatus = new JLabel(player1 + "'s Turn"); gameStatus.setFont(new Font("Serif", Font.BOLD, 18)); gameStatus.setForeground(Color.WHITE); gameStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add a label to the top of the window JLabel title = new JLabel(player1 + " vs " + player2); title.setFont(new Font("Serif", Font.BOLD, 28)); title.setForeground(Color.ORANGE); buttonsPanel.add(title); buttonsPanel.add(gameStatus); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(new JLabel()); buttonsPanel.add(button1); buttonsPanel.add(button2); moveStatus = new JLabel("Ready to play!"); moveStatus.setFont(new Font("Serif", Font.BOLD, 18)); moveStatus.setForeground(Color.CYAN); moveStatus.setBorder(new EmptyBorder(10, 10, 10, 10)); // add all the parts to the window add(header, BorderLayout.NORTH); add(boardPanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.EAST); add(moveStatus, BorderLayout.SOUTH); boardFrame.setVisible(true); setBackground(Color.BLACK); }
diff --git a/src/com/redhat/qe/sm/cli/tests/RegisterTests.java b/src/com/redhat/qe/sm/cli/tests/RegisterTests.java index 9875064e..2a478d5e 100644 --- a/src/com/redhat/qe/sm/cli/tests/RegisterTests.java +++ b/src/com/redhat/qe/sm/cli/tests/RegisterTests.java @@ -1,1080 +1,1080 @@ package com.redhat.qe.sm.cli.tests; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.xmlrpc.XmlRpcException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.redhat.qe.auto.tcms.ImplementsNitrateTest; import com.redhat.qe.auto.testng.Assert; import com.redhat.qe.auto.testng.BlockedByBzBug; import com.redhat.qe.auto.testng.BzChecker; import com.redhat.qe.auto.testng.LogMessageUtil; import com.redhat.qe.auto.testng.TestNGUtils; import com.redhat.qe.sm.base.ConsumerType; import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript; import com.redhat.qe.sm.cli.tasks.CandlepinTasks; import com.redhat.qe.sm.data.ConsumerCert; import com.redhat.qe.sm.data.EntitlementCert; import com.redhat.qe.sm.data.InstalledProduct; import com.redhat.qe.sm.data.ProductCert; import com.redhat.qe.sm.data.ProductSubscription; import com.redhat.qe.sm.data.SubscriptionPool; import com.redhat.qe.tools.RemoteFileTasks; import com.redhat.qe.tools.SSHCommandResult; import com.redhat.qe.tools.SSHCommandRunner; /** * @author ssalevan * @author jsefler * */ @Test(groups={"RegisterTests"}) public class RegisterTests extends SubscriptionManagerCLITestScript { // Test methods *********************************************************************** @Test( description="subscription-manager-cli: register to a Candlepin server", groups={"RegisterWithUsernameAndPassword_Test", "AcceptanceTests"}, dataProvider="getRegisterCredentialsData") @ImplementsNitrateTest(caseId=41677) public void RegisterWithCredentials_Test(String username, String password, String org) { log.info("Testing registration to a Candlepin using username="+username+" password="+password+" org="+org+" ..."); // cleanup from last test when needed clienttasks.unregister_(null, null, null); // determine this user's ability to register SSHCommandResult registerResult = clienttasks.register_(username, password, org, null, null, null, null, null, nullString, null, null, null, null); // determine this user's available subscriptions List<SubscriptionPool> allAvailableSubscriptionPools=null; if (registerResult.getExitCode()==0) { allAvailableSubscriptionPools = clienttasks.getCurrentlyAllAvailableSubscriptionPools(); } // determine this user's owner String ownerKey = null; if (registerResult.getExitCode()==0) { String consumerId = clienttasks.getCurrentConsumerId(registerResult); // c48dc3dc-be1d-4b8d-8814-e594017d63c1 testuser1 try { ownerKey = CandlepinTasks.getOwnerKeyOfConsumerId(sm_serverHostname,sm_serverPort,sm_serverPrefix,username,password, consumerId); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } RegistrationData userData = new RegistrationData(username,password,ownerKey,registerResult,allAvailableSubscriptionPools); registrationDataList.add(userData); clienttasks.unregister_(null, null, null); // when no org was given by the dataprovider, then this user must have READ_ONLY access to any one or more orgs if (org==null) { // TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=718205 - jsefler 07/01/2011 boolean invokeWorkaroundWhileBugIsOpen = true; String bugId="718205"; try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId).toString()+" Bugzilla bug "+bugId+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */} if (invokeWorkaroundWhileBugIsOpen) { // When org==null, then this user has no access to any org/owner // 1. the user has only READ_ONLY access to one org: // exitCode=1 stdout= User dopey cannot access organization/owner snowwhite // 2. the user has only READ_ONLY access to more than one org: // exitCode=1 stdout= You must specify an organization/owner for new consumers. // Once a Candlepin API is in place to figure this out, fix the OR in the Assert.assertContainsMatch(...) Assert.assertContainsMatch(registerResult.getStderr().trim(), "User "+username+" cannot access organization/owner \\w+|You must specify an organization/owner for new consumers."); // User testuser3 cannot access organization/owner admin // You must specify an organization/owner for new consumers. Assert.assertFalse(registerResult.getExitCode()==0, "The exit code indicates that the register attempt was NOT a success for a READ_ONLY user."); return; } // END OF WORKAROUND Assert.assertEquals(registerResult.getStderr().trim(), username+" cannot register to any organizations.", "Error message when READ_ONLY user attempts to register."); Assert.assertEquals(registerResult.getExitCode(), Integer.valueOf(255), "The exit code indicates that the register attempt was NOT a success for a READ_ONLY user."); return; } Assert.assertEquals(registerResult.getExitCode(), Integer.valueOf(0), "The exit code indicates that the register attempt was a success."); //Assert.assertContainsMatch(registerResult.getStdout().trim(), "[a-f,0-9,\\-]{36} "+/*username*/clienttasks.hostname); // applicable to RHEL61 and RHEL57 Assert.assertContainsMatch(registerResult.getStdout().trim(), "The system has been registered with id: [a-f,0-9,\\-]{36}"); } @Test( description="subscription-manager-cli: register to a Candlepin server using bogus credentials", groups={}, dataProvider="getInvalidRegistrationData") // @ImplementsNitrateTest(caseId={41691, 47918}) @ImplementsNitrateTest(caseId=47918) public void AttemptRegistrationWithInvalidCredentials_Test(Object meta, String username, String password, String owner, ConsumerType type, String name, String consumerId, Boolean autosubscribe, Boolean force, String debug, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex) { log.info("Testing registration to a Candlepin using various options and data and asserting various expected results."); // ensure we are unregistered //DO NOT clienttasks.unregister(); // attempt the registration SSHCommandResult sshCommandResult = clienttasks.register_(username, password, owner, null, type, name, consumerId, autosubscribe, nullString, force, null, null, null); // assert the sshCommandResult here if (expectedExitCode!=null) Assert.assertEquals(sshCommandResult.getExitCode(), expectedExitCode); if (expectedStdoutRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), expectedStdoutRegex); if (expectedStderrRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStderr().trim(), expectedStderrRegex); } @Test( description="subscription-manager-cli: attempt to register to a Candlepin server using bogus credentials and check for localized strings results", groups={"AcceptanceTests"}, dataProvider="getInvalidRegistrationWithLocalizedStringsData") @ImplementsNitrateTest(caseId=41691) public void AttemptLocalizedRegistrationWithInvalidCredentials_Test(Object meta, String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex) { // ensure we are unregistered clienttasks.unregister(null, null, null); log.info("Attempting to register to a candlepin server using invalid credentials and expecting output in language "+(lang==null?"DEFAULT":lang)); String command = String.format("%s %s register --username=%s --password=%s", lang==null?"":"LANG="+lang, clienttasks.command, username, password); RemoteFileTasks.runCommandAndAssert(client, command, exitCode, stdoutRegex, stderrRegex); // assert that the consumer cert and key have NOT been dropped Assert.assertEquals(RemoteFileTasks.testFileExists(client,clienttasks.consumerKeyFile),0, "Consumer key file '"+clienttasks.consumerKeyFile+"' does NOT exist after an attempt to register with invalid credentials."); Assert.assertEquals(RemoteFileTasks.testFileExists(client,clienttasks.consumerCertFile),0, "Consumer cert file '"+clienttasks.consumerCertFile+" does NOT exist after an attempt to register with invalid credentials."); } @Test( description="subscription-manager-cli: attempt to register a user who has unaccepted Terms and Conditions", groups={}, enabled=true) @ImplementsNitrateTest(caseId=48502) public void AttemptRegistrationWithUnacceptedTermsAndConditions_Test() { String username = sm_usernameWithUnacceptedTC; String password = sm_passwordWithUnacceptedTC; if (username.equals("")) throw new SkipException("Must specify a username who has not accepted Terms & Conditions before attempting this test."); AttemptLocalizedRegistrationWithInvalidCredentials_Test(null, null,username,password,255, null, "You must first accept Red Hat's Terms and conditions. Please visit https://www.redhat.com/wapps/ugc"); } @Test( description="subscription-manager-cli: attempt to register a user who has been disabled", groups={}, enabled=true) @ImplementsNitrateTest(caseId=50210) public void AttemptRegistrationWithDisabledUserCredentials_Test() { String username = sm_disabledUsername; String password = sm_disabledPassword; if (username.equals("")) throw new SkipException("Must specify a username who has been disabled before attempting this test."); AttemptLocalizedRegistrationWithInvalidCredentials_Test(null, null,username,password,255, null,"The user has been disabled, if this is a mistake, please contact customer service."); } @Test( description="subscription-manager-cli: register to a Candlepin server using autosubscribe functionality", groups={"RegisterWithAutosubscribe_Test","blockedByBug-602378", "blockedByBug-616137", "blockedByBug-678049", "AcceptanceTests"}, enabled=true) public void RegisterWithAutosubscribe_Test() throws JSONException, Exception { log.info("RegisterWithAutosubscribe_Test Strategy:"); log.info(" For DEV and QA testing purposes, we may not have valid products installed on the client, therefore we will fake an installed product by following this strategy:"); log.info(" 1. Change the rhsm.conf configuration for productCertDir to point to a new temporary product cert directory."); log.info(" 2. Register with autosubscribe and assert that no product binding has occurred."); log.info(" 3. Subscribe to a randomly available pool"); log.info(" 4. Copy the downloaded entitlement cert to the temporary product cert directory."); log.info(" (this will fake rhsm into believing that the same product is installed)"); log.info(" 5. Reregister with autosubscribe and assert that a product has been bound."); // create a clean temporary productCertDir and change the rhsm.conf to point to it RemoteFileTasks.runCommandAndAssert(client, "rm -rf "+tmpProductCertDir, Integer.valueOf(0)); // incase something was leftover from a prior run RemoteFileTasks.runCommandAndAssert(client, "mkdir "+tmpProductCertDir, Integer.valueOf(0)); clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir", tmpProductCertDir); // Register and assert that no products appear to be installed since we changed the productCertDir to a temporary clienttasks.unregister(null, null, null); SSHCommandResult sshCommandResult = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, nullString, null, null, null, null); // pre-fix for blockedByBug-678049 Assert.assertContainsNoMatch(sshCommandResult.getStdout().trim(), "^Subscribed to Products:", "register with autosubscribe should NOT appear to have subscribed to something when there are no installed products."); Assert.assertContainsNoMatch(sshCommandResult.getStdout().trim(), "^Installed Products:", "register with autosubscribe should NOT list the status of installed products when there are no installed products."); Assert.assertEquals(clienttasks.list_(null, null, null, null, Boolean.TRUE, null, null, null).getStdout().trim(),"No installed Products to list", "Since we changed the productCertDir configuration to an empty location, we should not appear to have any products installed."); //List <InstalledProduct> currentlyInstalledProducts = InstalledProduct.parse(clienttasks.list_(null, null, null, Boolean.TRUE, null, null, null).getStdout()); //for (String status : new String[]{"Not Subscribed","Subscribed"}) { // Assert.assertNull(InstalledProduct.findFirstInstanceWithMatchingFieldFromList("status", status, currentlyInstalledProducts), // "When no product certs are installed, then we should not be able to find a installed product with status '"+status+"'."); //} // subscribe to a randomly available pool /* This is too random List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools(); SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool File entitlementCertFile = clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); */ // subscribe to the first available pool that provides one product File entitlementCertFile = null; for (SubscriptionPool pool : clienttasks.getCurrentlyAvailableSubscriptionPools()) { JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_serverHostname,sm_serverPort,sm_serverPrefix,sm_clientUsername,sm_clientPassword,"/pools/"+pool.poolId)); JSONArray jsonProvidedProducts = jsonPool.getJSONArray("providedProducts"); if (jsonProvidedProducts.length()==1) { entitlementCertFile = clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); break; } } if (entitlementCertFile==null) throw new SkipException("Could not find an available pool that provides only one product with which to test register with --autosubscribe."); // copy the downloaded entitlement cert to the temporary product cert directory (this will fake rhsm into believing that the same product is installed) RemoteFileTasks.runCommandAndAssert(client, "cp "+entitlementCertFile.getPath()+" "+tmpProductCertDir, Integer.valueOf(0)); File tmpProductCertFile = new File(tmpProductCertDir+File.separator+entitlementCertFile.getName()); ProductCert fakeProductCert = clienttasks.getProductCertFromProductCertFile(tmpProductCertFile); // reregister with autosubscribe and assert that the product is bound clienttasks.unregister(null, null, null); sshCommandResult = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, nullString, null, null, null, null); // assert that the sshCommandResult from register indicates the fakeProductCert was subscribed /* # subscription-manager register --username=testuser1 --password=password d67df9c8-f381-4449-9d17-56094ea58092 testuser1 Subscribed to Products: RHEL for Physical Servers SVC(37060) Red Hat Enterprise Linux High Availability (for RHEL Entitlement)(4) */ /* # subscription-manager register --username=testuser1 --password=password cadf825a-6695-41e3-b9eb-13d7344159d3 jsefler-onprem03.usersys.redhat.com Installed Products: Clustering Bits - Subscribed Awesome OS Server Bits - Not Installed */ /* # subscription-manager register --username=testuser1 --password=password --org=admin --autosubscribe The system has been registered with id: f95fd9bb-4cc8-428e-b3fd-d656b14bfb89 Installed Product Current Status: ProductName: Awesome OS for S390X Bits Status: Subscribed */ // assert that our fake product install appears to have been autosubscribed InstalledProduct autoSubscribedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("status", "Subscribed", InstalledProduct.parse(clienttasks.list_(null, null, null, null, Boolean.TRUE, null, null, null).getStdout())); Assert.assertNotNull(autoSubscribedProduct, "We appear to have autosubscribed to our fake product install."); // pre-fix for blockedByBug-678049 Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), "^Subscribed to Products:", "The stdout from register with autotosubscribe indicates that we have subscribed to something"); // pre-fix for blockedByBug-678049 Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), "^\\s+"+autoSubscribedProduct.productName.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)"), "Expected ProductName '"+autoSubscribedProduct.productName+"' was reported as autosubscribed in the output from register with autotosubscribe."); //Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), ".* - Subscribed", "The stdout from register with autotosubscribe indicates that we have automatically subscribed at least one of this system's installed products to an available subscription pool."); List<InstalledProduct> autosubscribedProductStatusList = InstalledProduct.parse(sshCommandResult.getStdout()); Assert.assertEquals(autosubscribedProductStatusList.size(), 1, "Only one product was autosubscribed."); Assert.assertEquals(autosubscribedProductStatusList.get(0),new InstalledProduct(fakeProductCert.productName,"Subscribed",null,null,null,null), "As expected, ProductName '"+fakeProductCert.productName+"' was reported as subscribed in the output from register with autotosubscribe."); // WARNING The following two asserts lead to misleading failures when the entitlementCertFile that we using to fake as a tmpProductCertFile happens to have multiple bundled products inside. This is why we search for an available pool that provides one product early in this test. //Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), "^\\s+"+autoSubscribedProduct.productName.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)")+" - Subscribed", "Expected ProductName '"+autoSubscribedProduct.productName+"' was reported as autosubscribed in the output from register with autotosubscribe."); //Assert.assertNotNull(ProductSubscription.findFirstInstanceWithMatchingFieldFromList("productName", autoSubscribedProduct.productName, clienttasks.getCurrentlyConsumedProductSubscriptions()),"Expected ProductSubscription with ProductName '"+autoSubscribedProduct.productName+"' is consumed after registering with autosubscribe."); } @Test( description="subscription-manager-cli: register with --force", groups={"blockedByBug-623264"}, enabled=true) public void RegisterWithForce_Test() { // start fresh by unregistering clienttasks.unregister(null, null, null); // make sure you are first registered SSHCommandResult sshCommandResult = clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null, nullString, null, null, null, null); String firstConsumerId = clienttasks.getCurrentConsumerId(); // subscribe to a random pool (so as to consume an entitlement) List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools(); if (pools.isEmpty()) throw new SkipException("Cannot randomly pick a pool for subscribing when there are no available pools for testing."); SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); // attempt to register again and assert that you are warned that the system is already registered sshCommandResult = clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null, nullString, null, null, null, null); Assert.assertTrue(sshCommandResult.getStdout().startsWith("This system is already registered."),"Expecting: This system is already registered."); // register with force sshCommandResult = clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null, nullString, Boolean.TRUE, null, null, null); String secondConsumerId = clienttasks.getCurrentConsumerId(); // assert the stdout reflects a new consumer Assert.assertTrue(sshCommandResult.getStdout().startsWith("The system with UUID "+firstConsumerId+" has been unregistered"), "The system with UUID "+firstConsumerId+" has been unregistered"); Assert.assertTrue(!secondConsumerId.equals(firstConsumerId), "After registering with force, a newly registered consumerid was returned."); // assert that the new consumer is not consuming any entitlements List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions(); Assert.assertEquals(productSubscriptions.size(),0,"After registering with force, no product subscriptions should be consumed."); } @Test( description="subscription-manager-cli: register with --name", dataProvider="getRegisterWithNameData", groups={}, enabled=true) @ImplementsNitrateTest(caseId=62352) // caseIds=81089 81090 81091 public void RegisterWithName_Test(Object meta, String name, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex) { // start fresh by unregistering clienttasks.unregister(null, null, null); // register with a name SSHCommandResult sshCommandResult = clienttasks.register_(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,name,null, null, nullString, null, null, null, null); // assert the sshCommandResult here if (expectedExitCode!=null) Assert.assertEquals(sshCommandResult.getExitCode(), expectedExitCode,"ExitCode after register with --name=\""+name+"\" option:"); if (expectedStdoutRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), expectedStdoutRegex,"Stdout after register with --name=\""+name+"\" option:"); if (expectedStderrRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStderr().trim(), expectedStderrRegex,"Stderr after register with --name=\""+name+"\" option:"); // assert that the name is happily placed in the consumer cert if (expectedExitCode!=null && expectedExitCode==0) { ConsumerCert consumerCert = clienttasks.getCurrentConsumerCert(); Assert.assertEquals(consumerCert.name, name, ""); } } @Test( description="subscription-manager-cli: register with --name and --type", dataProvider="getRegisterWithNameAndTypeData", groups={}, enabled=true) //@ImplementsNitrateTest(caseId=) public void RegisterWithNameAndType_Test(Object meta, String username, String password, String owner, String name, ConsumerType type, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex) { // start fresh by unregistering clienttasks.unregister(null, null, null); // register with a name SSHCommandResult sshCommandResult = clienttasks.register_(username,password,owner,null,type,name,null, null, nullString, null, null, null, null); // assert the sshCommandResult here if (expectedExitCode!=null) Assert.assertEquals(sshCommandResult.getExitCode(), expectedExitCode,"ExitCode after register with --name="+name+" --type="+type+" options:"); if (expectedStdoutRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), expectedStdoutRegex,"Stdout after register with --name="+name+" --type="+type+" options:"); if (expectedStderrRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStderr().trim(), expectedStderrRegex,"Stderr after register with --name="+name+" --type="+type+" options:"); } /** * https://tcms.engineering.redhat.com/case/56327/?from_plan=2476 Actions: * register a client to candlepin * subscribe to a pool * list consumed * reregister Expected Results: * check the identity cert has not changed * check the consumed entitlements have not changed */ @Test( description="subscription-manager-cli: reregister basic registration", groups={"blockedByBug-636843","AcceptanceTests"}, enabled=true) @ImplementsNitrateTest(caseId=56327) public void ReregisterBasicRegistration_Test() { // start fresh by unregistering and registering clienttasks.unregister(null, null, null); String consumerIdBefore = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,null,null,null,null)); // take note of your identity cert before reregister ConsumerCert consumerCertBefore = clienttasks.getCurrentConsumerCert(); // subscribe to a random pool List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools(); if (pools.isEmpty()) throw new SkipException("Cannot randomly pick a pool for subscribing when there are no available pools for testing."); SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); // get a list of the consumed products List<ProductSubscription> consumedProductSubscriptionsBefore = clienttasks.getCurrentlyConsumedProductSubscriptions(); // reregister //clienttasks.reregister(null,null,null); clienttasks.reregisterToExistingConsumer(sm_clientUsername,sm_clientPassword,consumerIdBefore); // assert that the identity cert has not changed ConsumerCert consumerCertAfter = clienttasks.getCurrentConsumerCert(); Assert.assertEquals(consumerCertBefore, consumerCertAfter, "The consumer identity cert has not changed after reregistering with consumerid."); // assert that the user is still consuming the same products List<ProductSubscription> consumedProductSubscriptionsAfter = clienttasks.getCurrentlyConsumedProductSubscriptions(); Assert.assertTrue( consumedProductSubscriptionsAfter.containsAll(consumedProductSubscriptionsBefore) && consumedProductSubscriptionsBefore.size()==consumedProductSubscriptionsAfter.size(), "The list of consumed products after reregistering is identical."); } /** * https://tcms.engineering.redhat.com/case/56328/?from_plan=2476 * Actions: * register a client to candlepin (take note of the uuid returned) * take note of your identity cert info using openssl x509 * subscribe to a pool * list consumed * ls /etc/pki/entitlement/products * Now.. mess up your identity.. mv /etc/pki/consumer/cert.pem /bak * run the "reregister" command w/ username and passwd AND w/consumerid=<uuid> Expected Results: * after running reregister you should have a new identity cert * after registering you should still the same products consumed (list consumed) * the entitlement serials should be the same as before the registration */ @Test( description="subscription-manager-cli: bad identity cert", groups={"blockedByBug-624106"}, enabled=true) @ImplementsNitrateTest(caseId=56328) public void ReregisterWithBadIdentityCert_Test() { // start fresh by unregistering and registering clienttasks.unregister(null, null, null); clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,null,null,null,null); // take note of your identity cert ConsumerCert consumerCertBefore = clienttasks.getCurrentConsumerCert(); // subscribe to a random pool List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools(); if (pools.isEmpty()) throw new SkipException("Cannot randomly pick a pool for subscribing when there are no available pools for testing."); SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); // get a list of the consumed products List<ProductSubscription> consumedProductSubscriptionsBefore = clienttasks.getCurrentlyConsumedProductSubscriptions(); // Now.. mess up your identity.. by borking its content log.info("Messing up the identity cert by borking its content..."); RemoteFileTasks.runCommandAndAssert(client, "openssl x509 -noout -text -in "+clienttasks.consumerCertFile+" > /tmp/stdout; mv /tmp/stdout -f "+clienttasks.consumerCertFile, 0); // reregister w/ username, password, and consumerid //clienttasks.reregister(client1username,client1password,consumerCertBefore.consumerid); log.warning("The subscription-manager-cli reregister module has been eliminated and replaced by register --consumerid (b3c728183c7259841100eeacb7754c727dc523cd)..."); clienttasks.register(sm_clientUsername,sm_clientPassword,null,null,null,null,consumerCertBefore.consumerid, null, nullString, Boolean.TRUE, null, null, null); // assert that the identity cert has not changed ConsumerCert consumerCertAfter = clienttasks.getCurrentConsumerCert(); Assert.assertEquals(consumerCertBefore, consumerCertAfter, "The consumer identity cert has not changed after reregistering with consumerid."); // assert that the user is still consuming the same products List<ProductSubscription> consumedProductSubscriptionsAfter = clienttasks.getCurrentlyConsumedProductSubscriptions(); Assert.assertTrue( consumedProductSubscriptionsAfter.containsAll(consumedProductSubscriptionsBefore) && consumedProductSubscriptionsBefore.size()==consumedProductSubscriptionsAfter.size(), "The list of consumed products after reregistering is identical."); } /** * https://tcms.engineering.redhat.com/case/72845/?from_plan=2476 * Actions: * register with username and password and remember the consumerid * subscribe to one or more subscriptions * list the consumed subscriptions and remember them * clean system * assert that there are no entitlements on the system * register with same username, password and existing consumerid * assert that originally consumed subscriptions are once again being consumed Expected Results: * when registering a new system to an already existing consumer, all of the existing consumers entitlement certs should be downloaded to the new system */ @Test( description="register with existing consumerid should automatically refresh entitlements", groups={}, enabled=true) @ImplementsNitrateTest(caseId=72845) public void ReregisterWithConsumerIdShouldAutomaticallyRefreshEntitlements_Test() { // register with username and password and remember the consumerid clienttasks.unregister(null, null, null); String consumerId = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null, null, nullString, null, null, null, null)); // subscribe to one or more subscriptions //// subscribe to a random pool //List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools(); //SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool //clienttasks.subscribeToSubscriptionPoolUsingPoolId(pool); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(); // list the consumed subscriptions and remember them List <ProductSubscription> originalConsumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions(); // also remember the current entitlement certs List <EntitlementCert> originalEntitlementCerts= clienttasks.getCurrentEntitlementCerts(); // clean system clienttasks.clean(null, null, null); // assert that there are no entitlements on the system //Assert.assertTrue(clienttasks.getCurrentlyConsumedProductSubscriptions().isEmpty(),"There are NO consumed Product Subscriptions on this system after running clean"); Assert.assertTrue(clienttasks.getCurrentEntitlementCerts().isEmpty(),"There are NO Entitlement Certs on this system after running clean"); // register with same username, password and existing consumerid // Note: no need to register with force as running clean wipes system of all local registration data clienttasks.register(sm_clientUsername,sm_clientPassword,null,null,null,null,consumerId, null, nullString, null, null, null, null); // assert that originally consumed subscriptions are once again being consumed List <ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions(); Assert.assertEquals(consumedProductSubscriptions.size(),originalConsumedProductSubscriptions.size(), "The number of consumed Product Subscriptions after registering to an existing consumerid matches his original count."); for (ProductSubscription productSubscription : consumedProductSubscriptions) { Assert.assertContains(originalConsumedProductSubscriptions, productSubscription); } // assert that original entitlement certs are once on the system List <EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts(); Assert.assertEquals(entitlementCerts.size(),originalEntitlementCerts.size(), "The number of Entitlement Certs on the system after registering to an existing consumerid matches his original count."); for (EntitlementCert entitlementCert : entitlementCerts) { Assert.assertContains(originalEntitlementCerts, entitlementCert); } } @Test( description="register with an empty /var/lib/rhsm/facts/facts.json file", groups={"blockedByBug-667953","blockedByBug-669208"}, enabled=true) //@ImplementsNitrateTest(caseId=) public void RegisterWithAnEmptyRhsmFactsJsonFile_Test() { Assert.assertTrue(RemoteFileTasks.testFileExists(client, clienttasks.rhsmFactsJsonFile)==1, "rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"' exists"); log.info("Emptying rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"'..."); client.runCommandAndWait("echo \"\" > "+clienttasks.rhsmFactsJsonFile, LogMessageUtil.action()); SSHCommandResult result = client.runCommandAndWait("cat "+clienttasks.rhsmFactsJsonFile, LogMessageUtil.action()); Assert.assertTrue(result.getStdout().trim().equals(""), "rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"' is empty."); log.info("Attempt to register with an empty rhsm facts file (expecting success)..."); clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, nullString, Boolean.TRUE, null, null, null); } @Test( description="register with a missing /var/lib/rhsm/facts/facts.json file", groups={}, enabled=true) //@ImplementsNitrateTest(caseId=) public void RegisterWithAnMissingRhsmFactsJsonFile_Test() { Assert.assertTrue(RemoteFileTasks.testFileExists(client, clienttasks.rhsmFactsJsonFile)==1, "rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"' exists"); log.info("Deleting rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"'..."); RemoteFileTasks.runCommandAndWait(client, "rm -f "+clienttasks.rhsmFactsJsonFile, LogMessageUtil.action()); Assert.assertTrue(RemoteFileTasks.testFileExists(client, clienttasks.rhsmFactsJsonFile)==0, "rhsm facts json file '"+clienttasks.rhsmFactsJsonFile+"' has been removed"); log.info("Attempt to register with a missing rhsm facts file (expecting success)..."); clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, nullString, Boolean.TRUE, null, null, null); } @Test( description="register with interactive prompting for credentials", groups={"blockedByBug-678151"}, dataProvider = "getInteractiveRegistrationData", enabled=true) //@ImplementsNitrateTest(caseId=) public void RegisterWithInteractivePromptingForCredentials_Test(Object bugzilla, String promptedUsername, String promptedPassword, String commandLineUsername, String commandLinePassword, String commandLineOrg, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex) { // skip automated interactive password tests on rhel57 if (clienttasks.redhatRelease.contains("release 5.7") && promptedPassword!=null) throw new SkipException("Interactive registration with password prompting must be tested manually on RHEL5.7 since python-2.4 is denying password entry from echo piped to stdin."); // ensure we are unregistered clienttasks.unregister(null,null,null); // call register while providing a valid username at the interactive prompt // assemble an ssh command using echo and pipe to simulate an interactively supply of credentials to the register command String echoUsername= promptedUsername==null?"":promptedUsername; String echoPassword = promptedPassword==null?"":promptedPassword; String n = (promptedPassword!=null&&promptedUsername!=null)? "\n":""; String command = String.format("echo -e \"%s\" | %s register %s %s %s", echoUsername+n+echoPassword, clienttasks.command, commandLineUsername==null?"":"--username="+commandLineUsername, commandLinePassword==null?"":"--password="+commandLinePassword, commandLineOrg==null?"":"--org="+commandLineOrg); // attempt to register with the interactive credentials SSHCommandResult sshCommandResult = client.runCommandAndWait(command); // assert the sshCommandResult here if (expectedExitCode!=null) Assert.assertEquals(sshCommandResult.getExitCode(), expectedExitCode, "The expected exit code from the register attempt."); if (expectedStdoutRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStdout(), expectedStdoutRegex, "The expected stdout result from register while supplying interactive credentials."); if (expectedStderrRegex!=null) Assert.assertContainsMatch(sshCommandResult.getStderr(), expectedStderrRegex, "The expected stderr result from register while supplying interactive credentials."); } @Test( description="User is warned when already registered using RHN Classic", groups={}, enabled=true) @ImplementsNitrateTest(caseId=75972) public void InteroperabilityRegister_Test() { // interoperabilityWarningMessage is defined in /usr/share/rhsm/subscription_manager/branding/__init__.py self.REGISTERED_TO_OTHER_WARNING String interoperabilityWarningMessage = "WARNING" +"\n\n"+ "You have already registered with RHN using RHN Classic technology. This tool requires registration using RHN Certificate-Based Entitlement technology." +"\n\n"+ "Except for a few cases, Red Hat recommends customers only register with RHN once." +"\n\n"+ "For more information, including alternate tools, consult this Knowledge Base Article: https://access.redhat.com/kb/docs/DOC-45563"; // query the branding python file directly to get the default interoperabilityWarningMessage (when the subscription-manager rpm came from a git build - this assumes that any build of subscription-manager must have a branding module e.g. redhat_branding.py) if (client.runCommandAndWait("rpm -q subscription-manager").getStdout().contains(".git.")) { interoperabilityWarningMessage = clienttasks.getBrandingString("REGISTERED_TO_OTHER_WARNING"); } Assert.assertTrue(interoperabilityWarningMessage.startsWith("WARNING"), "The interoperability message starts with \"WARNING\"."); log.info("Simulating registration by RHN Classic by creating an empty systemid file '"+clienttasks.rhnSystemIdFile+"'..."); RemoteFileTasks.runCommandAndWait(client, "touch "+clienttasks.rhnSystemIdFile, LogMessageUtil.action()); Assert.assertTrue(RemoteFileTasks.testFileExists(client, clienttasks.rhnSystemIdFile)==1, "RHN Classic systemid file '"+clienttasks.rhnSystemIdFile+"' is in place."); log.info("Attempt to register while already registered via RHN Classic..."); SSHCommandResult result = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, nullString, true, null, null, null); //Assert.assertTrue(result.getStdout().startsWith(interoperabilityWarningMessage), "subscription-manager warns the registerer when the system is already registered via RHN Classic with this expected message:\n"+interoperabilityWarningMessage); Assert.assertContainsMatch(result.getStdout(),"^"+interoperabilityWarningMessage, "subscription-manager warns the registerer when the system is already registered via RHN Classic with the expected message."); log.info("Now let's make sure we are NOT warned when we are NOT already registered via RHN Classic..."); RemoteFileTasks.runCommandAndWait(client, "rm -rf "+clienttasks.rhnSystemIdFile, LogMessageUtil.action()); Assert.assertTrue(RemoteFileTasks.testFileExists(client, clienttasks.rhnSystemIdFile)==0, "RHN Classic systemid file '"+clienttasks.rhnSystemIdFile+"' is gone."); result = clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, nullString, true, null, null, null); //Assert.assertFalse(result.getStdout().startsWith(interoperabilityWarningMessage), "subscription-manager does NOT warn registerer when the system is not already registered via RHN Classic."); Assert.assertContainsNoMatch(result.getStdout(),interoperabilityWarningMessage, "subscription-manager does NOT warn registerer when the system is NOT already registered via RHN Classic."); } @Test( description="subscription-manager: attempt register to --environment when the candlepin server does not support environments should fail", groups={}, enabled=true) //@ImplementsNitrateTest(caseId=) public void AttemptRegisterToEnvironmentWhenCandlepinDoesNotSupportEnvironments_Test() throws JSONException, Exception { // ask the candlepin server if it supports environment boolean supportsEnvironments = CandlepinTasks.isEnvironmentsSupported(sm_serverHostname, sm_serverPort, sm_serverPrefix, sm_clientUsername, sm_clientPassword); // skip this test when candlepin supports environments if (supportsEnvironments) throw new SkipException("Candlepin server '"+sm_serverHostname+"' appears to support environments, therefore this test is not applicable."); SSHCommandResult result = clienttasks.register_(sm_clientUsername,sm_clientPassword,sm_clientOrg,"foo",null,null,null,null,nullString,true,null,null, null); // assert results Assert.assertEquals(result.getStderr().trim(), "ERROR: Server does not support environments.","Attempt to register to an environment on a server that does not support environments should be blocked."); Assert.assertEquals(result.getExitCode(), Integer.valueOf(1),"Exit code from register to environment when the candlepin server does NOT support environments."); } @Test( description="subscription-manager: attempt register to --environment without --org option should fail", groups={}, enabled=true) //@ImplementsNitrateTest(caseId=) public void AttemptRegisterToEnvironmentWithoutOrg_Test() { SSHCommandResult result = clienttasks.register_(sm_clientUsername,sm_clientPassword,null,"foo",null,null,null,null,nullString,true,null,null, null); // assert results Assert.assertEquals(result.getStdout().trim(), "Error: Must specify --org to register to an environment.","Registering to an environment requires that the org be specified."); Assert.assertEquals(result.getExitCode(), Integer.valueOf(255),"Exit code from register with environment option and without org option."); } // Candidates for an automated Test: // TODO https://bugzilla.redhat.com/show_bug.cgi?id=627685 // TODO https://bugzilla.redhat.com/show_bug.cgi?id=627665 // TODO https://bugzilla.redhat.com/show_bug.cgi?id=668814 // TODO https://bugzilla.redhat.com/show_bug.cgi?id=669395 // TODO Bug 693896 - subscription-manager does not always reload dbus scripts automatically // TODO Bug 719378 - White space in user name causes error // Protected Class Variables *********************************************************************** protected final String tmpProductCertDir = "/tmp/productCertDir"; protected String productCertDir = null; // Configuration methods *********************************************************************** @BeforeGroups(value={"RegisterWithAutosubscribe_Test"}) public void storeProductCertDir() { this.productCertDir = clienttasks.productCertDir; } @AfterGroups(value={"RegisterWithAutosubscribe_Test"},alwaysRun=true) @AfterClass (alwaysRun=true) public void cleaupAfterClass() { if (clienttasks==null) return; if (this.productCertDir!=null) clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir", this.productCertDir); client.runCommandAndWait("rm -rf "+tmpProductCertDir); client.runCommandAndWait("rm -rf "+clienttasks.rhnSystemIdFile); } @BeforeGroups(value={"RegisterWithUsernameAndPassword_Test"},alwaysRun=true) public void unregisterBeforeRegisterWithUsernameAndPassword_Test() { if (clienttasks==null) return; clienttasks.unregister_(null, null, null); } @AfterGroups(value={"RegisterWithUsernameAndPassword_Test"},alwaysRun=true) public void generateRegistrationReportTableAfterRegisterWithUsernameAndPassword_Test() { // now dump out the list of userData to a file File file = new File("CandlepinRegistrationReport.html"); // this will be in the automation.dir directory on hudson (workspace/automatjon/sm) DateFormat dateFormat = new SimpleDateFormat("MMM d HH:mm:ss yyyy z"); try { Writer output = new BufferedWriter(new FileWriter(file)); // write out the rows of the table output.write("<html>\n"); output.write("<table border=1>\n"); output.write("<h2>Candlepin Registration Report</h2>\n"); //output.write("<h3>(generated on "+dateFormat.format(System.currentTimeMillis())+")</h3>"); output.write("Candlepin hostname= <b>"+sm_serverHostname+"</b><br>\n"); output.write(dateFormat.format(System.currentTimeMillis())+"\n"); output.write("<tr><th>Username/<BR>Password</th><th>OrgKey</th><th>Register Result</th><th>All Available Subscriptions<BR>(to system consumers)</th></tr>\n"); for (RegistrationData registeredConsumer : registrationDataList) { if (registeredConsumer.ownerKey==null) { output.write("<tr bgcolor=#F47777>"); } else {output.write("<tr>");} if (registeredConsumer.username!=null) { output.write("<td valign=top>"+registeredConsumer.username+"/<BR>"+registeredConsumer.password+"</td>"); } else {output.write("<td/>");}; if (registeredConsumer.ownerKey!=null) { output.write("<td valign=top>"+registeredConsumer.ownerKey+"</td>"); } else {output.write("<td/>");}; if (registeredConsumer.registerResult!=null) { output.write("<td valign=top>"+registeredConsumer.registerResult.getStdout()+registeredConsumer.registerResult.getStderr()+"</td>"); } else {output.write("<td/>");}; if (registeredConsumer.allAvailableSubscriptionPools!=null) { output.write("<td valign=top><ul>"); for (SubscriptionPool availableSubscriptionPool : registeredConsumer.allAvailableSubscriptionPools) { output.write("<li>"+availableSubscriptionPool+"</li>"); } output.write("</ul></td>"); } else {output.write("<td/>");}; output.write("</tr>\n"); } output.write("</table>\n"); output.write("</html>\n"); output.close(); //log.info(file.getCanonicalPath()+" exists="+file.exists()+" writable="+file.canWrite()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Protected methods *********************************************************************** protected void checkInvalidRegistrationStrings(SSHCommandRunner sshCommandRunner, String username, String password){ sshCommandRunner.runCommandAndWait("subscription-manager-cli register --username="+username+this.getRandInt()+" --password="+password+this.getRandInt()+" --force"); Assert.assertContainsMatch(sshCommandRunner.getStdout(), "Invalid username or password. To create a login, please visit https:\\/\\/www.redhat.com\\/wapps\\/ugc\\/register.html"); } // Data Providers *********************************************************************** @DataProvider(name="getInvalidRegistrationData") public Object[][] getInvalidRegistrationDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getInvalidRegistrationDataAsListOfLists()); } protected List<List<Object>> getInvalidRegistrationDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); String randomString = String.valueOf(getRandInt()); // Object bugzilla, String username, String password, String owner, String type, String consumerId, Boolean autosubscribe, Boolean force, String debug, Integer exitCode, String stdoutRegex, String stderrRegex ll.add(Arrays.asList(new Object[] {null, sm_clientUsername, String.valueOf(getRandInt()), null, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] {null, sm_clientUsername+getRandInt(), sm_clientPassword, null, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] {null, sm_clientUsername+getRandInt(), String.valueOf(getRandInt()), null, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] {null, sm_clientUsername, sm_clientPassword, null, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(255), null, "You must specify an organization/owner for new consumers."})); ll.add(Arrays.asList(new Object[] {null, sm_clientUsername, sm_clientPassword, randomString, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(255), null, "Organization/Owner "+randomString+" does not exist."})); // force a successful registration, and then... ll.add(Arrays.asList(new Object[]{ new BlockedByBzBug(new String[]{"616065","669395"}), sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, null, Integer.valueOf(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); // ... try to register again even though the system is already registered ll.add(Arrays.asList(new Object[] {null, sm_clientUsername, sm_clientPassword, null, null, null, null, null, Boolean.FALSE, null, Integer.valueOf(1), "This system is already registered. Use --force to override", null})); return ll; } @DataProvider(name="getInteractiveRegistrationData") public Object[][] getInteractiveRegistrationDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getInteractiveRegistrationDataAsListOfLists()); } protected List<List<Object>> getInteractiveRegistrationDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); String x = String.valueOf(getRandInt()); // Object bugzilla, String promptedUsername, String promptedPassword, String commandLineUsername, String commandLinePassword, String commandLineOwner, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex ll.add(Arrays.asList(new Object[] { null, sm_clientUsername, null, null, sm_clientPassword, sm_clientOrg, new Integer(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); ll.add(Arrays.asList(new Object[] { null, sm_clientUsername+x, null, null, sm_clientPassword, sm_clientOrg, new Integer(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] { null, null, sm_clientPassword, sm_clientUsername, null, sm_clientOrg, new Integer(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); ll.add(Arrays.asList(new Object[] { null, null, sm_clientPassword+x, sm_clientUsername, null, sm_clientOrg, new Integer(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] { null, sm_clientUsername, sm_clientPassword, null, null, sm_clientOrg, new Integer(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); ll.add(Arrays.asList(new Object[] { null, sm_clientUsername+x, sm_clientPassword+x, null, null, sm_clientOrg, new Integer(255), null, uErrMsg})); ll.add(Arrays.asList(new Object[] { null, "\n\n"+sm_clientUsername, "\n\n"+sm_clientPassword, null, null, sm_clientOrg, new Integer(0), "(Username: ){3}The system has been registered with id: [a-f,0-9,\\-]{36}", "(Warning: Password input may be echoed.\nPassword: \n){3}"})); return ll; } @DataProvider(name="getInvalidRegistrationWithLocalizedStringsData") public Object[][] getInvalidRegistrationWithLocalizedStringsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getInvalidRegistrationWithLocalizedStringsAsListOfLists()); } protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_isServerOnPremises) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); - ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidas"})); + ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidos"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidos"})); ll.add(Arrays.asList(new Object[]{null, "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); // TODO need translation } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (!sm_isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF8 subscription-manager clean --help"; LANG=$l.UTF8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ return ll; } @DataProvider(name="getRegisterWithNameAndTypeData") public Object[][] getRegisterWithNameAndTypeDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameAndTypeDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameAndTypeDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String username=sm_clientUsername; String password=sm_clientPassword; String owner=sm_clientOrg; // flatten all the ConsumerType values into a comma separated list // String consumerTypesAsString = ""; // for (ConsumerType type : ConsumerType.values()) consumerTypesAsString+=type+","; // consumerTypesAsString = consumerTypesAsString.replaceAll(",$", ""); // interate across all ConsumerType values and append rows to the dataProvider for (ConsumerType type : ConsumerType.values()) { String name = type.toString()+"_NAME"; // List <String> registerableConsumerTypes = Arrays.asList(getProperty("sm.consumerTypes", consumerTypesAsString).trim().split(" *, *")); // registerable consumer types List <String> registerableConsumerTypes = sm_consumerTypes; // decide what username and password to test with if (type.equals(ConsumerType.person) && !getProperty("sm.rhpersonal.username", "").equals("")) { username = sm_rhpersonalUsername; password = sm_rhpersonalPassword; owner = sm_rhpersonalOrg; } else { username = sm_clientUsername; password = sm_clientPassword; owner = sm_clientOrg; } // String username, String password, String owner, String name, ConsumerType type, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex if (registerableConsumerTypes.contains(type.toString())) { /* applicable to RHEL61 and RHEL57 if (type.equals(ConsumerType.person)) { ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("661130"), username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+username, null})); } else { ll.add(Arrays.asList(new Object[]{null, username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+name, null})); } */ ll.add(Arrays.asList(new Object[]{null, username, password, owner, name, type, Integer.valueOf(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); } else { ll.add(Arrays.asList(new Object[]{ null, username, password, owner, name, type, Integer.valueOf(255), null, "No such consumer type: "+type})); } } return ll; } @DataProvider(name="getRegisterWithNameData") public Object[][] getRegisterWithNameDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String invalidNameStderr = "System name must consist of only alphanumeric characters, periods, dashes and underscores."; // bugzilla 672233 invalidNameStderr = "System name cannot contain most special characters."; // bugzilla 677405 String maxCharsStderr = "Name of the consumer should be shorter than 250 characters\\."; String name; String successfulStdout = "The system has been registered with id: [a-f,0-9,\\-]{36}"; // valid names according to bugzilla 672233 name = "periods...dashes---underscores___alphanumerics123"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "249_characters_678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); // the tolerable characters has increased due to bugzilla 677405 and agilo task http://gibson.usersys.redhat.com/agilo/ticket/5235 (6.1) As an IT Person, I would like to ensure that user service and candlepin enforce the same valid character rules (QE); Developer beav "Christopher Duryee" <[email protected]> // https://bugzilla.redhat.com/show_bug.cgi?id=677405#c1 name = "[openingBracket["; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\[openingBracket\\["*/, null})); name = "]closingBracket]"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\]closingBracket\\]"*/, null})); name = "{openingBrace{"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\{openingBrace\\{"*/, null})); name = "}closingBrace}"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\}closingBrace\\}"*/, null})); name = "(openingParenthesis("; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\(openingParenthesis\\("*/, null})); name = ")closingParenthesis)"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\)closingParenthesis\\)"*/, null})); name = "?questionMark?"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\?questionMark\\?"*/, null})); name = "@at@"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "!exclamationPoint!"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "`backTick`"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "'singleQuote'"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "pound#sign"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); // Note: pound signs within the name are acceptable, but not at the beginning // invalid names // Note: IT Services invalid characters can be tested by trying to Sign Up a new login here: https://www.webqa.redhat.com/wapps/sso/login.html // Invalid Chars: (") ($) (^) (<) (>) (|) (+) (%) (/) (;) (:) (,) (\) (*) (=) (~) // from https://bugzilla.redhat.com/show_bug.cgi?id=677405#c1 name = "\"doubleQuotes\""; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "$dollarSign$"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "^caret^"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "<lessThan<"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = ">greaterThan>"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "|verticalBar|"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "+plus+"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "%percent%"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "/slash/"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = ";semicolon;"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = ":colon:"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = ",comma,"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "\\backslash\\"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "*asterisk*"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "=equal="; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); name = "~tilde~"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); // spaces are also rejected characters from IT Services name = "s p a c e s"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, invalidNameStderr})); // special case (pound sign at the beginning is a limitation in the x509 certificates) name = "#poundSign"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(255), null, "System name cannot begin with # character"})); // // http://www.ascii.cl/htmlcodes.htm // TODO //name = "é"; ll.add(Arrays.asList(new Object[]{ name, Integer.valueOf(255), null, invalidNameStderr})); //name = "ë"; ll.add(Arrays.asList(new Object[]{ name, Integer.valueOf(255), null, invalidNameStderr})); //name = "â"; ll.add(Arrays.asList(new Object[]{ name, Integer.valueOf(255), null, invalidNameStderr})); // names that are too long (>=250 chars) name = "250_characters_6789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("672233"), name, Integer.valueOf(255), null, maxCharsStderr})); return ll; } }
true
true
protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_isServerOnPremises) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidas"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidos"})); ll.add(Arrays.asList(new Object[]{null, "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); // TODO need translation } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (!sm_isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF8 subscription-manager clean --help"; LANG=$l.UTF8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ return ll; } @DataProvider(name="getRegisterWithNameAndTypeData") public Object[][] getRegisterWithNameAndTypeDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameAndTypeDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameAndTypeDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String username=sm_clientUsername; String password=sm_clientPassword; String owner=sm_clientOrg; // flatten all the ConsumerType values into a comma separated list // String consumerTypesAsString = ""; // for (ConsumerType type : ConsumerType.values()) consumerTypesAsString+=type+","; // consumerTypesAsString = consumerTypesAsString.replaceAll(",$", ""); // interate across all ConsumerType values and append rows to the dataProvider for (ConsumerType type : ConsumerType.values()) { String name = type.toString()+"_NAME"; // List <String> registerableConsumerTypes = Arrays.asList(getProperty("sm.consumerTypes", consumerTypesAsString).trim().split(" *, *")); // registerable consumer types List <String> registerableConsumerTypes = sm_consumerTypes; // decide what username and password to test with if (type.equals(ConsumerType.person) && !getProperty("sm.rhpersonal.username", "").equals("")) { username = sm_rhpersonalUsername; password = sm_rhpersonalPassword; owner = sm_rhpersonalOrg; } else { username = sm_clientUsername; password = sm_clientPassword; owner = sm_clientOrg; } // String username, String password, String owner, String name, ConsumerType type, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex if (registerableConsumerTypes.contains(type.toString())) { /* applicable to RHEL61 and RHEL57 if (type.equals(ConsumerType.person)) { ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("661130"), username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+username, null})); } else { ll.add(Arrays.asList(new Object[]{null, username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+name, null})); } */ ll.add(Arrays.asList(new Object[]{null, username, password, owner, name, type, Integer.valueOf(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); } else { ll.add(Arrays.asList(new Object[]{ null, username, password, owner, name, type, Integer.valueOf(255), null, "No such consumer type: "+type})); } } return ll; } @DataProvider(name="getRegisterWithNameData") public Object[][] getRegisterWithNameDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String invalidNameStderr = "System name must consist of only alphanumeric characters, periods, dashes and underscores."; // bugzilla 672233 invalidNameStderr = "System name cannot contain most special characters."; // bugzilla 677405 String maxCharsStderr = "Name of the consumer should be shorter than 250 characters\\."; String name; String successfulStdout = "The system has been registered with id: [a-f,0-9,\\-]{36}"; // valid names according to bugzilla 672233 name = "periods...dashes---underscores___alphanumerics123"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "249_characters_678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); // the tolerable characters has increased due to bugzilla 677405 and agilo task http://gibson.usersys.redhat.com/agilo/ticket/5235 (6.1) As an IT Person, I would like to ensure that user service and candlepin enforce the same valid character rules (QE); Developer beav "Christopher Duryee" <[email protected]> // https://bugzilla.redhat.com/show_bug.cgi?id=677405#c1 name = "[openingBracket["; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\[openingBracket\\["*/, null})); name = "]closingBracket]"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\]closingBracket\\]"*/, null}));
protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_isServerOnPremises) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidos"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidos"})); ll.add(Arrays.asList(new Object[]{null, "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); // TODO need translation ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); // TODO need translation ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); // TODO need translation } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (!sm_isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF8 subscription-manager clean --help"; LANG=$l.UTF8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ return ll; } @DataProvider(name="getRegisterWithNameAndTypeData") public Object[][] getRegisterWithNameAndTypeDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameAndTypeDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameAndTypeDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String username=sm_clientUsername; String password=sm_clientPassword; String owner=sm_clientOrg; // flatten all the ConsumerType values into a comma separated list // String consumerTypesAsString = ""; // for (ConsumerType type : ConsumerType.values()) consumerTypesAsString+=type+","; // consumerTypesAsString = consumerTypesAsString.replaceAll(",$", ""); // interate across all ConsumerType values and append rows to the dataProvider for (ConsumerType type : ConsumerType.values()) { String name = type.toString()+"_NAME"; // List <String> registerableConsumerTypes = Arrays.asList(getProperty("sm.consumerTypes", consumerTypesAsString).trim().split(" *, *")); // registerable consumer types List <String> registerableConsumerTypes = sm_consumerTypes; // decide what username and password to test with if (type.equals(ConsumerType.person) && !getProperty("sm.rhpersonal.username", "").equals("")) { username = sm_rhpersonalUsername; password = sm_rhpersonalPassword; owner = sm_rhpersonalOrg; } else { username = sm_clientUsername; password = sm_clientPassword; owner = sm_clientOrg; } // String username, String password, String owner, String name, ConsumerType type, Integer expectedExitCode, String expectedStdoutRegex, String expectedStderrRegex if (registerableConsumerTypes.contains(type.toString())) { /* applicable to RHEL61 and RHEL57 if (type.equals(ConsumerType.person)) { ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("661130"), username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+username, null})); } else { ll.add(Arrays.asList(new Object[]{null, username, password, name, type, Integer.valueOf(0), "[a-f,0-9,\\-]{36} "+name, null})); } */ ll.add(Arrays.asList(new Object[]{null, username, password, owner, name, type, Integer.valueOf(0), "The system has been registered with id: [a-f,0-9,\\-]{36}", null})); } else { ll.add(Arrays.asList(new Object[]{ null, username, password, owner, name, type, Integer.valueOf(255), null, "No such consumer type: "+type})); } } return ll; } @DataProvider(name="getRegisterWithNameData") public Object[][] getRegisterWithNameDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getRegisterWithNameDataAsListOfLists()); } protected List<List<Object>> getRegisterWithNameDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); String invalidNameStderr = "System name must consist of only alphanumeric characters, periods, dashes and underscores."; // bugzilla 672233 invalidNameStderr = "System name cannot contain most special characters."; // bugzilla 677405 String maxCharsStderr = "Name of the consumer should be shorter than 250 characters\\."; String name; String successfulStdout = "The system has been registered with id: [a-f,0-9,\\-]{36}"; // valid names according to bugzilla 672233 name = "periods...dashes---underscores___alphanumerics123"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); name = "249_characters_678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} "+name*/, null})); // the tolerable characters has increased due to bugzilla 677405 and agilo task http://gibson.usersys.redhat.com/agilo/ticket/5235 (6.1) As an IT Person, I would like to ensure that user service and candlepin enforce the same valid character rules (QE); Developer beav "Christopher Duryee" <[email protected]> // https://bugzilla.redhat.com/show_bug.cgi?id=677405#c1 name = "[openingBracket["; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\[openingBracket\\["*/, null})); name = "]closingBracket]"; ll.add(Arrays.asList(new Object[] {null, name, Integer.valueOf(0), successfulStdout/*"[a-f,0-9,\\-]{36} \\]closingBracket\\]"*/, null}));
diff --git a/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java b/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java index 39289f5..16ee27a 100644 --- a/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java +++ b/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java @@ -1,314 +1,314 @@ package com.smp.funwithmusic.activities; import static com.smp.funwithmusic.utilities.Constants.*; import static com.smp.funwithmusic.utilities.UtilityMethods.*; import java.util.List; import java.util.Locale; import com.afollestad.cardsui.Card; import com.afollestad.cardsui.Card.CardMenuListener; import com.afollestad.cardsui.CardBase; import com.afollestad.cardsui.CardHeader; import com.afollestad.cardsui.CardListView; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.smp.funwithmusic.R; import com.smp.funwithmusic.adapters.SongCardAdapter; import com.smp.funwithmusic.dataobjects.Song; import com.smp.funwithmusic.dataobjects.SongCard; import com.smp.funwithmusic.services.IdentifyMusicService; import com.smp.funwithmusic.views.ProgressWheel; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class FlowActivity extends Activity implements CardMenuListener<Card> { private List<Song> songs; private IntentFilter filter; private UpdateActivityReceiver receiver; private SongCardAdapter<SongCard> cardsAdapter; private CardListView cardsList; private String lastArtist; private View idDialog; private View welcomeScreen; private RequestQueue queue; private class UpdateActivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ACTION_REMOVE_IDENTIFY)) { viewGone(idDialog); } else if (intent.getAction().equals(ACTION_ADD_SONG)) { addCardsFromList(); if (intent.getBooleanExtra(EXTRA_FROM_ID, false)) scrollToBottomOfList(); } } } private void resetArtist() { lastArtist = null; } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); saveSongs(); resetArtist(); queue.cancelAll(TAG_VOLLEY); } // reseting the imageUrl and lryics will allow the program to attempt to // find them the next time if it couldn't this time. // Song object determines if they should be reset internally. private void saveSongs() { for (Song song : songs) { song.resetImageUrl(); song.resetLyrics(); } writeObjectToFile(this, SONG_FILE_NAME, songs); } @Override protected void onResume() { super.onResume(); addCardsFromList(); scrollToBottomOfList(); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter); if (isMyServiceRunning(this, IdentifyMusicService.class)) { viewVisible(idDialog); } else { viewGone(idDialog); } } // Scrolls the view so that last item is at the bottom of the screen. // private void scrollToBottomOfList() { cardsList.post(new Runnable() { @Override public void run() { // Select the last row so it will scroll into view cardsList.setSelection(cardsAdapter.getCount() - 1); } }); } // need to make old OS friendly @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flow); queue = Volley.newRequestQueue(this); - cardsAdapter = new SongCardAdapter<SongCard>(getApplicationContext(), queue, TAG_VOLLEY); + cardsAdapter = new SongCardAdapter<SongCard>(this, queue, TAG_VOLLEY); cardsAdapter.setAccentColorRes(android.R.color.holo_blue_dark); cardsAdapter.setPopupMenu(R.menu.card_popup, this); // the popup menu // callback is this // activity TextView progressText = (TextView) findViewById(R.id.progress_text); progressText.setText(getResources().getText(R.string.identify)); idDialog = findViewById(R.id.progress); welcomeScreen = findViewById(R.id.welcome_screen); cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(cardsAdapter); cardsList.setOnCardClickListener(new CardListView.CardClickListener() { @SuppressWarnings("rawtypes") @Override public void onCardClick(int index, CardBase card, View view) { SongCard songCard = (SongCard) card; Song song = songCard.getSong(); if (song.hasLyrics()) { Intent intent = new Intent(FlowActivity.this, WebActivity.class); intent.putExtra(WEB_URL, song.getFullLyricsUrl()); startActivity(intent); /* * Uri uri = Uri.parse(song.getFullLyricsUrl()); Intent * intent = new Intent(Intent.ACTION_VIEW, uri); * startActivity(intent); */ } } }); filter = new IntentFilter(); filter.addAction(ACTION_ADD_SONG); filter.addAction(ACTION_REMOVE_IDENTIFY); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new UpdateActivityReceiver(); } private void addCardsFromList() { // songs never is null songs = getSongList(this); cardsAdapter.clear(); cardsAdapter.notifyDataSetChanged(); for (Song song : songs) { addCard(song); } if (cardsAdapter.getCount() == 0) { viewVisible(welcomeScreen); } else { viewGone(welcomeScreen); } } // Adds to same stack if the artist is the same. private void addCard(final Song song) { // lastArtist null check probably not necessary here. Locale locale = Locale.getDefault(); if (cardsAdapter.getCount() != 0 && lastArtist != null && lastArtist.toUpperCase(locale).equals(song.getArtist().toUpperCase(locale))) { cardsAdapter.add(new SongCard(song, this)); return; } lastArtist = song.getArtist(); cardsAdapter.add(new CardHeader(song.getArtist()) .setAction(this, R.string.artist_info, new CardHeader.ActionListener() { @Override public void onClick(CardHeader header) { Intent intent = new Intent(FlowActivity.this, ArtistActivity.class); intent.putExtra(ARTIST_NAME, song.getArtist()); startActivity(intent); } })); cardsAdapter.add(new SongCard(song, this)); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.clear: doDeleteFlow(this); resetArtist(); addCardsFromList(); break; case R.id.listen: if (!isMyServiceRunning(this, IdentifyMusicService.class)) { doListen(getApplicationContext(), idDialog); } break; default: return false; } return true; } public static void doListen(Context context, final View idDialog) { viewVisible(idDialog); Intent intent = new Intent(context, IdentifyMusicService.class); context.startService(intent); } public static void viewVisible(final View view) { view.post(new Runnable() { @Override public void run() { ProgressWheel pw = (ProgressWheel) view.findViewById(R.id.pw_spinner); if (pw != null) pw.spin(); view.setVisibility(View.VISIBLE); } }); } public static void viewGone(final View view) { view.post(new Runnable() { @Override public void run() { ProgressWheel pw = (ProgressWheel) view.findViewById(R.id.pw_spinner); if (pw != null) pw.stopSpinning(); view.setVisibility(View.GONE); } }); } public static void doDeleteFlow(Context context) { context.deleteFile(SONG_FILE_NAME); Toast.makeText(context, TOAST_FLOW_DELETED, Toast.LENGTH_SHORT).show(); } @Override public void onMenuItemClick(Card card, MenuItem item) { } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_flow, menu); return true; } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flow); queue = Volley.newRequestQueue(this); cardsAdapter = new SongCardAdapter<SongCard>(getApplicationContext(), queue, TAG_VOLLEY); cardsAdapter.setAccentColorRes(android.R.color.holo_blue_dark); cardsAdapter.setPopupMenu(R.menu.card_popup, this); // the popup menu // callback is this // activity TextView progressText = (TextView) findViewById(R.id.progress_text); progressText.setText(getResources().getText(R.string.identify)); idDialog = findViewById(R.id.progress); welcomeScreen = findViewById(R.id.welcome_screen); cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(cardsAdapter); cardsList.setOnCardClickListener(new CardListView.CardClickListener() { @SuppressWarnings("rawtypes") @Override public void onCardClick(int index, CardBase card, View view) { SongCard songCard = (SongCard) card; Song song = songCard.getSong(); if (song.hasLyrics()) { Intent intent = new Intent(FlowActivity.this, WebActivity.class); intent.putExtra(WEB_URL, song.getFullLyricsUrl()); startActivity(intent); /* * Uri uri = Uri.parse(song.getFullLyricsUrl()); Intent * intent = new Intent(Intent.ACTION_VIEW, uri); * startActivity(intent); */ } } }); filter = new IntentFilter(); filter.addAction(ACTION_ADD_SONG); filter.addAction(ACTION_REMOVE_IDENTIFY); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new UpdateActivityReceiver(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flow); queue = Volley.newRequestQueue(this); cardsAdapter = new SongCardAdapter<SongCard>(this, queue, TAG_VOLLEY); cardsAdapter.setAccentColorRes(android.R.color.holo_blue_dark); cardsAdapter.setPopupMenu(R.menu.card_popup, this); // the popup menu // callback is this // activity TextView progressText = (TextView) findViewById(R.id.progress_text); progressText.setText(getResources().getText(R.string.identify)); idDialog = findViewById(R.id.progress); welcomeScreen = findViewById(R.id.welcome_screen); cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(cardsAdapter); cardsList.setOnCardClickListener(new CardListView.CardClickListener() { @SuppressWarnings("rawtypes") @Override public void onCardClick(int index, CardBase card, View view) { SongCard songCard = (SongCard) card; Song song = songCard.getSong(); if (song.hasLyrics()) { Intent intent = new Intent(FlowActivity.this, WebActivity.class); intent.putExtra(WEB_URL, song.getFullLyricsUrl()); startActivity(intent); /* * Uri uri = Uri.parse(song.getFullLyricsUrl()); Intent * intent = new Intent(Intent.ACTION_VIEW, uri); * startActivity(intent); */ } } }); filter = new IntentFilter(); filter.addAction(ACTION_ADD_SONG); filter.addAction(ACTION_REMOVE_IDENTIFY); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new UpdateActivityReceiver(); }
diff --git a/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/scoping/XcoreResourceDescriptionStrategy.java b/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/scoping/XcoreResourceDescriptionStrategy.java index 9d45692..d5034ff 100644 --- a/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/scoping/XcoreResourceDescriptionStrategy.java +++ b/org.eclipse.emf.ecore.xcore/src/org/eclipse/emf/ecore/xcore/scoping/XcoreResourceDescriptionStrategy.java @@ -1,129 +1,131 @@ package org.eclipse.emf.ecore.xcore.scoping; import java.util.Collections; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenDataType; import org.eclipse.emf.codegen.ecore.genmodel.GenModelFactory; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcoreFactory; import org.eclipse.emf.ecore.xcore.XAnnotationDirective; import org.eclipse.emf.ecore.xcore.XClass; import org.eclipse.emf.ecore.xcore.XDataType; import org.eclipse.emf.ecore.xcore.XEnum; import org.eclipse.emf.ecore.xcore.XPackage; import org.eclipse.xtext.common.types.JvmEnumerationType; import org.eclipse.xtext.common.types.JvmGenericType; import org.eclipse.xtext.common.types.TypesFactory; import org.eclipse.xtext.naming.IQualifiedNameProvider; import org.eclipse.xtext.naming.QualifiedName; import org.eclipse.xtext.resource.EObjectDescription; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.impl.DefaultResourceDescriptionStrategy; import org.eclipse.xtext.util.IAcceptor; import com.google.inject.Inject; public class XcoreResourceDescriptionStrategy extends DefaultResourceDescriptionStrategy { @Inject(optional=true) private TypesFactory typesFactory = TypesFactory.eINSTANCE; @Inject(optional=true) private EcoreFactory ecoreFactory = EcoreFactory.eINSTANCE; @Inject(optional=true) private GenModelFactory genFactory = GenModelFactory.eINSTANCE; @Inject private LazyCreationProxyUriConverter proxyTool; @Inject private IQualifiedNameProvider nameProvider; @Override public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof XPackage) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); - qn = QualifiedName.create(qn.toString()); - URI uri = eObject.eResource().getURI(); - createEPackageDescription(uri, acceptor, qn); + if (qn != null) + { + URI uri = eObject.eResource().getURI(); + createEPackageDescription(uri, acceptor, qn); + } } if (eObject instanceof XClass) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); createGenModelDescription(uri, acceptor, qn); createEcoreDescription(uri, acceptor, qn); createJvmTypesDescription(uri, acceptor, qn); } return false; } if (eObject instanceof XDataType) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); GenDataType genDatatype = genFactory.createGenDataType(); proxyTool.installProxyURI(uri, genDatatype, qn); acceptor.accept(EObjectDescription.create(qn, genDatatype)); if (eObject instanceof XEnum) { createJvmEnumDescription(uri, acceptor, qn); } } return false; } if (eObject instanceof XAnnotationDirective) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { acceptor.accept(EObjectDescription.create(qn, eObject)); } } return true; } protected void createJvmTypesDescription(URI resourceURI, IAcceptor<IEObjectDescription> acceptor, QualifiedName qn) { JvmGenericType theInterface = typesFactory.createJvmGenericType(); proxyTool.installProxyURI(resourceURI, theInterface, qn); acceptor.accept(EObjectDescription.create(qn, theInterface)); // TODO This isn't right. // It's bad new have logic like this in multiple places. // We need to know the proper package name which only the GenPackage knows. // It's even possible that separate interface and implement classes is suppressed... // QualifiedName implClassName = QualifiedName.create(qn.toString()+"Impl"); JvmGenericType theImplClass = typesFactory.createJvmGenericType(); proxyTool.installProxyURI(resourceURI, theImplClass, implClassName); acceptor.accept(EObjectDescription.create(implClassName, theImplClass)); } protected void createJvmEnumDescription(URI resourceURI, IAcceptor<IEObjectDescription> acceptor, QualifiedName qn) { JvmEnumerationType theEnum = typesFactory.createJvmEnumerationType(); proxyTool.installProxyURI(resourceURI, theEnum, qn); acceptor.accept(EObjectDescription.create(qn, theEnum)); } protected void createEcoreDescription(URI resourceURI, IAcceptor<IEObjectDescription> acceptor, QualifiedName qn) { EClass eclass = ecoreFactory.createEClass(); proxyTool.installProxyURI(resourceURI, eclass, qn); acceptor.accept(EObjectDescription.create(qn, eclass)); } protected void createEPackageDescription(URI resourceURI, IAcceptor<IEObjectDescription> acceptor, QualifiedName qn) { EPackage ePackage = ecoreFactory.createEPackage(); proxyTool.installProxyURI(resourceURI, ePackage, qn); acceptor.accept(EObjectDescription.create(qn, ePackage, Collections.singletonMap("nsURI", "true"))); } protected void createGenModelDescription(URI resourceURI, IAcceptor<IEObjectDescription> acceptor, QualifiedName qn) { GenClass genClass = genFactory.createGenClass(); proxyTool.installProxyURI(resourceURI, genClass, qn); acceptor.accept(EObjectDescription.create(qn, genClass)); } }
true
true
public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof XPackage) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); qn = QualifiedName.create(qn.toString()); URI uri = eObject.eResource().getURI(); createEPackageDescription(uri, acceptor, qn); } if (eObject instanceof XClass) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); createGenModelDescription(uri, acceptor, qn); createEcoreDescription(uri, acceptor, qn); createJvmTypesDescription(uri, acceptor, qn); } return false; } if (eObject instanceof XDataType) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); GenDataType genDatatype = genFactory.createGenDataType(); proxyTool.installProxyURI(uri, genDatatype, qn); acceptor.accept(EObjectDescription.create(qn, genDatatype)); if (eObject instanceof XEnum) { createJvmEnumDescription(uri, acceptor, qn); } } return false; } if (eObject instanceof XAnnotationDirective) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { acceptor.accept(EObjectDescription.create(qn, eObject)); } } return true; }
public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof XPackage) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); createEPackageDescription(uri, acceptor, qn); } } if (eObject instanceof XClass) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); createGenModelDescription(uri, acceptor, qn); createEcoreDescription(uri, acceptor, qn); createJvmTypesDescription(uri, acceptor, qn); } return false; } if (eObject instanceof XDataType) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { URI uri = eObject.eResource().getURI(); GenDataType genDatatype = genFactory.createGenDataType(); proxyTool.installProxyURI(uri, genDatatype, qn); acceptor.accept(EObjectDescription.create(qn, genDatatype)); if (eObject instanceof XEnum) { createJvmEnumDescription(uri, acceptor, qn); } } return false; } if (eObject instanceof XAnnotationDirective) { QualifiedName qn = nameProvider.getFullyQualifiedName(eObject); if (qn != null) { acceptor.accept(EObjectDescription.create(qn, eObject)); } } return true; }
diff --git a/jipdbs-admin/src/main/java/jipdbs/admin/commands/UpdateAliasIp.java b/jipdbs-admin/src/main/java/jipdbs/admin/commands/UpdateAliasIp.java index 9b323d9..69b3f4f 100644 --- a/jipdbs-admin/src/main/java/jipdbs/admin/commands/UpdateAliasIp.java +++ b/jipdbs-admin/src/main/java/jipdbs/admin/commands/UpdateAliasIp.java @@ -1,145 +1,145 @@ package jipdbs.admin.commands; import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import jipdbs.admin.Command; import jipdbs.admin.utils.EntityIterator; import jipdbs.admin.utils.EntityIterator.Callback; import jipdbs.core.model.Alias; import jipdbs.core.model.AliasIP; import jipdbs.core.model.Player; import jipdbs.core.model.dao.AliasDAO; import jipdbs.core.model.dao.impl.AliasDAOImpl; import jipdbs.core.util.LocalCache; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Transaction; public class UpdateAliasIp extends Command { static int count = 0; @Override protected void execute(String[] args) throws Exception { final long maxEntities = 10000000000L; final AliasDAO aliasDAO = new AliasDAOImpl(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Query playerQuery = new Query("Player"); //playerQuery.addFilter("nickname", FilterOperator.EQUAL, ""); PreparedQuery pq = ds.prepare(playerQuery); final int total = pq.countEntities(withLimit(Integer.MAX_VALUE)); count = 0; System.out.println("Processing " + total + " records."); EntityIterator.iterate(playerQuery, maxEntities, new Callback() { @SuppressWarnings("deprecation") @Override public void withEntity(Entity entity, DatastoreService ds) throws Exception { final Player player = new Player(entity); count = count + 1; if (player.getNickname() != null) return; Alias lastAlias = aliasDAO.getLastUsedAlias(player.getKey()); player.setNickname(lastAlias.getNickname()); player.setIp(lastAlias.getIp()); List<Alias> aliases = aliasDAO.findByPlayer(player.getKey(), 0, 1000, null); List<Key> deleteAlias = new ArrayList<Key>(); Map<String, Entity> mapAlias = new LinkedHashMap<String, Entity>(); Map<String, Entity> mapIP = new LinkedHashMap<String, Entity>(); for (Alias alias : aliases) { deleteAlias.add(alias.getKey()); if (alias.getCreated() == null) alias.setCreated(new Date()); if (alias.getUpdated() == null) alias.setUpdated(new Date()); Alias newAlias = null; if (mapAlias.containsKey(alias.getNickname())) { newAlias = new Alias(mapAlias.get(alias.getNickname())); newAlias.setCount(newAlias.getCount() + 1L); if (alias.getUpdated().after(newAlias.getUpdated())) { newAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newAlias.getCreated())) { newAlias.setCreated(alias.getCreated()); } } else { newAlias = new Alias(player.getKey()); newAlias.setCount(1L); - newAlias.setNickname(player.getNickname()); + newAlias.setNickname(alias.getNickname()); newAlias.setCreated(alias.getCreated()); newAlias.setUpdated(alias.getUpdated()); newAlias.setNgrams(alias.getNgrams()); newAlias.setServer(player.getServer()); } mapAlias.put(alias.getNickname(), newAlias.toEntity()); AliasIP newIpAlias = null; if (mapIP.containsKey(alias.getIp())) { newIpAlias = new AliasIP(mapIP.get(alias.getIp())); newIpAlias.setCount(newIpAlias.getCount() + 1L); if (alias.getUpdated().after(newIpAlias.getUpdated())) { newIpAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newIpAlias.getCreated())) { newIpAlias.setCreated(alias.getCreated()); } } else { newIpAlias = new AliasIP(player.getKey()); newIpAlias.setCount(1L); newIpAlias.setCreated(alias.getCreated()); newIpAlias.setIp(alias.getIp()); newIpAlias.setUpdated(alias.getUpdated()); } mapIP.put(alias.getIp(), newIpAlias.toEntity()); } Transaction tx = ds.beginTransaction(); try { ds.put(player.toEntity()); ds.put(mapAlias.values()); ds.put(mapIP.values()); ds.delete(deleteAlias); tx.commit(); } catch (Exception e) { System.err.println("Player: " + player.getGuid()); System.err.println(e.getMessage()); } finally { if (tx.isActive()) tx.rollback(); } System.out.println("%" + (count * 100) / total); } }); LocalCache.getInstance().clearAll(); System.out.print("Done"); } }
true
true
protected void execute(String[] args) throws Exception { final long maxEntities = 10000000000L; final AliasDAO aliasDAO = new AliasDAOImpl(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Query playerQuery = new Query("Player"); //playerQuery.addFilter("nickname", FilterOperator.EQUAL, ""); PreparedQuery pq = ds.prepare(playerQuery); final int total = pq.countEntities(withLimit(Integer.MAX_VALUE)); count = 0; System.out.println("Processing " + total + " records."); EntityIterator.iterate(playerQuery, maxEntities, new Callback() { @SuppressWarnings("deprecation") @Override public void withEntity(Entity entity, DatastoreService ds) throws Exception { final Player player = new Player(entity); count = count + 1; if (player.getNickname() != null) return; Alias lastAlias = aliasDAO.getLastUsedAlias(player.getKey()); player.setNickname(lastAlias.getNickname()); player.setIp(lastAlias.getIp()); List<Alias> aliases = aliasDAO.findByPlayer(player.getKey(), 0, 1000, null); List<Key> deleteAlias = new ArrayList<Key>(); Map<String, Entity> mapAlias = new LinkedHashMap<String, Entity>(); Map<String, Entity> mapIP = new LinkedHashMap<String, Entity>(); for (Alias alias : aliases) { deleteAlias.add(alias.getKey()); if (alias.getCreated() == null) alias.setCreated(new Date()); if (alias.getUpdated() == null) alias.setUpdated(new Date()); Alias newAlias = null; if (mapAlias.containsKey(alias.getNickname())) { newAlias = new Alias(mapAlias.get(alias.getNickname())); newAlias.setCount(newAlias.getCount() + 1L); if (alias.getUpdated().after(newAlias.getUpdated())) { newAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newAlias.getCreated())) { newAlias.setCreated(alias.getCreated()); } } else { newAlias = new Alias(player.getKey()); newAlias.setCount(1L); newAlias.setNickname(player.getNickname()); newAlias.setCreated(alias.getCreated()); newAlias.setUpdated(alias.getUpdated()); newAlias.setNgrams(alias.getNgrams()); newAlias.setServer(player.getServer()); } mapAlias.put(alias.getNickname(), newAlias.toEntity()); AliasIP newIpAlias = null; if (mapIP.containsKey(alias.getIp())) { newIpAlias = new AliasIP(mapIP.get(alias.getIp())); newIpAlias.setCount(newIpAlias.getCount() + 1L); if (alias.getUpdated().after(newIpAlias.getUpdated())) { newIpAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newIpAlias.getCreated())) { newIpAlias.setCreated(alias.getCreated()); } } else { newIpAlias = new AliasIP(player.getKey()); newIpAlias.setCount(1L); newIpAlias.setCreated(alias.getCreated()); newIpAlias.setIp(alias.getIp()); newIpAlias.setUpdated(alias.getUpdated()); } mapIP.put(alias.getIp(), newIpAlias.toEntity()); } Transaction tx = ds.beginTransaction(); try { ds.put(player.toEntity()); ds.put(mapAlias.values()); ds.put(mapIP.values()); ds.delete(deleteAlias); tx.commit(); } catch (Exception e) { System.err.println("Player: " + player.getGuid()); System.err.println(e.getMessage()); } finally { if (tx.isActive()) tx.rollback(); } System.out.println("%" + (count * 100) / total); } }); LocalCache.getInstance().clearAll(); System.out.print("Done"); }
protected void execute(String[] args) throws Exception { final long maxEntities = 10000000000L; final AliasDAO aliasDAO = new AliasDAOImpl(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Query playerQuery = new Query("Player"); //playerQuery.addFilter("nickname", FilterOperator.EQUAL, ""); PreparedQuery pq = ds.prepare(playerQuery); final int total = pq.countEntities(withLimit(Integer.MAX_VALUE)); count = 0; System.out.println("Processing " + total + " records."); EntityIterator.iterate(playerQuery, maxEntities, new Callback() { @SuppressWarnings("deprecation") @Override public void withEntity(Entity entity, DatastoreService ds) throws Exception { final Player player = new Player(entity); count = count + 1; if (player.getNickname() != null) return; Alias lastAlias = aliasDAO.getLastUsedAlias(player.getKey()); player.setNickname(lastAlias.getNickname()); player.setIp(lastAlias.getIp()); List<Alias> aliases = aliasDAO.findByPlayer(player.getKey(), 0, 1000, null); List<Key> deleteAlias = new ArrayList<Key>(); Map<String, Entity> mapAlias = new LinkedHashMap<String, Entity>(); Map<String, Entity> mapIP = new LinkedHashMap<String, Entity>(); for (Alias alias : aliases) { deleteAlias.add(alias.getKey()); if (alias.getCreated() == null) alias.setCreated(new Date()); if (alias.getUpdated() == null) alias.setUpdated(new Date()); Alias newAlias = null; if (mapAlias.containsKey(alias.getNickname())) { newAlias = new Alias(mapAlias.get(alias.getNickname())); newAlias.setCount(newAlias.getCount() + 1L); if (alias.getUpdated().after(newAlias.getUpdated())) { newAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newAlias.getCreated())) { newAlias.setCreated(alias.getCreated()); } } else { newAlias = new Alias(player.getKey()); newAlias.setCount(1L); newAlias.setNickname(alias.getNickname()); newAlias.setCreated(alias.getCreated()); newAlias.setUpdated(alias.getUpdated()); newAlias.setNgrams(alias.getNgrams()); newAlias.setServer(player.getServer()); } mapAlias.put(alias.getNickname(), newAlias.toEntity()); AliasIP newIpAlias = null; if (mapIP.containsKey(alias.getIp())) { newIpAlias = new AliasIP(mapIP.get(alias.getIp())); newIpAlias.setCount(newIpAlias.getCount() + 1L); if (alias.getUpdated().after(newIpAlias.getUpdated())) { newIpAlias.setUpdated(alias.getUpdated()); } if (alias.getCreated().before(newIpAlias.getCreated())) { newIpAlias.setCreated(alias.getCreated()); } } else { newIpAlias = new AliasIP(player.getKey()); newIpAlias.setCount(1L); newIpAlias.setCreated(alias.getCreated()); newIpAlias.setIp(alias.getIp()); newIpAlias.setUpdated(alias.getUpdated()); } mapIP.put(alias.getIp(), newIpAlias.toEntity()); } Transaction tx = ds.beginTransaction(); try { ds.put(player.toEntity()); ds.put(mapAlias.values()); ds.put(mapIP.values()); ds.delete(deleteAlias); tx.commit(); } catch (Exception e) { System.err.println("Player: " + player.getGuid()); System.err.println(e.getMessage()); } finally { if (tx.isActive()) tx.rollback(); } System.out.println("%" + (count * 100) / total); } }); LocalCache.getInstance().clearAll(); System.out.print("Done"); }