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/FP/Server.java b/src/FP/Server.java
index eaa234b..7e30a33 100644
--- a/src/FP/Server.java
+++ b/src/FP/Server.java
@@ -1,96 +1,99 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package FP;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import no.ntnu.fp.net.admin.Log;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.net.co.ConnectionImpl;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
* @author lycantrophe
*/
public class Server {
public static Map<String, Person> persons;
public static Map<String, Location> locations;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Create log
Log log = new Log();
log.setLogName("Server-side application");
buildAllObjects();
// server connection instance, listen on port 5555
Connection server = new ConnectionImpl(5555);
// each new connection lives in its own instance
- Connection conn;
+ // Connection conn;
// TODO: Thread at this point?
while (true) {
try {
- conn = server.accept();
+ System.out.println("ACCEPTING CONNECTIONS");
+ Connection conn = server.accept();
Thread thread = new ServerThread(conn);
- thread.run();
+ System.out.println("About to start thread");
+ thread.start();
+ System.err.println("Thread started");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void buildAllObjects() {
System.out.println("Building objects!");
Query query = new Query();
persons = new HashMap<String, Person>();
// Get persons
for (Person other : query.getPersons()) {
// User.addPerson(other);
persons.put(other.getUsername(), other);
}
// Get locations
locations = new HashMap<String, Location>();
for (Location location : query.getLocations()) {
locations.put(location.getName(), location);
}
// Create appointments
query.createAllAppointments(persons, locations);
query.close();
}
public static String Serialize(Object object) throws IOException {
BASE64Encoder encode = new BASE64Encoder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(object);
out.flush();
return encode.encode(baos.toByteArray());
}
public static Object Deserialize(String input) throws IOException, ClassNotFoundException {
BASE64Decoder decode = new BASE64Decoder();
ByteArrayInputStream bis = new ByteArrayInputStream(decode.decodeBuffer(input));
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
}
| false | true | public static void main(String[] args) {
// TODO code application logic here
// Create log
Log log = new Log();
log.setLogName("Server-side application");
buildAllObjects();
// server connection instance, listen on port 5555
Connection server = new ConnectionImpl(5555);
// each new connection lives in its own instance
Connection conn;
// TODO: Thread at this point?
while (true) {
try {
conn = server.accept();
Thread thread = new ServerThread(conn);
thread.run();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
// TODO code application logic here
// Create log
Log log = new Log();
log.setLogName("Server-side application");
buildAllObjects();
// server connection instance, listen on port 5555
Connection server = new ConnectionImpl(5555);
// each new connection lives in its own instance
// Connection conn;
// TODO: Thread at this point?
while (true) {
try {
System.out.println("ACCEPTING CONNECTIONS");
Connection conn = server.accept();
Thread thread = new ServerThread(conn);
System.out.println("About to start thread");
thread.start();
System.err.println("Thread started");
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
diff --git a/src/main/java/de/deyovi/chat/core/interpreters/impl/ImageSegmentInterpreter.java b/src/main/java/de/deyovi/chat/core/interpreters/impl/ImageSegmentInterpreter.java
index 6ea722b..669994c 100755
--- a/src/main/java/de/deyovi/chat/core/interpreters/impl/ImageSegmentInterpreter.java
+++ b/src/main/java/de/deyovi/chat/core/interpreters/impl/ImageSegmentInterpreter.java
@@ -1,61 +1,61 @@
package de.deyovi.chat.core.interpreters.impl;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
import de.deyovi.chat.core.interpreters.InputSegmentInterpreter;
import de.deyovi.chat.core.objects.Segment;
import de.deyovi.chat.core.objects.Segment.ContentType;
import de.deyovi.chat.core.objects.impl.ThumbnailedSegment;
import de.deyovi.chat.core.services.impl.ImageThumbGeneratorService;
public class ImageSegmentInterpreter implements InputSegmentInterpreter {
private final static Logger logger = Logger.getLogger(ImageSegmentInterpreter.class);
private final static String[] EXTENSIONS = new String[] {
"jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp"
};
@Override
public Segment[] interprete(InterpretableSegment segment) {
if (segment.isURL()) {
String user = segment.getUser();
String content = segment.getContent();
logger.debug("file " + content);
URL url = segment.getURL();
String name = url.getFile();
if (name == null || name.isEmpty()) {
name = "image_" + url.getHost();
} else {
- int ixOfSlash = name.lastIndexOf(File.separatorChar);
+ int ixOfSlash = name.lastIndexOf('/');
name = name.substring(ixOfSlash + 1);
}
URLConnection urlConnection = segment.getConnection();
String contentType = urlConnection.getContentType();
ImageThumbGeneratorService thumbGenerator = new ImageThumbGeneratorService();
if (contentType != null && contentType.startsWith("image/")) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
} else {
String urlAsString = content;
String lcUrlAsString = urlAsString.toLowerCase().trim();
for (String extension : EXTENSIONS) {
if (lcUrlAsString.endsWith(extension)) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
}
}
}
}
return null;
}
// TODO write Test!
// public static void main(String[] args) throws IOException {
// java.net.URL url = new java.net.URL("http://upload.wikimedia.org/wikipedia/commons/9/92/Colorful_spring_garden.jpg");
// new ImageProcessorPlugin().process(url.openConnection());
// }
}
| true | true | public Segment[] interprete(InterpretableSegment segment) {
if (segment.isURL()) {
String user = segment.getUser();
String content = segment.getContent();
logger.debug("file " + content);
URL url = segment.getURL();
String name = url.getFile();
if (name == null || name.isEmpty()) {
name = "image_" + url.getHost();
} else {
int ixOfSlash = name.lastIndexOf(File.separatorChar);
name = name.substring(ixOfSlash + 1);
}
URLConnection urlConnection = segment.getConnection();
String contentType = urlConnection.getContentType();
ImageThumbGeneratorService thumbGenerator = new ImageThumbGeneratorService();
if (contentType != null && contentType.startsWith("image/")) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
} else {
String urlAsString = content;
String lcUrlAsString = urlAsString.toLowerCase().trim();
for (String extension : EXTENSIONS) {
if (lcUrlAsString.endsWith(extension)) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
}
}
}
}
return null;
}
| public Segment[] interprete(InterpretableSegment segment) {
if (segment.isURL()) {
String user = segment.getUser();
String content = segment.getContent();
logger.debug("file " + content);
URL url = segment.getURL();
String name = url.getFile();
if (name == null || name.isEmpty()) {
name = "image_" + url.getHost();
} else {
int ixOfSlash = name.lastIndexOf('/');
name = name.substring(ixOfSlash + 1);
}
URLConnection urlConnection = segment.getConnection();
String contentType = urlConnection.getContentType();
ImageThumbGeneratorService thumbGenerator = new ImageThumbGeneratorService();
if (contentType != null && contentType.startsWith("image/")) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
} else {
String urlAsString = content;
String lcUrlAsString = urlAsString.toLowerCase().trim();
for (String extension : EXTENSIONS) {
if (lcUrlAsString.endsWith(extension)) {
return new Segment[] { new ThumbnailedSegment(user, name, content, ContentType.IMAGE, urlConnection, thumbGenerator)};
}
}
}
}
return null;
}
|
diff --git a/src/persistence/grails/orm/HibernateCriteriaBuilder.java b/src/persistence/grails/orm/HibernateCriteriaBuilder.java
index 8b229ab0f..493dc3804 100644
--- a/src/persistence/grails/orm/HibernateCriteriaBuilder.java
+++ b/src/persistence/grails/orm/HibernateCriteriaBuilder.java
@@ -1,969 +1,969 @@
/*
* 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 grails.orm;
import groovy.lang.*;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.*;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import java.util.*;
/**
* <p>Wraps the Hibernate Criteria API in a builder. The builder can be retrieved through the "createCriteria()" dynamic static
* method of Grails domain classes (Example in Groovy):
*
* <pre>
* def c = Account.createCriteria()
* def results = c {
* projections {
* groupProperty("branch")
* }
* like("holderFirstName", "Fred%")
* and {
* between("balance", 500, 1000)
* eq("branch", "London")
* }
* maxResults(10)
* order("holderLastName", "desc")
* }
* </pre>
*
* <p>The builder can also be instantiated standalone with a SessionFactory and persistent Class instance:
*
* <pre>
* new HibernateCriteriaBuilder(clazz, sessionFactory).list {
* eq("firstName", "Fred")
* }
* </pre>
*
* @author Graeme Rocher
* @since Oct 10, 2005
*/
public class HibernateCriteriaBuilder extends GroovyObjectSupport {
public static final String AND = "and"; // builder
public static final String IS_NULL = "isNull"; // builder
public static final String IS_NOT_NULL = "isNotNull"; // builder
public static final String NOT = "not";// builder
public static final String OR = "or"; // builder
public static final String ID_EQUALS = "idEq"; // builder
public static final String IS_EMPTY = "isEmpty"; //builder
public static final String IS_NOT_EMPTY = "isNotEmpty"; //builder
public static final String BETWEEN = "between";//method
public static final String EQUALS = "eq";//method
public static final String EQUALS_PROPERTY = "eqProperty";//method
public static final String GREATER_THAN = "gt";//method
public static final String GREATER_THAN_PROPERTY = "gtProperty";//method
public static final String GREATER_THAN_OR_EQUAL = "ge";//method
public static final String GREATER_THAN_OR_EQUAL_PROPERTY = "geProperty";//method
public static final String ILIKE = "ilike";//method
public static final String IN = "in";//method
public static final String LESS_THAN = "lt"; //method
public static final String LESS_THAN_PROPERTY = "ltProperty";//method
public static final String LESS_THAN_OR_EQUAL = "le";//method
public static final String LESS_THAN_OR_EQUAL_PROPERTY = "leProperty";//method
public static final String LIKE = "like";//method
public static final String NOT_EQUAL = "ne";//method
public static final String NOT_EQUAL_PROPERTY = "neProperty";//method
public static final String SIZE_EQUALS = "sizeEq"; //method
public static final String ORDER_DESCENDING = "desc";
public static final String ORDER_ASCENDING = "asc";
private static final String ROOT_DO_CALL = "doCall";
private static final String ROOT_CALL = "call";
private static final String LIST_CALL = "list";
private static final String LIST_DISTINCT_CALL = "listDistinct";
private static final String COUNT_CALL = "count";
private static final String GET_CALL = "get";
private static final String SCROLL_CALL = "scroll";
private static final String PROJECTIONS = "projections";
private SessionFactory sessionFactory;
private Session session;
private Class targetClass;
private Criteria criteria;
private MetaClass criteriaMetaClass;
private boolean uniqueResult = false;
private Stack logicalExpressionStack = new Stack();
private boolean participate;
private boolean scroll;
private boolean count;
private ProjectionList projectionList;
private BeanWrapper targetBean;
private List aliasStack = new ArrayList();
private static final String ALIAS = "_alias";
private ResultTransformer resultTransformer;
public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory) {
super();
this.targetClass = targetClass;
this.targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass));
this.sessionFactory = sessionFactory;
}
public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory, boolean uniqueResult) {
super();
this.targetClass = targetClass;
this.sessionFactory = sessionFactory;
this.uniqueResult = uniqueResult;
}
public void setUniqueResult(boolean uniqueResult) {
this.uniqueResult = uniqueResult;
}
/**
* A projection that selects a property name
* @param propertyName The name of the property
*/
public void property(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [property] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.property(propertyName));
}
}
/**
* A projection that selects a distince property name
* @param propertyName The property name
*/
public void distinct(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.distinct(Projections.property(propertyName)));
}
}
/**
* A distinct projection that takes a list
*
* @param propertyNames The list of distince property names
*/
public void distinct(Collection propertyNames) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node"));
}
else {
ProjectionList list = Projections.projectionList();
for (Iterator i = propertyNames.iterator(); i.hasNext();) {
Object o = i.next();
list.add(Projections.property(o.toString()));
}
this.projectionList.add(Projections.distinct(list));
}
}
/**
* Adds a projection that allows the criteria to return the property average value
*
* @param propertyName The name of the property
*/
public void avg(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [avg] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.avg(propertyName));
}
}
/**
* Calculates the property name including any alias paths
*
* @param propertyName The property name
* @return The calculated property name
*/
private String calculatePropertyName(String propertyName) {
if(this.aliasStack.size()>0) {
return this.aliasStack.get(this.aliasStack.size()-1).toString()+'.'+propertyName;
}
return propertyName;
}
/**
* Calculates the property value, converting GStrings if necessary
*
* @param propertyValue The property value
* @return The calculated property value
*/
private Object calculatePropertyValue(Object propertyValue) {
if(propertyValue instanceof GString) {
return propertyValue.toString();
}
return propertyValue;
}
/**
* Adds a projection that allows the criteria to return the property count
*
* @param propertyName The name of the property
*/
public void count(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [count] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.count(propertyName));
}
}
/**
* Adds a projection that allows the criteria to return the distinct property count
*
* @param propertyName The name of the property
*/
public void countDistinct(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [countDistinct] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.countDistinct(propertyName));
}
}
/**
* Adds a projection that allows the criteria's result to be grouped by a property
*
* @param propertyName The name of the property
*/
public void groupProperty(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [groupProperty] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.groupProperty(propertyName));
}
}
/**
* Adds a projection that allows the criteria to retrieve a maximum property value
*
* @param propertyName The name of the property
*/
public void max(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [max] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.max(propertyName));
}
}
/**
* Adds a projection that allows the criteria to retrieve a minimum property value
*
* @param propertyName The name of the property
*/
public void min(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [min] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.min(propertyName));
}
}
/**
* Adds a projection that allows the criteria to return the row count
*
*/
public void rowCount() {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [rowCount] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.rowCount());
}
}
/**
* Adds a projection that allows the criteria to retrieve the sum of the results of a property
*
* @param propertyName The name of the property
*/
public void sum(String propertyName) {
if(this.projectionList == null) {
throwRuntimeException( new IllegalArgumentException("call to [sum] must be within a [projections] node"));
}
else {
this.projectionList.add(Projections.sum(propertyName));
}
}
/**
* Sets the fetch mode of an associated path
*
* @param associationPath The name of the associated path
* @param fetchMode The fetch mode to set
*/
public void fetchMode(String associationPath, FetchMode fetchMode) {
if(criteria!=null) {
criteria.setFetchMode(associationPath, fetchMode);
}
}
/**
* Sets the resultTransformer.
* @param resultTransformer The result transformer to use.
*/
public void resultTransformer(ResultTransformer resultTransformer) {
if (criteria == null) {
throwRuntimeException( new IllegalArgumentException("Call to [resultTransformer] not supported here"));
}
this.resultTransformer = resultTransformer;
}
/**
* Creates a Criterion that compares to class properties for equality
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object eqProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [eqProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.") );
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.eqProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that compares to class properties for !equality
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object neProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [neProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.neProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is greater than the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object gtProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [gtProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.gtProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is greater than or equal to the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object geProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [geProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.geProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is less than the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object ltProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ltProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.ltProperty( propertyName, otherPropertyName ));
}
/**
* Creates a Criterion that tests if the first property is less than or equal to the second property
* @param propertyName The first property name
* @param otherPropertyName The second property name
* @return A Criterion instance
*/
public Object leProperty(String propertyName, String otherPropertyName) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [leProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
otherPropertyName = calculatePropertyName(otherPropertyName);
return addToCriteria(Restrictions.leProperty(propertyName, otherPropertyName));
}
/**
* Creates a "greater than" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object gt(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [gt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.gt(propertyName, propertyValue));
}
/**
* Creates a "greater than or equal to" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object ge(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ge] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ge(propertyName, propertyValue));
}
/**
* Creates a "less than" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object lt(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [lt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.lt(propertyName, propertyValue));
}
/**
* Creates a "less than or equal to" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return A Criterion instance
*/
public Object le(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [le] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.le(propertyName, propertyValue));
}
/**
* Creates an "equals" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
*
* @return A Criterion instance
*/
public Object eq(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [eq] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.eq(propertyName, propertyValue));
}
/**
* Creates a Criterion with from the specified property name and "like" expression
* @param propertyName The property name
* @param propertyValue The like value
*
* @return A Criterion instance
*/
public Object like(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [like] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.like(propertyName, propertyValue));
}
/**
* Creates a Criterion with from the specified property name and "ilike" (a case sensitive version of "like") expression
* @param propertyName The property name
* @param propertyValue The ilike value
*
* @return A Criterion instance
*/
public Object ilike(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ilike] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ilike(propertyName, propertyValue));
}
/**
* Applys a "in" contrain on the specified property
* @param propertyName The property name
* @param values A collection of values
*
* @return A Criterion instance
*/
public Object in(String propertyName, Collection values) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.in(propertyName, values));
}
/**
* Delegates to in as in is a Groovy keyword
**/
public Object inList(String propertyName, Collection values) {
return in(propertyName, values);
}
/**
* Delegates to in as in is a Groovy keyword
**/
public Object inList(String propertyName, Object[] values) {
return in(propertyName, values);
}
/**
* Applys a "in" contrain on the specified property
* @param propertyName The property name
* @param values A collection of values
*
* @return A Criterion instance
*/
public Object in(String propertyName, Object[] values) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.in(propertyName, values));
}
/**
* Orders by the specified property name (defaults to ascending)
*
* @param propertyName The property name to order by
* @return A Order instance
*/
public Object order(String propertyName) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here."));
propertyName = calculatePropertyName(propertyName);
Order o = Order.asc(propertyName);
this.criteria.addOrder(o);
return o;
}
/**
* Orders by the specified property name and direction
*
* @param propertyName The property name to order by
* @param direction Either "asc" for ascending or "desc" for descending
*
* @return A Order instance
*/
public Object order(String propertyName, String direction) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here."));
propertyName = calculatePropertyName(propertyName);
Order o;
if(direction.equals( ORDER_DESCENDING )) {
o = Order.desc(propertyName);
}
else {
o = Order.asc(propertyName);
}
this.criteria.addOrder(o);
return o;
}
/**
* Creates a Criterion that contrains a collection property by size
*
* @param propertyName The property name
* @param size The size to constrain by
*
* @return A Criterion instance
*/
public Object sizeEq(String propertyName, int size) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.sizeEq(propertyName, size));
}
/**
* Creates a "not equal" Criterion based on the specified property name and value
* @param propertyName The property name
* @param propertyValue The property value
* @return The criterion object
*/
public Object ne(String propertyName, Object propertyValue) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [ne] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
propertyValue = calculatePropertyValue(propertyValue);
return addToCriteria(Restrictions.ne(propertyName, propertyValue));
}
public Object notEqual(String propertyName, Object propertyValue) {
return ne(propertyName, propertyValue);
}
/**
* Creates a "between" Criterion based on the property name and specified lo and hi values
* @param propertyName The property name
* @param lo The low value
* @param hi The high value
* @return A Criterion instance
*/
public Object between(String propertyName, Object lo, Object hi) {
if(!validateSimpleExpression()) {
throwRuntimeException( new IllegalArgumentException("Call to [between] with propertyName ["+propertyName+"] not allowed here."));
}
propertyName = calculatePropertyName(propertyName);
return addToCriteria(Restrictions.between(propertyName, lo, hi));
}
private boolean validateSimpleExpression() {
if(this.criteria == null) {
return false;
}
return true;
}
public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
- invokeClosureNode(args);
+ invokeClosureNode(args[0]);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
- invokeClosureNode(args);
+ invokeClosureNode(args[0]);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
this.criteria.createAlias(name.toString(), name.toString()+ALIAS,CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(name.toString()+ALIAS);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
- invokeClosureNode(args);
+ invokeClosureNode(args[0]);
aliasStack.remove(aliasStack.size()-1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
return name;
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( (String)value ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( (String)value );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( (String)value );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty( (String)value );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
private boolean isCriteriaConstructionMethod(String name, Object[] args) {
return (name.equals(LIST_CALL) && args.length == 2 && args[0] instanceof Map && args[1] instanceof Closure) ||
(name.equals(ROOT_CALL) ||
name.equals(ROOT_DO_CALL) ||
name.equals(LIST_CALL) ||
name.equals(LIST_DISTINCT_CALL) ||
name.equals(GET_CALL) ||
name.equals(COUNT_CALL) ||
name.equals(SCROLL_CALL) && args.length == 1 && args[0] instanceof Closure);
}
private void createCriteriaInstance() {
if(TransactionSynchronizationManager.hasResource(sessionFactory)) {
this.participate = true;
this.session = ((SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)).getSession();
}
else {
this.session = sessionFactory.openSession();
}
this.criteria = this.session.createCriteria(targetClass);
this.criteriaMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(criteria.getClass());
}
private void invokeClosureNode(Object args) {
Closure callable = (Closure)args;
callable.setDelegate(this);
callable.call();
}
/**
* Throws a runtime exception where necessary to ensure the session gets closed
*/
private void throwRuntimeException(RuntimeException t) {
closeSessionFollowingException();
throw t;
}
private void closeSessionFollowingException() {
if(this.session != null && this.session.isOpen() && !this.participate) {
this.session.close();
}
if(this.criteria != null) {
this.criteria = null;
}
}
/**
* adds and returns the given criterion to the currently active criteria set.
* this might be either the root criteria or a currently open
* LogicalExpression.
*/
private Criterion addToCriteria(Criterion c) {
if (!logicalExpressionStack.isEmpty()) {
((LogicalExpression) logicalExpressionStack.peek()).args.add(c);
}
else {
this.criteria.add(c);
}
return c;
}
/**
* instances of this class are pushed onto the logicalExpressionStack
* to represent all the unfinished "and", "or", and "not" expressions.
*/
private class LogicalExpression {
final Object name;
final ArrayList args = new ArrayList();
LogicalExpression(Object name) {
this.name = name;
}
Criterion toCriterion() {
if (name.equals(NOT)) {
switch (args.size()) {
case 0:
throwRuntimeException(new IllegalArgumentException("Logical expression [not] must contain at least 1 expression"));
return null;
case 1:
return Restrictions.not((Criterion) args.get(0));
default:
// treat multiple sub-criteria as an implicit "OR"
return Restrictions.not(buildJunction(Restrictions.disjunction(), args));
}
}
else if (name.equals(AND)) {
return buildJunction(Restrictions.conjunction(), args);
}
else if (name.equals(OR)) {
return buildJunction(Restrictions.disjunction(), args);
}
else {
throwRuntimeException(new IllegalStateException("Logical expression [" + name + "] not handled!"));
return null;
}
}
// add the Criterion objects in the given list to the given junction.
Junction buildJunction(Junction junction, List criteria) {
for (Iterator i = criteria.iterator(); i.hasNext();) {
junction.add((Criterion) i.next());
}
return junction;
}
}
}
| false | true | public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
invokeClosureNode(args);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
invokeClosureNode(args);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
this.criteria.createAlias(name.toString(), name.toString()+ALIAS,CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(name.toString()+ALIAS);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
invokeClosureNode(args);
aliasStack.remove(aliasStack.size()-1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
return name;
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( (String)value ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( (String)value );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( (String)value );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty( (String)value );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
| public Object invokeMethod(String name, Object obj) {
Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj};
if(isCriteriaConstructionMethod(name, args)) {
if(this.criteria != null) {
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
}
if (name.equals(GET_CALL)) {
this.uniqueResult = true;
}
else if (name.equals(SCROLL_CALL)) {
this.scroll = true;
}
else if (name.equals(COUNT_CALL)) {
this.count = true;
}
else if (name.equals(LIST_DISTINCT_CALL)) {
this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
}
boolean paginationEnabledList = false;
createCriteriaInstance();
// Check for pagination params
if(name.equals(LIST_CALL) && args.length == 2) {
paginationEnabledList = true;
invokeClosureNode(args[1]);
} else {
invokeClosureNode(args[0]);
}
if(resultTransformer != null) {
this.criteria.setResultTransformer(resultTransformer);
}
Object result;
if(!uniqueResult) {
if(scroll) {
result = this.criteria.scroll();
}
else if(count) {
this.criteria.setProjection(Projections.rowCount());
result = this.criteria.uniqueResult();
} else if(paginationEnabledList) {
GrailsHibernateUtil.populateArgumentsForCriteria(this.criteria, (Map)args[0]);
PagedResultList pagedRes = new PagedResultList(this.criteria.list());
this.criteria.setFirstResult(0);
this.criteria.setMaxResults(Integer.MAX_VALUE);
this.criteria.setProjection(Projections.rowCount());
int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();
pagedRes.setTotalCount(totalCount);
result = pagedRes;
} else {
result = this.criteria.list();
}
}
else {
result = this.criteria.uniqueResult();
}
if(!this.participate) {
this.session.close();
}
return result;
}
else {
if(criteria==null) createCriteriaInstance();
MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(this, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(name, args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
if(metaMethod != null) {
return metaMethod.invoke(criteria, args);
}
else if(args.length == 1 && args[0] instanceof Closure) {
if(name.equals( AND ) ||
name.equals( OR ) ||
name.equals( NOT ) ) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.logicalExpressionStack.add(new LogicalExpression(name));
invokeClosureNode(args[0]);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
addToCriteria(logicalExpression.toCriterion());
return name;
} else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
this.projectionList = Projections.projectionList();
invokeClosureNode(args[0]);
if(this.projectionList != null && this.projectionList.getLength() > 0) {
this.criteria.setProjection(this.projectionList);
}
return name;
}
else if(targetBean.isReadableProperty(name.toString())) {
this.criteria.createAlias(name.toString(), name.toString()+ALIAS,CriteriaSpecification.LEFT_JOIN);
this.aliasStack.add(name.toString()+ALIAS);
// the criteria within an association node are grouped with an implicit AND
logicalExpressionStack.push(new LogicalExpression(AND));
invokeClosureNode(args[0]);
aliasStack.remove(aliasStack.size()-1);
LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.pop();
if (!logicalExpression.args.isEmpty()) {
addToCriteria(logicalExpression.toCriterion());
}
return name;
}
}
else if(args.length == 1 && args[0] != null) {
if(this.criteria == null)
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here"));
Object value = args[0];
Criterion c = null;
if(name.equals(ID_EQUALS)) {
c = Restrictions.idEq(value);
}
else {
if( name.equals( IS_NULL ) ||
name.equals( IS_NOT_NULL ) ||
name.equals( IS_EMPTY ) ||
name.equals( IS_NOT_EMPTY )) {
if(!(value instanceof String))
throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value."));
if(name.equals( IS_NULL )) {
c = Restrictions.isNull( (String)value ) ;
}
else if(name.equals( IS_NOT_NULL )) {
c = Restrictions.isNotNull( (String)value );
}
else if(name.equals( IS_EMPTY )) {
c = Restrictions.isEmpty( (String)value );
}
else if(name.equals( IS_NOT_EMPTY )) {
c = Restrictions.isNotEmpty( (String)value );
}
}
}
if(c != null) {
return addToCriteria(c);
}
}
}
closeSessionFollowingException();
throw new MissingMethodException(name, getClass(), args) ;
}
|
diff --git a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditConfigurationTemplateModel.java b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditConfigurationTemplateModel.java
index 5df5485e1..8a3e273ca 100644
--- a/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditConfigurationTemplateModel.java
+++ b/webapp/src/edu/cornell/mannlib/vitro/webapp/web/templatemodels/edit/EditConfigurationTemplateModel.java
@@ -1,774 +1,774 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.edit;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.beans.DataProperty;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.Property;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.ParamMap;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditElementVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.ConstantFieldOptions;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.SelectListGeneratorVTwo;
import edu.cornell.mannlib.vitro.webapp.web.beanswrappers.ReadOnlyBeansWrapper;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.BaseTemplateModel;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ObjectPropertyStatementTemplateModel;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual.ObjectPropertyTemplateModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
public class EditConfigurationTemplateModel extends BaseTemplateModel {
EditConfigurationVTwo editConfig;
HashMap<String, Object> pageData = new HashMap<String, Object>();
VitroRequest vreq;
private Log log = LogFactory.getLog(EditConfigurationTemplateModel.class);
public EditConfigurationTemplateModel( EditConfigurationVTwo editConfig, VitroRequest vreq) throws Exception{
this.editConfig = editConfig;
this.vreq = vreq;
//get additional data that may be required to generate template
this.retrieveEditData();
}
public String getEditKey(){
return editConfig.getEditKey();
}
public boolean isUpdate(){
return editConfig.isObjectPropertyUpdate();
}
public String getSubmitToUrl(){
return getUrl( editConfig.getSubmitToUrl() );
}
/*
* Used to calculate/retrieve/extract additional form-specific data
* Such as options for a drop-down etc.
*/
private void retrieveEditData() throws Exception {
//Get vitro request attributes for
setFormTitle();
setSubmitLabel();
//Get the form specific data
HashMap<String, Object> formSpecificData = editConfig.getFormSpecificData();
if( formSpecificData != null)
pageData.putAll(formSpecificData);
populateDropdowns();
//populate html with edit element where appropriate
populateGeneratedHtml();
}
//Based on certain pre-set fields/variables, look for what
//drop-downs need to be populated
private void populateDropdowns() throws Exception {
//For each field with an optionType defined, create the options
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
for(String fieldName: editConfig.getFields().keySet()){
FieldVTwo field = editConfig.getField(fieldName);
//TODO: Check if we even need empty options if field options do not exist
if( field.getFieldOptions() == null ){
//empty options
field.setOptions(new ConstantFieldOptions());
}
Map<String, String> optionsMap = SelectListGeneratorVTwo.getOptions(editConfig, fieldName, wdf);
optionsMap = SelectListGeneratorVTwo.getSortedMap(optionsMap, field.getFieldOptions().getCustomComparator(), vreq);
if(pageData.containsKey(fieldName)) {
log.error("Check the edit configuration setup as pageData already contains " + fieldName + " and this will be overwritten now with empty collection");
}
pageData.put(fieldName, optionsMap);
}
}
//TODO: Check if this should return a list instead
//Also check if better manipulated/handled within the freemarker form itself
private String getSelectedValue(String field) {
String selectedValue = null;
Map<String, List<String>> urisInScope = editConfig.getUrisInScope();
if(urisInScope.containsKey(field)) {
List<String> values = urisInScope.get(field);
//Unsure how to deal with multi-select drop-downs
//TODO: Handle multiple select dropdowns
selectedValue = StringUtils.join(values, ",");
}
return selectedValue;
}
private void setFormTitle() {
String predicateUri = editConfig.getPredicateUri();
if(predicateUri != null) {
if(EditConfigurationUtils.isObjectProperty(editConfig.getPredicateUri(), vreq)) {
setObjectFormTitle();
} else {
setDataFormTitle();
}
}
}
private void setDataFormTitle() {
String formTitle = "";
DataProperty prop = EditConfigurationUtils.getDataProperty(vreq);
if(prop != null) {
if( editConfig.isDataPropertyUpdate() ) {
formTitle = "Change text for: <em>"+prop.getPublicName()+"</em>";
} else {
formTitle ="Add new entry for: <em>"+prop.getPublicName()+"</em>";
}
}
pageData.put("formTitle", formTitle);
}
//Process and set data
//Both form title and submit label would depend on whether this is data property
//or object property
private void setObjectFormTitle() {
String formTitle = null;
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);
ObjectProperty prop = EditConfigurationUtils.getObjectProperty(vreq);
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
String propertyTitle = getObjectPropertyNameForDisplay();
if(objectIndividual != null) {
formTitle = "Change entry for: <em>" + propertyTitle + " </em>";
} else {
if ( prop.getOfferCreateNewOption() ) {
log.debug("property set to offer \"create new\" option; custom form: ["+prop.getCustomEntryForm()+"]");
formTitle = "Select an existing "+propertyTitle+" for "+subject.getName();
} else {
formTitle = "Add an entry to: <em>"+propertyTitle+"</em>";
}
}
pageData.put("formTitle", formTitle);
}
//Also used above and can be used in object auto complete form
public String getObjectPropertyNameForDisplay() {
// TODO modify this to get prop/class combo
String propertyTitle = null;
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);
ObjectProperty prop = EditConfigurationUtils.getObjectProperty(vreq);
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
VClass rangeClass = EditConfigurationUtils.getRangeVClass(vreq);
if(objectIndividual != null) {
propertyTitle = prop.getDomainPublic();
} else {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
if ( prop.getOfferCreateNewOption() ) {
//Try to get the name of the class to select from
VClass classOfObjectFillers = null;
if (rangeClass != null) {
classOfObjectFillers = rangeClass;
} else if( prop.getRangeVClassURI() == null ) {
// If property has no explicit range, try to get classes
List<VClass> classes = wdf.getVClassDao().getVClassesForProperty(subject.getVClassURI(), prop.getURI());
if( classes == null || classes.size() == 0 || classes.get(0) == null ){
// If property has no explicit range, we will use e.g. owl:Thing.
// Typically an allValuesFrom restriction will come into play later.
classOfObjectFillers = wdf.getVClassDao().getTopConcept();
} else {
if( classes.size() > 1 )
log.debug("Found multiple classes when attempting to get range vclass.");
classOfObjectFillers = classes.get(0);
}
}else{
classOfObjectFillers = wdf.getVClassDao().getVClassByURI(prop.getRangeVClassURI());
if( classOfObjectFillers == null )
classOfObjectFillers = wdf.getVClassDao().getTopConcept();
}
propertyTitle = classOfObjectFillers.getName();
} else {
propertyTitle = prop.getDomainPublic();
}
}
return propertyTitle;
}
private void setSubmitLabel() {
String submitLabel = null;
String predicateUri = editConfig.getPredicateUri();
if(predicateUri != null) {
if(EditConfigurationUtils.isObjectProperty(editConfig.getPredicateUri(), vreq)) {
Individual objectIndividual = EditConfigurationUtils.getObjectIndividual(vreq);
ObjectProperty prop = EditConfigurationUtils.getObjectProperty(vreq);
if(objectIndividual != null) {
submitLabel = "Save change";
} else {
if ( prop.getOfferCreateNewOption() ) {
submitLabel = "Select existing";
} else {
submitLabel = "Save entry";
}
}
} else {
if(editConfig.isDataPropertyUpdate()) {
submitLabel = "Save change";
} else {
submitLabel = "Save entry";
}
}
}
pageData.put("submitLabel", submitLabel);
}
public String getFormTitle() {
return (String) pageData.get("formTitle");
}
public String getSubmitLabel() {
return (String) pageData.get("submitLabel");
}
/*
public Map<String, String> getRangeOptions() {
Map<String, String> rangeOptions = (Map<String, String>) pageData.get("rangeOptions");
return rangeOptions;
}*/
//Get literals in scope, i.e. variable names with values assigned
public Map<String, List<Literal>> getLiteralValues() {
return editConfig.getLiteralsInScope();
}
//variables names with URIs assigned
public Map<String, List<String>> getObjectUris() {
return editConfig.getUrisInScope();
}
public List<String> getLiteralStringValue(String key) {
List<String> literalValues = new ArrayList<String>();
Map<String, List<Literal>> literalsInScope = editConfig.getLiteralsInScope();
if(literalsInScope.containsKey(key)) {
List<Literal> ls = literalsInScope.get(key);
for(Literal l: ls) {
literalValues.add(l.getString());
}
}
return literalValues;
}
//Check if possible to send in particular parameter
public String dataLiteralValueFor(String dataLiteralName) {
List<String> literalValues = getLiteralStringValue(dataLiteralName);
return StringUtils.join(literalValues, ",");
}
public String testMethod(String testValue) {
return testValue + "test";
}
public String getDataLiteralValuesAsString() {
List<String> values = getDataLiteralValues();
return StringUtils.join(values, ",");
}
public List<String> getDataLiteralValues() {
//this is the name of the text element/i.e. variable name of data value by which literal stored
String dataLiteral = getDataLiteral();
List<String> literalValues = getLiteralStringValue(dataLiteral);
return literalValues;
}
private String literalToString(Literal lit){
if( lit == null || lit.getValue() == null) return "";
String value = lit.getValue().toString();
if( "http://www.w3.org/2001/XMLSchema#anyURI".equals( lit.getDatatypeURI() )){
//strings from anyURI will be URLEncoded from the literal.
try{
value = URLDecoder.decode(value, "UTF8");
}catch(UnsupportedEncodingException ex){
log.error(ex);
}
}
return value;
}
//Get predicate
//What if this is a data property instead?
public Property getPredicateProperty() {
String predicateUri = getPredicateUri();
//If predicate uri corresponds to object property, return that
if(predicateUri != null) {
if(EditConfigurationUtils.isObjectProperty(predicateUri, vreq)){
return EditConfigurationUtils.getObjectPropertyForPredicate(this.vreq, predicateUri);
}
//otherwise return Data property
return EditConfigurationUtils.getDataPropertyForPredicate(this.vreq, predicateUri);
}
return null;
}
public ObjectProperty getObjectPredicateProperty() {
//explore usuing EditConfigurationUtils.getObjectProperty(this.vreq)
//return this.vreq.getWebappDaoFactory().getObjectPropertyDao().getObjectPropertyByURI(getPredicateUri());
return EditConfigurationUtils.getObjectPropertyForPredicate(this.vreq, getPredicateUri());
}
public DataProperty getDataPredicateProperty() {
return EditConfigurationUtils.getDataPropertyForPredicate(this.vreq, getPredicateUri());
}
public String getDataPredicatePublicDescription() {
DataProperty dp = getDataPredicateProperty();
return dp.getPublicDescription();
}
public String getPredicateUri() {
return editConfig.getPredicateUri();
}
public String getSubjectUri() {
return editConfig.getSubjectUri();
}
public String getSubjectName() {
Individual subject = EditConfigurationUtils.getIndividual(vreq, getSubjectUri());
return subject.getName();
}
public String getObjectUri() {
return editConfig.getObject();
}
public String getDomainUri() {
return EditConfigurationUtils.getDomainUri(vreq);
}
public String getRangeUri() {
return EditConfigurationUtils.getRangeUri(vreq);
}
//data literal
//Thus would depend on the literals on the form
//Here we are assuming there is only one data literal but there may be more than one
//TODO: Support multiple data literals AND/or leaving the data literal to the
public String getDataLiteral() {
List<String> literalsOnForm = editConfig.getLiteralsOnForm();
String dataLiteralName = null;
if(literalsOnForm.size() == 1) {
dataLiteralName = literalsOnForm.get(0);
}
return dataLiteralName;
}
public String getVarNameForObject() {
return editConfig.getVarNameForObject();
}
//Get data property key
//public description only appears visible for object property
public String getPropertyPublicDescription() {
return getObjectPredicateProperty().getPublicDescription();
}
//properties queried on the main object property
public boolean getPropertySelectFromExisting() {
return getObjectPredicateProperty().getSelectFromExisting();
}
//used for form title for object properties
//TODO: update because assumes domain public
public String getPropertyPublicDomainTitle() {
ObjectProperty prop = EditConfigurationUtils.getObjectProperty(vreq);
return prop.getDomainPublic();
}
//used for form title for data properties
//TODO: Update b/c assumes data property
public String getPropertyPublicName() {
DataProperty prop = EditConfigurationUtils.getDataProperty(vreq);
return prop.getPublicName();
}
public boolean getPropertyOfferCreateNewOption() {
return getObjectPredicateProperty().getOfferCreateNewOption();
}
public String getPropertyName() {
if(isObjectProperty()) {
return getPropertyPublicDomainTitle().toLowerCase();
}
if(isDataProperty()) {
return getPropertyPublicName();
}
return null;
}
//TODO: Implement statement display
public TemplateModel getObjectStatementDisplay() throws TemplateModelException {
Map<String, String> statementDisplay = new HashMap<String, String>();
String subjectUri = EditConfigurationUtils.getSubjectUri(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
String objectUri = EditConfigurationUtils.getObjectUri(vreq);
//Set data map
Map params = vreq.getParameterMap();
for (Object key : params.keySet()) {
String keyString = (String) key; //key.toString()
if (keyString.startsWith("statement_")) {
keyString = keyString.replaceFirst("statement_", "");
String value = ( (String[]) params.get(key))[0];
statementDisplay.put(keyString, value);
}
}
//If no statement parameters being sent back, then just pass back null
if(statementDisplay.size() == 0) {
return null;
}
//ObjectPropertyStatementTemplate Model should pass the object key as part of the delete url
String objectKey = vreq.getParameter("objectKey");
statementDisplay.put(objectKey, objectUri);
ObjectProperty predicate = new ObjectProperty();
predicate.setURI(predicateUri);
//Using object property statement template model here
ObjectPropertyStatementTemplateModel osm = new ObjectPropertyStatementTemplateModel(
subjectUri,
predicate,
objectKey,
statementDisplay,
null, vreq);
ReadOnlyBeansWrapper wrapper = new ReadOnlyBeansWrapper();
return wrapper.wrap(osm);
}
//HasEditor and HasReviewer Roles also expect the Property template model to be passed
public TemplateModel getObjectPropertyStatementDisplayPropertyModel() throws TemplateModelException {
Individual subject = EditConfigurationUtils.getSubjectIndividual(vreq);
ObjectProperty op = EditConfigurationUtils.getObjectProperty(vreq);
List<ObjectProperty> propList = new ArrayList<ObjectProperty>();
propList.add(op);
ObjectPropertyTemplateModel otm = ObjectPropertyTemplateModel.getObjectPropertyTemplateModel(op, subject, vreq, true, propList);
ReadOnlyBeansWrapper wrapper = new ReadOnlyBeansWrapper();
return wrapper.wrap(otm);
}
public String getDataStatementDisplay() {
//Just return the value of the data property
return getDataLiteralValuesFromParameter();
}
//Get a custom object uri for deletion if one exists, i.e. not the object uri for the property
public String getCustomDeleteObjectUri() {
return (String) vreq.getParameter("deleteObjectUri");
}
//Used for deletion in case there's a specific template to be employed
public String getDeleteTemplate() {
String templateName = vreq.getParameter("templateName");
if(templateName == null || templateName.isEmpty()) {
templateName = "propStatement-default.ftl";
}
return templateName;
}
//Retrieves data propkey from parameter and gets appropriate data value
private String getDataLiteralValuesFromParameter() {
String dataValue = null;
//Get data hash
int dataHash = EditConfigurationUtils.getDataHash(vreq);
DataPropertyStatement dps = EditConfigurationUtils.getDataPropertyStatement(vreq,
vreq.getSession(),
dataHash,
EditConfigurationUtils.getPredicateUri(vreq));
if(dps != null) {
dataValue = dps.getData().trim();
}
return dataValue;
}
//TODO:Check where this logic should actually go, copied from input element formatting tag
//Updating to enable multiple vclasses applicable to subject to be analyzed to understand possible range of types
public Map<String, String> getOfferTypesCreateNew() {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
ObjectProperty op =
wdf.getObjectPropertyDao().getObjectPropertyByURI(editConfig.getPredicateUri());
Individual sub =
wdf.getIndividualDao().getIndividualByURI(editConfig.getSubjectUri());
VClass rangeClass = EditConfigurationUtils.getRangeVClass(vreq);
List<VClass> vclasses = null;
List<VClass> subjectVClasses = sub.getVClasses();
if( subjectVClasses == null ) {
vclasses = wdf.getVClassDao().getAllVclasses();
} else if (rangeClass != null) {
List<VClass> rangeVClasses = new ArrayList<VClass>();
vclasses = new ArrayList<VClass>();
if (!rangeClass.isUnion()) {
rangeVClasses.add(rangeClass);
} else {
rangeVClasses.addAll(rangeClass.getUnionComponents());
}
for(VClass rangeVClass : rangeVClasses) {
vclasses.add(rangeVClass);
- List<String> subURIs = wdf.getVClassDao().getSubClassURIs(rangeVClass.getURI());
+ List<String> subURIs = wdf.getVClassDao().getAllSubClassURIs(rangeVClass.getURI());
for (String subClassURI : subURIs) {
VClass subClass = wdf.getVClassDao().getVClassByURI(subClassURI);
if (subClass != null) {
vclasses.add(subClass);
}
}
}
} else {
//this hash is used to make sure there are no duplicates in the vclasses
//a more elegant method may look at overriding equals/hashcode to enable a single hashset of VClass objects
HashSet<String> vclassesURIs = new HashSet<String>();
vclasses = new ArrayList<VClass>();
//Get the range vclasses applicable for the property and each vclass for the subject
for(VClass subjectVClass: subjectVClasses) {
List<VClass> rangeVclasses = wdf.getVClassDao().getVClassesForProperty(subjectVClass.getURI(), op.getURI());
//add range vclass to hash
if(rangeVclasses != null) {
for(VClass v: rangeVclasses) {
if(!vclassesURIs.contains(v.getURI())) {
vclassesURIs.add(v.getURI());
vclasses.add(v);
}
}
}
}
}
//if each subject vclass resulted in null being returned for range vclasses, then size of vclasses would be zero
if(vclasses.size() == 0) {
vclasses = wdf.getVClassDao().getAllVclasses();
}
HashMap<String,String> types = new HashMap<String, String>();
for( VClass vclass : vclasses ){
String name = null;
if( vclass.getPickListName() != null && vclass.getPickListName().length() > 0){
name = vclass.getPickListName();
}else if( vclass.getName() != null && vclass.getName().length() > 0){
name = vclass.getName();
}else if (vclass.getLocalNameWithPrefix() != null && vclass.getLocalNameWithPrefix().length() > 0){
name = vclass.getLocalNameWithPrefix();
}
if( name != null && name.length() > 0)
types.put(vclass.getURI(),name);
}
//Unlike input element formatting tag, including sorting logic here
return getSortedMap(types);
}
public Map<String,String> getSortedMap(Map<String,String> hmap){
// first make temporary list of String arrays holding both the key and its corresponding value, so that the list can be sorted with a decent comparator
List<String[]> objectsToSort = new ArrayList<String[]>(hmap.size());
for (String key:hmap.keySet()) {
String[] x = new String[2];
x[0] = key;
x[1] = hmap.get(key);
objectsToSort.add(x);
}
Collections.sort(objectsToSort, new MapComparator());
HashMap<String,String> map = new LinkedHashMap<String,String>(objectsToSort.size());
for (String[] pair:objectsToSort) {
map.put(pair[0],pair[1]);
}
return map;
}
private class MapComparator implements Comparator<String[]> {
public int compare (String[] s1, String[] s2) {
Collator collator = Collator.getInstance();
if (s2 == null) {
return 1;
} else if (s1 == null) {
return -1;
} else {
if ("".equals(s1[0])) {
return -1;
} else if ("".equals(s2[0])) {
return 1;
}
if (s2[1]==null) {
return 1;
} else if (s1[1] == null){
return -1;
} else {
return collator.compare(s1[1],s2[1]);
}
}
}
}
//booleans for checking whether predicate is data or object
public boolean isDataProperty() {
return EditConfigurationUtils.isDataProperty(getPredicateUri(), vreq);
}
public boolean isObjectProperty() {
return EditConfigurationUtils.isObjectProperty(getPredicateUri(), vreq);
}
//Additional methods that were originally in edit request dispatch controller
//to be employed here instead
public String getUrlToReturnTo() {
if( editConfig.getEntityToReturnTo() != null &&
! editConfig.getEntityToReturnTo().trim().isEmpty()) {
ParamMap params = new ParamMap();
params.put("uri", editConfig.getEntityToReturnTo());
return UrlBuilder.getUrl(UrlBuilder.Route.INDIVIDUAL, params);
}else if( vreq.getParameter("urlPattern") != null ){
return vreq.getParameter("urlPattern");
}else{
return UrlBuilder.Route.INDIVIDUAL.path();
}
}
public String getCurrentUrl() {
return EditConfigurationUtils.getEditUrl(vreq) + "?" + vreq.getQueryString();
}
public String getMainEditUrl() {
return EditConfigurationUtils.getEditUrl(vreq);
}
//this url is for canceling
public String getCancelUrl() {
String editKey = editConfig.getEditKey();
String cancelURL = EditConfigurationUtils.getCancelUrlBase(vreq) + "?editKey=" + editKey + "&cancel=true";
//Check for special return url parameter
String returnURLParameter = vreq.getParameter("returnURL");
if(returnURLParameter != null && !returnURLParameter.isEmpty() ) {
cancelURL += "&returnURL=" + returnURLParameter;
}
return cancelURL;
}
//Get confirm deletion url
public String getDeleteProcessingUrl() {
return vreq.getContextPath() + "/deletePropertyController";
}
//TODO: Check if this logic is correct and delete prohibited does not expect a specific value
public boolean isDeleteProhibited() {
String deleteProhibited = vreq.getParameter("deleteProhibited");
return (deleteProhibited != null && !deleteProhibited.isEmpty());
}
public String getDatapropKey() {
if( editConfig.getDatapropKey() == null )
return null;
else
return editConfig.getDatapropKey().toString();
}
public DataPropertyStatement getDataPropertyStatement() {
int dataHash = EditConfigurationUtils.getDataHash(vreq);
String predicateUri = EditConfigurationUtils.getPredicateUri(vreq);
return EditConfigurationUtils.getDataPropertyStatement(vreq,
vreq.getSession(),
dataHash,
predicateUri);
}
//Check whether deletion form should be included for default object property
public boolean getIncludeDeletionForm() {
if( isDeleteProhibited() )
return false;
if( isObjectProperty() ) {
return editConfig.isObjectPropertyUpdate();
} else {
return editConfig.isDataPropertyUpdate();
}
}
public String getVitroNsProperty() {
String vitroNsProp = vreq.getParameter("vitroNsProp");
if(vitroNsProp == null) {
vitroNsProp = "";
}
return vitroNsProp;
}
//Additional data to be returned
public HashMap<String, Object> getPageData() {
return pageData;
}
//Literals in scope and uris in scope are the values
//that currently exist for any of the fields/values
//Get literals in scope returned as string values
public Map<String, List<String>> getExistingLiteralValues() {
return EditConfigurationUtils.getExistingLiteralValues(vreq, editConfig);
}
public Map<String, List<String>> getExistingUriValues() {
return editConfig.getUrisInScope();
}
//Get editElements with html
public void populateGeneratedHtml() {
Map<String, String> generatedHtml = new HashMap<String, String>();
Map<String, FieldVTwo> fieldMap = editConfig.getFields();
//Check if any of the fields have edit elements and should be generated
Set<String> keySet = fieldMap.keySet();
for(String key: keySet) {
FieldVTwo field = fieldMap.get(key);
EditElementVTwo editElement = field.getEditElement();
String fieldName = field.getName();
if(editElement != null) {
generatedHtml.put(fieldName, EditConfigurationUtils.generateHTMLForElement(vreq, fieldName, editConfig));
}
}
//Put in pageData
pageData.put("htmlForElements", generatedHtml);
}
}
| true | true | public Map<String, String> getOfferTypesCreateNew() {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
ObjectProperty op =
wdf.getObjectPropertyDao().getObjectPropertyByURI(editConfig.getPredicateUri());
Individual sub =
wdf.getIndividualDao().getIndividualByURI(editConfig.getSubjectUri());
VClass rangeClass = EditConfigurationUtils.getRangeVClass(vreq);
List<VClass> vclasses = null;
List<VClass> subjectVClasses = sub.getVClasses();
if( subjectVClasses == null ) {
vclasses = wdf.getVClassDao().getAllVclasses();
} else if (rangeClass != null) {
List<VClass> rangeVClasses = new ArrayList<VClass>();
vclasses = new ArrayList<VClass>();
if (!rangeClass.isUnion()) {
rangeVClasses.add(rangeClass);
} else {
rangeVClasses.addAll(rangeClass.getUnionComponents());
}
for(VClass rangeVClass : rangeVClasses) {
vclasses.add(rangeVClass);
List<String> subURIs = wdf.getVClassDao().getSubClassURIs(rangeVClass.getURI());
for (String subClassURI : subURIs) {
VClass subClass = wdf.getVClassDao().getVClassByURI(subClassURI);
if (subClass != null) {
vclasses.add(subClass);
}
}
}
} else {
//this hash is used to make sure there are no duplicates in the vclasses
//a more elegant method may look at overriding equals/hashcode to enable a single hashset of VClass objects
HashSet<String> vclassesURIs = new HashSet<String>();
vclasses = new ArrayList<VClass>();
//Get the range vclasses applicable for the property and each vclass for the subject
for(VClass subjectVClass: subjectVClasses) {
List<VClass> rangeVclasses = wdf.getVClassDao().getVClassesForProperty(subjectVClass.getURI(), op.getURI());
//add range vclass to hash
if(rangeVclasses != null) {
for(VClass v: rangeVclasses) {
if(!vclassesURIs.contains(v.getURI())) {
vclassesURIs.add(v.getURI());
vclasses.add(v);
}
}
}
}
}
//if each subject vclass resulted in null being returned for range vclasses, then size of vclasses would be zero
if(vclasses.size() == 0) {
vclasses = wdf.getVClassDao().getAllVclasses();
}
HashMap<String,String> types = new HashMap<String, String>();
for( VClass vclass : vclasses ){
String name = null;
if( vclass.getPickListName() != null && vclass.getPickListName().length() > 0){
name = vclass.getPickListName();
}else if( vclass.getName() != null && vclass.getName().length() > 0){
name = vclass.getName();
}else if (vclass.getLocalNameWithPrefix() != null && vclass.getLocalNameWithPrefix().length() > 0){
name = vclass.getLocalNameWithPrefix();
}
if( name != null && name.length() > 0)
types.put(vclass.getURI(),name);
}
//Unlike input element formatting tag, including sorting logic here
return getSortedMap(types);
}
| public Map<String, String> getOfferTypesCreateNew() {
WebappDaoFactory wdf = vreq.getWebappDaoFactory();
ObjectProperty op =
wdf.getObjectPropertyDao().getObjectPropertyByURI(editConfig.getPredicateUri());
Individual sub =
wdf.getIndividualDao().getIndividualByURI(editConfig.getSubjectUri());
VClass rangeClass = EditConfigurationUtils.getRangeVClass(vreq);
List<VClass> vclasses = null;
List<VClass> subjectVClasses = sub.getVClasses();
if( subjectVClasses == null ) {
vclasses = wdf.getVClassDao().getAllVclasses();
} else if (rangeClass != null) {
List<VClass> rangeVClasses = new ArrayList<VClass>();
vclasses = new ArrayList<VClass>();
if (!rangeClass.isUnion()) {
rangeVClasses.add(rangeClass);
} else {
rangeVClasses.addAll(rangeClass.getUnionComponents());
}
for(VClass rangeVClass : rangeVClasses) {
vclasses.add(rangeVClass);
List<String> subURIs = wdf.getVClassDao().getAllSubClassURIs(rangeVClass.getURI());
for (String subClassURI : subURIs) {
VClass subClass = wdf.getVClassDao().getVClassByURI(subClassURI);
if (subClass != null) {
vclasses.add(subClass);
}
}
}
} else {
//this hash is used to make sure there are no duplicates in the vclasses
//a more elegant method may look at overriding equals/hashcode to enable a single hashset of VClass objects
HashSet<String> vclassesURIs = new HashSet<String>();
vclasses = new ArrayList<VClass>();
//Get the range vclasses applicable for the property and each vclass for the subject
for(VClass subjectVClass: subjectVClasses) {
List<VClass> rangeVclasses = wdf.getVClassDao().getVClassesForProperty(subjectVClass.getURI(), op.getURI());
//add range vclass to hash
if(rangeVclasses != null) {
for(VClass v: rangeVclasses) {
if(!vclassesURIs.contains(v.getURI())) {
vclassesURIs.add(v.getURI());
vclasses.add(v);
}
}
}
}
}
//if each subject vclass resulted in null being returned for range vclasses, then size of vclasses would be zero
if(vclasses.size() == 0) {
vclasses = wdf.getVClassDao().getAllVclasses();
}
HashMap<String,String> types = new HashMap<String, String>();
for( VClass vclass : vclasses ){
String name = null;
if( vclass.getPickListName() != null && vclass.getPickListName().length() > 0){
name = vclass.getPickListName();
}else if( vclass.getName() != null && vclass.getName().length() > 0){
name = vclass.getName();
}else if (vclass.getLocalNameWithPrefix() != null && vclass.getLocalNameWithPrefix().length() > 0){
name = vclass.getLocalNameWithPrefix();
}
if( name != null && name.length() > 0)
types.put(vclass.getURI(),name);
}
//Unlike input element formatting tag, including sorting logic here
return getSortedMap(types);
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java
index f72f4fee7..e80ca69d7 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/Submissions.java
@@ -1,430 +1,431 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.xmlui.aspect.submission;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.cocoon.AbstractDSpaceTransformer;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Cell;
import org.dspace.app.xmlui.wing.element.CheckBox;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.PageMeta;
import org.dspace.app.xmlui.wing.element.Para;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.SupervisedItem;
import org.dspace.content.WorkspaceItem;
import org.dspace.core.Constants;
import org.dspace.eperson.EPerson;
import org.xml.sax.SAXException;
/**
* @author Scott Phillips
*/
public class Submissions extends AbstractDSpaceTransformer
{
/** General Language Strings */
protected static final Message T_title =
message("xmlui.Submission.Submissions.title");
protected static final Message T_dspace_home =
message("xmlui.general.dspace_home");
protected static final Message T_trail =
message("xmlui.Submission.Submissions.trail");
protected static final Message T_head =
message("xmlui.Submission.Submissions.head");
protected static final Message T_untitled =
message("xmlui.Submission.Submissions.untitled");
protected static final Message T_email =
message("xmlui.Submission.Submissions.email");
// used by the unfinished submissions section
protected static final Message T_s_head1 =
message("xmlui.Submission.Submissions.submit_head1");
protected static final Message T_s_info1a =
message("xmlui.Submission.Submissions.submit_info1a");
protected static final Message T_s_info1b =
message("xmlui.Submission.Submissions.submit_info1b");
protected static final Message T_s_info1c =
message("xmlui.Submission.Submissions.submit_info1c");
protected static final Message T_s_head2 =
message("xmlui.Submission.Submissions.submit_head2");
protected static final Message T_s_info2a =
message("xmlui.Submission.Submissions.submit_info2a");
protected static final Message T_s_info2b =
message("xmlui.Submission.Submissions.submit_info2b");
protected static final Message T_s_info2c =
message("xmlui.Submission.Submissions.submit_info2c");
protected static final Message T_s_column1 =
message("xmlui.Submission.Submissions.submit_column1");
protected static final Message T_s_column2 =
message("xmlui.Submission.Submissions.submit_column2");
protected static final Message T_s_column3 =
message("xmlui.Submission.Submissions.submit_column3");
protected static final Message T_s_column4 =
message("xmlui.Submission.Submissions.submit_column4");
protected static final Message T_s_head3 =
message("xmlui.Submission.Submissions.submit_head3");
protected static final Message T_s_info3 =
message("xmlui.Submission.Submissions.submit_info3");
protected static final Message T_s_head4 =
message("xmlui.Submission.Submissions.submit_head4");
protected static final Message T_s_submit_remove =
message("xmlui.Submission.Submissions.submit_submit_remove");
// Used in the completed submissions section
protected static final Message T_c_head =
message("xmlui.Submission.Submissions.completed.head");
protected static final Message T_c_info =
message("xmlui.Submission.Submissions.completed.info");
protected static final Message T_c_column1 =
message("xmlui.Submission.Submissions.completed.column1");
protected static final Message T_c_column2 =
message("xmlui.Submission.Submissions.completed.column2");
protected static final Message T_c_column3 =
message("xmlui.Submission.Submissions.completed.column3");
protected static final Message T_c_limit =
message("xmlui.Submission.Submissions.completed.limit");
protected static final Message T_c_displayall =
message("xmlui.Submission.Submissions.completed.displayall");
@Override
public void addPageMeta(PageMeta pageMeta) throws SAXException,
WingException, UIException, SQLException, IOException,
AuthorizeException
{
pageMeta.addMetadata("title").addContent(T_title);
pageMeta.addTrailLink(contextPath + "/",T_dspace_home);
pageMeta.addTrailLink(null,T_trail);
}
@Override
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
Request request = ObjectModelHelper.getRequest(objectModel);
boolean displayAll = false;
//This param decides whether we display all of the user's previous
// submissions, or just a portion of them
if (request.getParameter("all") != null)
{
displayAll=true;
}
Division div = body.addInteractiveDivision("submissions", contextPath+"/submissions", Division.METHOD_POST,"primary");
div.setHead(T_head);
// this.addWorkflowTasksDiv(div);
this.addUnfinishedSubmissions(div);
// this.addSubmissionsInWorkflowDiv(div);
this.addPreviousSubmissions(div, displayAll);
}
/**
* If the user has any workflow tasks, either assigned to them or in an
* available pool of tasks, then build two tables listing each of these queues.
*
* If the user doesn't have any workflows then don't do anything.
*
* @param division The division to add the two queues too.
*/
private void addWorkflowTasksDiv(Division division) throws SQLException, WingException, AuthorizeException, IOException {
division.addDivision("workflow-tasks");
}
/**
* There are two options: the user has some unfinished submissions
* or the user does not.
*
* If the user does not, then we just display a simple paragraph
* explaining that the user may submit new items to dspace.
*
* If the user does have unfinished submissions then a table is
* presented listing all the unfinished submissions that this user has.
*
*/
private void addUnfinishedSubmissions(Division division) throws SQLException, WingException
{
// User's WorkflowItems
WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser());
SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser());
if (unfinishedItems.length <= 0 && supervisedItems.length <= 0)
{
Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD);
if (collections.length > 0)
{
Division start = division.addDivision("start-submision");
start.setHead(T_s_head1);
Para p = start.addPara();
p.addContent(T_s_info1a);
p.addXref(contextPath+"/submit",T_s_info1b);
- p.addContent(T_s_info1c);
+ Para secondP = start.addPara();
+ secondP.addContent(T_s_info1c);
return;
}
}
Division unfinished = division.addDivision("unfinished-submisions");
unfinished.setHead(T_s_head2);
Para p = unfinished.addPara();
p.addContent(T_s_info2a);
p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b);
p.addContent(T_s_info2c);
// Calculate the number of rows.
// Each list pluss the top header and bottom row for the button.
int rows = unfinishedItems.length + supervisedItems.length + 2;
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
rows++; // Authoring heading row
}
if (supervisedItems.length > 0)
{
rows++; // Supervising heading row
}
Table table = unfinished.addTable("unfinished-submissions",rows,5);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_s_column1);
header.addCellContent(T_s_column2);
header.addCellContent(T_s_column3);
header.addCellContent(T_s_column4);
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3);
}
if (unfinishedItems.length > 0)
{
for (WorkspaceItem workspaceItem : unfinishedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox remove = row.addCell().addCheckBox("workspaceID");
remove.setLabel("remove");
remove.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
displayTitle = displayTitle.substring(0, 50) + " ...";
row.addCell().addXref(url,displayTitle);
}
else
row.addCell().addXref(url,T_untitled);
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
}
else
{
header = table.addRow();
header.addCell(0,5).addHighlight("italic").addContent(T_s_info3);
}
if (supervisedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4);
}
for (WorkspaceItem workspaceItem : supervisedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox selected = row.addCell().addCheckBox("workspaceID");
selected.setLabel("select");
selected.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(url,displayTitle);
}
else
{
row.addCell().addXref(url, T_untitled);
}
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
header = table.addRow();
Cell lastCell = header.addCell(0,5);
if (unfinishedItems.length > 0 || supervisedItems.length > 0)
{
lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove);
}
}
/**
* This section lists all the submissions that this user has submitted which are currently under review.
*
* If the user has none, this nothing is displayed.
*/
private void addSubmissionsInWorkflowDiv(Division division)
throws SQLException, WingException, AuthorizeException, IOException
{
division.addDivision("submissions-inprogress");
}
/**
* Show the user's completed submissions.
*
* If the user has no completed submissions, display nothing.
* If 'displayAll' is true, then display all user's archived submissions.
* Otherwise, default to only displaying 50 archived submissions.
*
* @param division div to put archived submissions in
* @param displayAll whether to display all or just a limited number.
*/
private void addPreviousSubmissions(Division division, boolean displayAll)
throws SQLException,WingException
{
// Turn the iterator into a list (to get size info, in order to put in a table)
List subList = new LinkedList();
ItemIterator subs = Item.findBySubmitter(context, context.getCurrentUser());
//NOTE: notice we are adding each item to this list in *reverse* order...
// this is a very basic attempt at making more recent submissions float
// up to the top of the list (findBySubmitter() doesn't guarrantee
// chronological order, but tends to return older items near top of the list)
try
{
while (subs.hasNext())
{
subList.add(0, subs.next());
}
}
finally
{
if (subs != null)
subs.close();
}
// No tasks, so don't show the table.
if (!(subList.size() > 0))
return;
Division completedSubmissions = division.addDivision("completed-submissions");
completedSubmissions.setHead(T_c_head);
completedSubmissions.addPara(T_c_info);
// Create table, headers
Table table = completedSubmissions.addTable("completed-submissions",subList.size() + 2,3);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_c_column1); // ISSUE DATE
header.addCellContent(T_c_column2); // ITEM TITLE (LINKED)
header.addCellContent(T_c_column3); // COLLECTION NAME (LINKED)
//Limit to showing just 50 archived submissions, unless overridden
//(This is a saftey measure for Admins who may have submitted
// thousands of items under their account via bulk ingest tools, etc.)
int limit = 50;
int count = 0;
// Populate table
Iterator i = subList.iterator();
while(i.hasNext())
{
count++;
//exit loop if we've gone over our limit of submissions to display
if(count>limit && !displayAll)
break;
Item published = (Item) i.next();
String collUrl = contextPath+"/handle/"+published.getOwningCollection().getHandle();
String itemUrl = contextPath+"/handle/"+published.getHandle();
DCValue[] titles = published.getMetadata("dc", "title", null, Item.ANY);
String collectionName = published.getOwningCollection().getMetadata("name");
DCValue[] ingestDate = published.getMetadata("dc", "date", "accessioned", Item.ANY);
Row row = table.addRow();
// Item accession date
if (ingestDate != null && ingestDate.length > 0 &&
ingestDate[0].value != null)
{
String displayDate = ingestDate[0].value.substring(0,10);
Cell cellDate = row.addCell();
cellDate.addContent(displayDate);
}
else //if no accession date add an empty cell (shouldn't happen, but just in case)
row.addCell().addContent("");
// The item description
if (titles != null && titles.length > 0 &&
titles[0].value != null)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
displayTitle = displayTitle.substring(0,50)+ " ...";
row.addCell().addXref(itemUrl,displayTitle);
}
else
row.addCell().addXref(itemUrl,T_untitled);
// Owning Collection
row.addCell().addXref(collUrl,collectionName);
}//end while
//Display limit text & link to allow user to override this default limit
if(!displayAll && count>limit)
{
Para limitedList = completedSubmissions.addPara();
limitedList.addContent(T_c_limit);
limitedList.addXref(contextPath + "/submissions?all", T_c_displayall);
}
}
}
| true | true | private void addUnfinishedSubmissions(Division division) throws SQLException, WingException
{
// User's WorkflowItems
WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser());
SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser());
if (unfinishedItems.length <= 0 && supervisedItems.length <= 0)
{
Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD);
if (collections.length > 0)
{
Division start = division.addDivision("start-submision");
start.setHead(T_s_head1);
Para p = start.addPara();
p.addContent(T_s_info1a);
p.addXref(contextPath+"/submit",T_s_info1b);
p.addContent(T_s_info1c);
return;
}
}
Division unfinished = division.addDivision("unfinished-submisions");
unfinished.setHead(T_s_head2);
Para p = unfinished.addPara();
p.addContent(T_s_info2a);
p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b);
p.addContent(T_s_info2c);
// Calculate the number of rows.
// Each list pluss the top header and bottom row for the button.
int rows = unfinishedItems.length + supervisedItems.length + 2;
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
rows++; // Authoring heading row
}
if (supervisedItems.length > 0)
{
rows++; // Supervising heading row
}
Table table = unfinished.addTable("unfinished-submissions",rows,5);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_s_column1);
header.addCellContent(T_s_column2);
header.addCellContent(T_s_column3);
header.addCellContent(T_s_column4);
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3);
}
if (unfinishedItems.length > 0)
{
for (WorkspaceItem workspaceItem : unfinishedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox remove = row.addCell().addCheckBox("workspaceID");
remove.setLabel("remove");
remove.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
displayTitle = displayTitle.substring(0, 50) + " ...";
row.addCell().addXref(url,displayTitle);
}
else
row.addCell().addXref(url,T_untitled);
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
}
else
{
header = table.addRow();
header.addCell(0,5).addHighlight("italic").addContent(T_s_info3);
}
if (supervisedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4);
}
for (WorkspaceItem workspaceItem : supervisedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox selected = row.addCell().addCheckBox("workspaceID");
selected.setLabel("select");
selected.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(url,displayTitle);
}
else
{
row.addCell().addXref(url, T_untitled);
}
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
header = table.addRow();
Cell lastCell = header.addCell(0,5);
if (unfinishedItems.length > 0 || supervisedItems.length > 0)
{
lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove);
}
}
| private void addUnfinishedSubmissions(Division division) throws SQLException, WingException
{
// User's WorkflowItems
WorkspaceItem[] unfinishedItems = WorkspaceItem.findByEPerson(context,context.getCurrentUser());
SupervisedItem[] supervisedItems = SupervisedItem.findbyEPerson(context, context.getCurrentUser());
if (unfinishedItems.length <= 0 && supervisedItems.length <= 0)
{
Collection[] collections = Collection.findAuthorized(context, null, Constants.ADD);
if (collections.length > 0)
{
Division start = division.addDivision("start-submision");
start.setHead(T_s_head1);
Para p = start.addPara();
p.addContent(T_s_info1a);
p.addXref(contextPath+"/submit",T_s_info1b);
Para secondP = start.addPara();
secondP.addContent(T_s_info1c);
return;
}
}
Division unfinished = division.addDivision("unfinished-submisions");
unfinished.setHead(T_s_head2);
Para p = unfinished.addPara();
p.addContent(T_s_info2a);
p.addHighlight("bold").addXref(contextPath+"/submit",T_s_info2b);
p.addContent(T_s_info2c);
// Calculate the number of rows.
// Each list pluss the top header and bottom row for the button.
int rows = unfinishedItems.length + supervisedItems.length + 2;
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
rows++; // Authoring heading row
}
if (supervisedItems.length > 0)
{
rows++; // Supervising heading row
}
Table table = unfinished.addTable("unfinished-submissions",rows,5);
Row header = table.addRow(Row.ROLE_HEADER);
header.addCellContent(T_s_column1);
header.addCellContent(T_s_column2);
header.addCellContent(T_s_column3);
header.addCellContent(T_s_column4);
if (supervisedItems.length > 0 && unfinishedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head3);
}
if (unfinishedItems.length > 0)
{
for (WorkspaceItem workspaceItem : unfinishedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox remove = row.addCell().addCheckBox("workspaceID");
remove.setLabel("remove");
remove.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
displayTitle = displayTitle.substring(0, 50) + " ...";
row.addCell().addXref(url,displayTitle);
}
else
row.addCell().addXref(url,T_untitled);
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
}
else
{
header = table.addRow();
header.addCell(0,5).addHighlight("italic").addContent(T_s_info3);
}
if (supervisedItems.length > 0)
{
header = table.addRow();
header.addCell(null,Cell.ROLE_HEADER,0,5,null).addContent(T_s_head4);
}
for (WorkspaceItem workspaceItem : supervisedItems)
{
DCValue[] titles = workspaceItem.getItem().getDC("title", null, Item.ANY);
EPerson submitterEPerson = workspaceItem.getItem().getSubmitter();
int workspaceItemID = workspaceItem.getID();
String url = contextPath+"/submit?workspaceID="+workspaceItemID;
String submitterName = submitterEPerson.getFullName();
String submitterEmail = submitterEPerson.getEmail();
String collectionName = workspaceItem.getCollection().getMetadata("name");
Row row = table.addRow(Row.ROLE_DATA);
CheckBox selected = row.addCell().addCheckBox("workspaceID");
selected.setLabel("select");
selected.addOption(workspaceItemID);
if (titles.length > 0)
{
String displayTitle = titles[0].value;
if (displayTitle.length() > 50)
{
displayTitle = displayTitle.substring(0, 50) + " ...";
}
row.addCell().addXref(url,displayTitle);
}
else
{
row.addCell().addXref(url, T_untitled);
}
row.addCell().addXref(url,collectionName);
Cell cell = row.addCell();
cell.addContent(T_email);
cell.addXref("mailto:"+submitterEmail,submitterName);
}
header = table.addRow();
Cell lastCell = header.addCell(0,5);
if (unfinishedItems.length > 0 || supervisedItems.length > 0)
{
lastCell.addButton("submit_submissions_remove").setValue(T_s_submit_remove);
}
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facets/geodistance/InternalGeoDistanceFacet.java b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facets/geodistance/InternalGeoDistanceFacet.java
index 3df9ba99c05..34d56652110 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/search/facets/geodistance/InternalGeoDistanceFacet.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/search/facets/geodistance/InternalGeoDistanceFacet.java
@@ -1,185 +1,185 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.search.facets.geodistance;
import org.elasticsearch.common.collect.ImmutableList;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.builder.XContentBuilder;
import org.elasticsearch.search.facets.Facet;
import org.elasticsearch.search.facets.internal.InternalFacet;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
/**
* @author kimchy (shay.banon)
*/
public class InternalGeoDistanceFacet implements GeoDistanceFacet, InternalFacet {
private String name;
private String fieldName;
private String valueFieldName;
private DistanceUnit unit;
private Entry[] entries;
InternalGeoDistanceFacet() {
}
public InternalGeoDistanceFacet(String name, String fieldName, String valueFieldName, DistanceUnit unit, Entry[] entries) {
this.name = name;
this.fieldName = fieldName;
this.valueFieldName = valueFieldName;
this.unit = unit;
this.entries = entries;
}
@Override public String name() {
return this.name;
}
@Override public String getName() {
return name();
}
@Override public Type type() {
return Type.GEO_DISTANCE;
}
@Override public Type getType() {
return type();
}
@Override public String fieldName() {
return this.fieldName;
}
@Override public String getFieldName() {
return fieldName();
}
@Override public String valueFieldName() {
return this.valueFieldName;
}
@Override public String getValueFieldName() {
return valueFieldName();
}
@Override public DistanceUnit unit() {
return this.unit;
}
@Override public DistanceUnit getUnit() {
return unit();
}
@Override public List<Entry> entries() {
return ImmutableList.copyOf(entries);
}
@Override public List<Entry> getEntries() {
return entries();
}
@Override public Iterator<Entry> iterator() {
return entries().iterator();
}
@Override public Facet aggregate(Iterable<Facet> facets) {
InternalGeoDistanceFacet agg = null;
for (Facet facet : facets) {
if (!facet.name().equals(name)) {
continue;
}
InternalGeoDistanceFacet geoDistanceFacet = (InternalGeoDistanceFacet) facet;
if (agg == null) {
agg = geoDistanceFacet;
} else {
for (int i = 0; i < geoDistanceFacet.entries.length; i++) {
agg.entries[i].count += geoDistanceFacet.entries[i].count;
agg.entries[i].total += geoDistanceFacet.entries[i].total;
}
}
}
return agg;
}
public static InternalGeoDistanceFacet readGeoDistanceFacet(StreamInput in) throws IOException {
InternalGeoDistanceFacet facet = new InternalGeoDistanceFacet();
facet.readFrom(in);
return facet;
}
@Override public void readFrom(StreamInput in) throws IOException {
name = in.readUTF();
fieldName = in.readUTF();
valueFieldName = in.readUTF();
unit = DistanceUnit.readDistanceUnit(in);
entries = new Entry[in.readVInt()];
for (int i = 0; i < entries.length; i++) {
entries[i] = new Entry(in.readDouble(), in.readDouble(), in.readVLong(), in.readDouble());
}
}
@Override public void writeTo(StreamOutput out) throws IOException {
out.writeUTF(name);
out.writeUTF(fieldName);
out.writeUTF(valueFieldName);
DistanceUnit.writeDistanceUnit(out, unit);
out.writeVInt(entries.length);
for (Entry entry : entries) {
out.writeDouble(entry.from);
out.writeDouble(entry.to);
out.writeVLong(entry.count);
out.writeDouble(entry.total);
}
}
@Override public void toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
- builder.field("_type", "histogram");
+ builder.field("_type", "geo_distance");
builder.field("_field", fieldName);
builder.field("_value_field", valueFieldName);
builder.field("_unit", unit);
builder.startArray("ranges");
for (Entry entry : entries) {
builder.startObject();
if (!Double.isInfinite(entry.from)) {
builder.field("from", entry.from);
}
if (!Double.isInfinite(entry.to)) {
builder.field("to", entry.to);
}
builder.field("count", entry.count());
builder.field("total", entry.total());
builder.field("mean", entry.mean());
builder.endObject();
}
builder.endArray();
builder.endObject();
}
}
| true | true | @Override public void toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.field("_type", "histogram");
builder.field("_field", fieldName);
builder.field("_value_field", valueFieldName);
builder.field("_unit", unit);
builder.startArray("ranges");
for (Entry entry : entries) {
builder.startObject();
if (!Double.isInfinite(entry.from)) {
builder.field("from", entry.from);
}
if (!Double.isInfinite(entry.to)) {
builder.field("to", entry.to);
}
builder.field("count", entry.count());
builder.field("total", entry.total());
builder.field("mean", entry.mean());
builder.endObject();
}
builder.endArray();
builder.endObject();
}
| @Override public void toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(name);
builder.field("_type", "geo_distance");
builder.field("_field", fieldName);
builder.field("_value_field", valueFieldName);
builder.field("_unit", unit);
builder.startArray("ranges");
for (Entry entry : entries) {
builder.startObject();
if (!Double.isInfinite(entry.from)) {
builder.field("from", entry.from);
}
if (!Double.isInfinite(entry.to)) {
builder.field("to", entry.to);
}
builder.field("count", entry.count());
builder.field("total", entry.total());
builder.field("mean", entry.mean());
builder.endObject();
}
builder.endArray();
builder.endObject();
}
|
diff --git a/src/org/pit/fetegeo/importer/processors/LocationProcessor.java b/src/org/pit/fetegeo/importer/processors/LocationProcessor.java
index 08e72ec..2e42b18 100644
--- a/src/org/pit/fetegeo/importer/processors/LocationProcessor.java
+++ b/src/org/pit/fetegeo/importer/processors/LocationProcessor.java
@@ -1,230 +1,229 @@
package org.pit.fetegeo.importer.processors;
import org.openstreetmap.osmosis.core.domain.v0_6.*;
import org.openstreetmap.osmosis.core.lifecycle.CompletableContainer;
import org.openstreetmap.osmosis.core.store.*;
import org.pit.fetegeo.importer.objects.Constants;
import org.postgis.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Author: Pit Apps
* Date: 10/26/12
* Time: 3:43 PM
*/
public class LocationProcessor {
private static Geometry currentLocation;
private static CompletableContainer storeContainer;
private static RandomAccessObjectStore<CleverPoint> nodeOS;
private static RandomAccessObjectStoreReader<CleverPoint> nodeReader;
private static IndexStore<Long, LongLongIndexElement> nodeIDX;
private static IndexStoreReader<Long, LongLongIndexElement> nodeIDXReader;
private static RandomAccessObjectStore<Way> wayOS;
private static RandomAccessObjectStoreReader<Way> wayReader;
private static IndexStore<Long, LongLongIndexElement> wayIDX;
private static IndexStoreReader<Long, LongLongIndexElement> wayIDXReader;
private static Map<Long, Geometry> relationMap = new HashMap<Long, Geometry>();
public LocationProcessor() {
storeContainer = new CompletableContainer();
// Create temp files for locations
try {
File nodeOSFile = File.createTempFile("nodeOS-", ".tmp", Constants.OUT_PATH);
File nodeIDXFile = File.createTempFile("nodeIDX-", ".tmp", Constants.OUT_PATH);
nodeOSFile.deleteOnExit();
nodeIDXFile.deleteOnExit();
nodeOS = storeContainer.add(new RandomAccessObjectStore<CleverPoint>(new SingleClassObjectSerializationFactory(CleverPoint.class), nodeOSFile));
nodeIDX = storeContainer.add(new IndexStore<Long, LongLongIndexElement>(LongLongIndexElement.class, new ComparableComparator<Long>(), nodeIDXFile));
File wayOSFile = File.createTempFile("wayOS-", ".tmp", Constants.OUT_PATH);
File wayIDXFile = File.createTempFile("wayIDX-", ".tmp", Constants.OUT_PATH);
wayOSFile.deleteOnExit();
wayIDXFile.deleteOnExit();
wayOS = storeContainer.add(new RandomAccessObjectStore<Way>(new SingleClassObjectSerializationFactory(Way.class), wayOSFile));
wayIDX = storeContainer.add(new IndexStore<Long, LongLongIndexElement>(LongLongIndexElement.class, new ComparableComparator<Long>(), wayIDXFile));
} catch (IOException ioe) {
System.out.println("Could not create cache file " + ioe.getLocalizedMessage());
}
}
/*
Processes Nodes and caches Ways and Relation to file if they're needed for location later on.
Sets currentLocation to the location found for the Entity
*/
public void process(Entity entity) {
// Find out what we're dealing with
switch (entity.getType()) {
case Node:
currentLocation = process((Node) entity);
break;
case Way:
currentLocation = process((Way) entity);
wayIDX.write(new LongLongIndexElement(entity.getId(), wayOS.add((Way) entity)));
break;
case Relation:
currentLocation = process((Relation) entity);
break;
default:
break;
}
}
/*
Returns Geometry of the last processed location.
*/
public static Geometry findLocation() {
return currentLocation;
}
private Geometry process(Node node) {
CleverPoint cp = new CleverPoint(node.getLatitude(), node.getLongitude());
nodeIDX.write(new LongLongIndexElement(node.getId(), nodeOS.add(cp)));
return cp;
}
private static Geometry process(Way way) {
if (nodeReader == null) {
nodeOS.complete();
nodeReader = nodeOS.createReader();
}
if (nodeIDXReader == null) {
nodeIDX.complete();
nodeIDXReader = nodeIDX.createReader();
}
List<WayNode> wayNodes = way.getWayNodes();
Point[] points = new Point[wayNodes.size()];
for (int i = 0; i < points.length; i++) {
try {
points[i] = nodeReader.get(nodeIDXReader.get(wayNodes.get(i).getNodeId()).getValue());
} catch (NoSuchIndexElementException nsiee) {
// continue (maybe we're importing an incomplete file; we'll do our best to display as much of the way as possible)
}
}
Geometry result;
// If points make a circle, we have a polygon. otherwise we have a line
if (points.length >= 3 && points[0].equals(points[points.length - 1])) {
result = new Polygon(new LinearRing[]{new LinearRing(points)});
} else {
result = new LineString(points);
}
result.setSrid(4326);
return result;
}
private static Geometry process(Relation relation) {
if (wayReader == null) {
wayOS.complete();
wayReader = wayOS.createReader();
}
if (wayIDXReader == null) {
wayIDX.complete();
wayIDXReader = wayIDX.createReader();
}
List<Geometry> coordinateList = fetchRelationCoors(relation);
// If we could not find all the coordinates, we return null!
if (coordinateList == null) {
return null;
}
GeometryCollection result = new GeometryCollection(coordinateList.toArray(new Geometry[coordinateList.size()]));
result.setSrid(4326);
relationMap.put(relation.getId(), result);
return result;
}
private static List<Geometry> fetchRelationCoors(Relation relation) {
List<Geometry> coordinateList = new ArrayList<Geometry>();
- int j = 0;
for (RelationMember relationMember : relation.getMembers()) {
- // only care about outer roles (maybe inner too?)
- if (!relationMember.getMemberRole().equalsIgnoreCase("outer")) {
+ // only care about outer roles. Some ways are not tagged...
+ if (!relationMember.getMemberRole().equalsIgnoreCase("outer") && !relationMember.getMemberRole().isEmpty()) {
continue;
}
switch (relationMember.getMemberType()) {
case Node:
// we don't care about Nodes as these are not used for roads or bounds (a part from designating the capital and other useless stuff)
break;
case Way:
try {
Way way = wayReader.get(wayIDXReader.get(relationMember.getMemberId()).getValue());
if (way != null) {
coordinateList.add(process(way));
}
} catch (NoSuchIndexElementException nsiee) {
return null; // if we can't find a way, then the relation might return a faulty geometry
}
break;
case Relation:
Geometry otherRelation = relationMap.get(relationMember.getMemberId());
if (otherRelation != null) {
Geometry geometry;
coordinateList.add(otherRelation);
// We need to differentiate between the two different types of relations
if (otherRelation instanceof MultiPolygon) {
MultiPolygon multiPolygon = (MultiPolygon) otherRelation;
for (int i = 0; i < multiPolygon.numPolygons(); i++) {
if ((geometry = multiPolygon.getPolygon(i)) != null) {
coordinateList.add(geometry);
}
}
} else if (otherRelation instanceof MultiLineString) {
MultiLineString multiLineString = (MultiLineString) otherRelation;
for (int i = 0; i < multiLineString.numLines(); i++) {
if ((geometry = multiLineString.getLine(i)) != null) {
coordinateList.add(geometry);
}
}
}
} else {
return null;
}
break;
default:
break;
}
}
return coordinateList;
}
private List<Geometry> cleanList(List<Geometry> list, int type) {
List<Geometry> cleanedList = new ArrayList<Geometry>();
for (Geometry g : list) {
if (g.getType() == type) {
cleanedList.add(g);
}
}
return cleanedList;
}
public void completeAndRelease() {
storeContainer.complete();
storeContainer.release();
}
}
| false | true | private static List<Geometry> fetchRelationCoors(Relation relation) {
List<Geometry> coordinateList = new ArrayList<Geometry>();
int j = 0;
for (RelationMember relationMember : relation.getMembers()) {
// only care about outer roles (maybe inner too?)
if (!relationMember.getMemberRole().equalsIgnoreCase("outer")) {
continue;
}
switch (relationMember.getMemberType()) {
case Node:
// we don't care about Nodes as these are not used for roads or bounds (a part from designating the capital and other useless stuff)
break;
case Way:
try {
Way way = wayReader.get(wayIDXReader.get(relationMember.getMemberId()).getValue());
if (way != null) {
coordinateList.add(process(way));
}
} catch (NoSuchIndexElementException nsiee) {
return null; // if we can't find a way, then the relation might return a faulty geometry
}
break;
case Relation:
Geometry otherRelation = relationMap.get(relationMember.getMemberId());
if (otherRelation != null) {
Geometry geometry;
coordinateList.add(otherRelation);
// We need to differentiate between the two different types of relations
if (otherRelation instanceof MultiPolygon) {
MultiPolygon multiPolygon = (MultiPolygon) otherRelation;
for (int i = 0; i < multiPolygon.numPolygons(); i++) {
if ((geometry = multiPolygon.getPolygon(i)) != null) {
coordinateList.add(geometry);
}
}
} else if (otherRelation instanceof MultiLineString) {
MultiLineString multiLineString = (MultiLineString) otherRelation;
for (int i = 0; i < multiLineString.numLines(); i++) {
if ((geometry = multiLineString.getLine(i)) != null) {
coordinateList.add(geometry);
}
}
}
} else {
return null;
}
break;
default:
break;
}
}
return coordinateList;
}
| private static List<Geometry> fetchRelationCoors(Relation relation) {
List<Geometry> coordinateList = new ArrayList<Geometry>();
for (RelationMember relationMember : relation.getMembers()) {
// only care about outer roles. Some ways are not tagged...
if (!relationMember.getMemberRole().equalsIgnoreCase("outer") && !relationMember.getMemberRole().isEmpty()) {
continue;
}
switch (relationMember.getMemberType()) {
case Node:
// we don't care about Nodes as these are not used for roads or bounds (a part from designating the capital and other useless stuff)
break;
case Way:
try {
Way way = wayReader.get(wayIDXReader.get(relationMember.getMemberId()).getValue());
if (way != null) {
coordinateList.add(process(way));
}
} catch (NoSuchIndexElementException nsiee) {
return null; // if we can't find a way, then the relation might return a faulty geometry
}
break;
case Relation:
Geometry otherRelation = relationMap.get(relationMember.getMemberId());
if (otherRelation != null) {
Geometry geometry;
coordinateList.add(otherRelation);
// We need to differentiate between the two different types of relations
if (otherRelation instanceof MultiPolygon) {
MultiPolygon multiPolygon = (MultiPolygon) otherRelation;
for (int i = 0; i < multiPolygon.numPolygons(); i++) {
if ((geometry = multiPolygon.getPolygon(i)) != null) {
coordinateList.add(geometry);
}
}
} else if (otherRelation instanceof MultiLineString) {
MultiLineString multiLineString = (MultiLineString) otherRelation;
for (int i = 0; i < multiLineString.numLines(); i++) {
if ((geometry = multiLineString.getLine(i)) != null) {
coordinateList.add(geometry);
}
}
}
} else {
return null;
}
break;
default:
break;
}
}
return coordinateList;
}
|
diff --git a/src/com/martinbrook/tesseractuhc/util/MatchUtils.java b/src/com/martinbrook/tesseractuhc/util/MatchUtils.java
index dbe699b..1f1fbe5 100644
--- a/src/com/martinbrook/tesseractuhc/util/MatchUtils.java
+++ b/src/com/martinbrook/tesseractuhc/util/MatchUtils.java
@@ -1,176 +1,176 @@
package com.martinbrook.tesseractuhc.util;
import java.util.ArrayList;
import java.util.Calendar;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import com.martinbrook.tesseractuhc.TesseractUHC;
import com.wimbli.WorldBorder.BorderData;
import com.wimbli.WorldBorder.WorldBorder;
public class MatchUtils {
private MatchUtils() { }
public static String formatDuration(Calendar t1, Calendar t2, boolean precise) {
// Get duration in seconds
int d = (int) (t2.getTimeInMillis() - t1.getTimeInMillis()) / 1000;
if (precise) {
int seconds = d % 60;
d = d / 60;
int minutes = d % 60;
int hours = d / 60;
// The string
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
} else {
int minutes = d / 60;
return minutes + " minute" + (minutes != 1 ? "s" : "");
}
}
/**
* Get a BorderData from the WorldBorder plugin
*
* @param w The world to get borders for
* @return The WorldBorder BorderData object
*/
private static BorderData getWorldBorder(World w) {
Plugin plugin = TesseractUHC.getInstance().getServer().getPluginManager().getPlugin("WorldBorder");
// Check if the plugin is loaded
if (plugin == null || !(plugin instanceof WorldBorder))
return null;
WorldBorder wb = (WorldBorder) plugin;
return wb.GetWorldBorder(w.getName());
}
/**
* Change the WorldBorder radius for a world
*
* @param w The world to be changed
* @param radius The new radius
* @return Whether the operation succeeded
*/
public static boolean setWorldRadius(World w, int radius) {
BorderData border = getWorldBorder(w);
if (border != null) {
border.setRadius(radius);
return true;
}
return false;
}
/**
* Attempt to parse a calcstarts command and return a list of start points
*
* @param args The arguments which were passed to the command
* @return List of start locations, or null if failed
*/
public static ArrayList<Location> calculateStarts(String[] args) {
if (args.length < 1) return null;
String method = args[0];
if ("radial".equalsIgnoreCase(method)) {
if (args.length != 3) return null;
int count;
int radius;
try {
count = Integer.parseInt(args[1]);
radius = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
return null;
}
return calculateRadialStarts(count, radius);
}
return null;
}
/**
* Generate a list of radial start points
*
* @param count Number of starts to generate
* @param radius Radius of circle
* @return List of starts
*/
private static ArrayList<Location> calculateRadialStarts(int count, int radius) {
ArrayList<Location> locations = new ArrayList<Location>();
double arc = (2*Math.PI) / count;
World w = TesseractUHC.getInstance().getMatch().getStartingWorld();
for(int i = 0; i < count; i++) {
int x = (int) (radius * Math.cos(i*arc));
int z = (int) (radius * Math.sin(i*arc));
int y = w.getHighestBlockYAt(x, z);
locations.add(new Location(w,x,y,z));
}
return locations;
}
/**
* Convert a string to a boolean.
*
* true, on, yes, y, 1 => True
* false, off, no, n, 0 => False
*
* @param s The string to check
* @return Boolean value, or null if not parsable
*/
public static Boolean stringToBoolean(String s) {
if ("true".equalsIgnoreCase(s) || "on".equalsIgnoreCase(s) || "yes".equalsIgnoreCase(s) || "y".equalsIgnoreCase(s) || "1".equals(s))
return true;
if ("false".equalsIgnoreCase(s) || "off".equalsIgnoreCase(s) || "no".equalsIgnoreCase(s) || "n".equalsIgnoreCase(s) || "0".equals(s))
return false;
return null;
}
/**
* Format a string for display on a sign
*
* @param s The string to be formatted
* @return An array with 4 elements, containing the 4 lines to go on the sign
*/
public static String[] signWrite(String s) {
// Create array to hold the lines, and initialise with empty strings
String[] lines = new String[4];
int currentLine = 0;
for (int i = 0; i < 4; i++) lines[i] = "";
// Split the message into strings on whitespace
String[] words = s.split("\\s");
// Loop through words, adding them to lines as they fit
int currentWord = 0;
- while(currentLine < 4 && currentWord <= words.length) {
+ while(currentLine < 4 && currentWord < words.length) {
if (lines[currentLine].length() + words[currentWord].length() <= 14)
lines[currentLine] += " " + words[currentWord++];
else
currentLine++;
}
// If we have only used one or two lines, move everything down by one.
if (currentLine < 2) {
lines[2]=lines[1];
lines[1]=lines[0];
lines[0]="";
}
return lines;
}
}
| true | true | public static String[] signWrite(String s) {
// Create array to hold the lines, and initialise with empty strings
String[] lines = new String[4];
int currentLine = 0;
for (int i = 0; i < 4; i++) lines[i] = "";
// Split the message into strings on whitespace
String[] words = s.split("\\s");
// Loop through words, adding them to lines as they fit
int currentWord = 0;
while(currentLine < 4 && currentWord <= words.length) {
if (lines[currentLine].length() + words[currentWord].length() <= 14)
lines[currentLine] += " " + words[currentWord++];
else
currentLine++;
}
// If we have only used one or two lines, move everything down by one.
if (currentLine < 2) {
lines[2]=lines[1];
lines[1]=lines[0];
lines[0]="";
}
return lines;
}
| public static String[] signWrite(String s) {
// Create array to hold the lines, and initialise with empty strings
String[] lines = new String[4];
int currentLine = 0;
for (int i = 0; i < 4; i++) lines[i] = "";
// Split the message into strings on whitespace
String[] words = s.split("\\s");
// Loop through words, adding them to lines as they fit
int currentWord = 0;
while(currentLine < 4 && currentWord < words.length) {
if (lines[currentLine].length() + words[currentWord].length() <= 14)
lines[currentLine] += " " + words[currentWord++];
else
currentLine++;
}
// If we have only used one or two lines, move everything down by one.
if (currentLine < 2) {
lines[2]=lines[1];
lines[1]=lines[0];
lines[0]="";
}
return lines;
}
|
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
index 989020184..415c37ee7 100644
--- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
+++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
@@ -1,1608 +1,1606 @@
/*******************************************************************************
* Copyright (c) 2007, 2013 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.ui.model;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenCountUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.memory.IMemoryRenderingSite;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.tcf.debug.ui.ITCFDebugUIConstants;
import org.eclipse.tcf.debug.ui.ITCFExecContext;
import org.eclipse.tcf.internal.debug.model.TCFContextState;
import org.eclipse.tcf.internal.debug.model.TCFFunctionRef;
import org.eclipse.tcf.internal.debug.model.TCFSourceRef;
import org.eclipse.tcf.internal.debug.model.TCFSymFileRef;
import org.eclipse.tcf.internal.debug.ui.ColorCache;
import org.eclipse.tcf.internal.debug.ui.ImageCache;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.ILineNumbers;
import org.eclipse.tcf.services.IMemory;
import org.eclipse.tcf.services.IMemoryMap;
import org.eclipse.tcf.services.IProcesses;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.services.ISymbols;
import org.eclipse.tcf.util.TCFDataCache;
import org.eclipse.ui.IWorkbenchPart;
public class TCFNodeExecContext extends TCFNode implements ISymbolOwner, ITCFExecContext {
private final TCFChildrenExecContext children_exec;
private final TCFChildrenStackTrace children_stack;
private final TCFChildrenRegisters children_regs;
private final TCFChildrenExpressions children_exps;
private final TCFChildrenHoverExpressions children_hover_exps;
private final TCFChildrenLogExpressions children_log_exps;
private final TCFChildrenModules children_modules;
private final TCFChildrenContextQuery children_query;
private final TCFData<IMemory.MemoryContext> mem_context;
private final TCFData<IRunControl.RunControlContext> run_context;
private final TCFData<MemoryRegion[]> memory_map;
private final TCFData<IProcesses.ProcessContext> prs_context;
private final TCFData<TCFContextState> state;
private final TCFData<BigInteger> address; // Current PC as BigInteger
private final TCFData<Collection<Map<String,Object>>> signal_list;
private final TCFData<SignalMask[]> signal_mask;
private final TCFData<TCFNodeExecContext> memory_node;
private final TCFData<TCFNodeExecContext> symbols_node;
private final TCFData<String> full_name;
private LinkedHashMap<BigInteger,TCFDataCache<TCFSymFileRef>> syms_info_lookup_cache;
private LinkedHashMap<BigInteger,TCFDataCache<TCFSourceRef>> line_info_lookup_cache;
private LinkedHashMap<BigInteger,TCFDataCache<TCFFunctionRef>> func_info_lookup_cache;
private LookupCacheTimer lookup_cache_timer;
private int mem_seq_no;
private int exe_seq_no;
private static final TCFNode[] empty_node_array = new TCFNode[0];
/*
* LookupCacheTimer is executed periodically to dispose least-recently
* accessed entries in line_info_lookup_cache and func_info_lookup_cache.
* The timer disposes itself when both caches become empty.
*/
private class LookupCacheTimer implements Runnable {
LookupCacheTimer() {
Protocol.invokeLater(4000, this);
}
public void run() {
if (isDisposed()) return;
if (syms_info_lookup_cache != null) {
BigInteger addr = syms_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = syms_info_lookup_cache.get(addr);
if (!cache.isPending()) {
syms_info_lookup_cache.remove(addr).dispose();
if (syms_info_lookup_cache.size() == 0) syms_info_lookup_cache = null;
}
}
if (line_info_lookup_cache != null) {
BigInteger addr = line_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = line_info_lookup_cache.get(addr);
if (!cache.isPending()) {
line_info_lookup_cache.remove(addr).dispose();
if (line_info_lookup_cache.size() == 0) line_info_lookup_cache = null;
}
}
if (func_info_lookup_cache != null) {
BigInteger addr = func_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = func_info_lookup_cache.get(addr);
if (!cache.isPending()) {
func_info_lookup_cache.remove(addr).dispose();
if (func_info_lookup_cache.size() == 0) func_info_lookup_cache = null;
}
}
if (syms_info_lookup_cache == null && line_info_lookup_cache == null && func_info_lookup_cache == null) {
lookup_cache_timer = null;
}
else {
Protocol.invokeLater(2500, this);
}
}
}
public static class ChildrenStateInfo {
public boolean running;
public boolean suspended;
public boolean not_active;
public boolean breakpoint;
}
private final Map<String,TCFNodeSymbol> symbols = new HashMap<String,TCFNodeSymbol>();
private int resumed_cnt;
private boolean resume_pending;
private boolean resumed_by_action;
private TCFNode[] last_stack_trace;
private TCFNode[] last_children_list;
private String last_label;
private ImageDescriptor last_image;
private ChildrenStateInfo last_children_state_info;
private boolean delayed_children_list_delta;
/**
* Wrapper class for IMemoryMap.MemoryRegion.
* The class help to search memory region by address by
* providing contains() method.
*/
public static class MemoryRegion {
private final BigInteger addr_start;
private final BigInteger addr_end;
public final IMemoryMap.MemoryRegion region;
private MemoryRegion(IMemoryMap.MemoryRegion region) {
this.region = region;
Number addr = region.getAddress();
Number size = region.getSize();
if (addr == null || size == null) {
addr_start = null;
addr_end = null;
}
else {
addr_start = JSON.toBigInteger(addr);
addr_end = addr_start.add(JSON.toBigInteger(size));
}
}
public boolean contains(BigInteger addr) {
return
addr_start != null && addr_end != null &&
addr_start.compareTo(addr) <= 0 &&
addr_end.compareTo(addr) > 0;
}
@Override
public String toString() {
return region.getProperties().toString();
}
}
public static class SignalMask {
protected Map<String,Object> props;
protected boolean dont_stop;
protected boolean dont_pass;
protected boolean pending;
public Number getIndex() {
return (Number)props.get(IProcesses.SIG_INDEX);
}
public Number getCode() {
return (Number)props.get(IProcesses.SIG_CODE);
}
public Map<String,Object> getProperties() {
return props;
}
public boolean isDontStop() {
return dont_stop;
}
public boolean isDontPass() {
return dont_pass;
}
public boolean isPending() {
return pending;
}
@Override
public String toString() {
StringBuffer bf = new StringBuffer();
bf.append("[attrs=");
bf.append(props.toString());
if (dont_stop) bf.append(",don't stop");
if (dont_pass) bf.append(",don't pass");
if (pending) bf.append(",pending");
bf.append(']');
return bf.toString();
}
}
TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
- if (res.contains("/")) res = "\"" + res + "\"";
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
- if (name.contains("/")) name = "\"" + name + "\"";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
String name = lst.get(i - 1);
boolean quote = name.indexOf('/') >= 0;
bf.append('/');
if (quote) bf.append('"');
bf.append(name);
if (quote) bf.append('"');
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
@Override
void dispose() {
assert !isDisposed();
ArrayList<TCFNodeSymbol> l = new ArrayList<TCFNodeSymbol>(symbols.values());
for (TCFNodeSymbol s : l) s.dispose();
assert symbols.size() == 0;
super.dispose();
}
void setMemSeqNo(int no) {
mem_seq_no = no;
}
void setExeSeqNo(int no) {
exe_seq_no = no;
}
TCFChildren getHoverExpressionCache(String expression) {
children_hover_exps.setExpression(expression);
return children_hover_exps;
}
public TCFChildrenLogExpressions getLogExpressionCache() {
return children_log_exps;
}
void setRunContext(IRunControl.RunControlContext ctx) {
run_context.reset(ctx);
}
void setProcessContext(IProcesses.ProcessContext ctx) {
prs_context.reset(ctx);
}
void setMemoryContext(IMemory.MemoryContext ctx) {
mem_context.reset(ctx);
}
public TCFDataCache<TCFNodeExecContext> getSymbolsNode() {
return symbols_node;
}
public TCFDataCache<TCFNodeExecContext> getMemoryNode() {
return memory_node;
}
public TCFDataCache<MemoryRegion[]> getMemoryMap() {
return memory_map;
}
public TCFDataCache<Collection<Map<String,Object>>> getSignalList() {
return signal_list;
}
public TCFDataCache<SignalMask[]> getSignalMask() {
return signal_mask;
}
public TCFDataCache<TCFSymFileRef> getSymFileInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFSymFileRef> ref_cache;
if (syms_info_lookup_cache != null) {
ref_cache = syms_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ISymbols syms = launch.getService(ISymbols.class);
if (syms == null) return null;
if (syms_info_lookup_cache == null) {
syms_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFSymFileRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
syms_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFSymFileRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFSymFileRef ref_data = new TCFSymFileRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = syms.getSymFileInfo(ref_data.context_id, addr, new ISymbols.DoneGetSymFileInfo() {
public void doneGetSymFileInfo(IToken token, Exception error, Map<String,Object> props) {
ref_data.address = addr;
ref_data.error = error;
ref_data.props = props;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
public TCFDataCache<TCFSourceRef> getLineInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFSourceRef> ref_cache;
if (line_info_lookup_cache != null) {
ref_cache = line_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ILineNumbers ln = launch.getService(ILineNumbers.class);
if (ln == null) return null;
final BigInteger n0 = addr;
final BigInteger n1 = n0.add(BigInteger.valueOf(1));
if (line_info_lookup_cache == null) {
line_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFSourceRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
line_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFSourceRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFSourceRef ref_data = new TCFSourceRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = ln.mapToSource(id, n0, n1, new ILineNumbers.DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, ILineNumbers.CodeArea[] areas) {
ref_data.address = addr;
if (error == null && areas != null && areas.length > 0) {
for (ILineNumbers.CodeArea area : areas) {
BigInteger a0 = JSON.toBigInteger(area.start_address);
BigInteger a1 = JSON.toBigInteger(area.end_address);
if (n0.compareTo(a0) >= 0 && n0.compareTo(a1) < 0) {
if (ref_data.area == null || area.start_line < ref_data.area.start_line) {
if (area.start_address != a0 || area.end_address != a1) {
area = new ILineNumbers.CodeArea(area.directory, area.file,
area.start_line, area.start_column,
area.end_line, area.end_column,
a0, a1, area.isa,
area.is_statement, area.basic_block,
area.prologue_end, area.epilogue_begin);
}
ref_data.area = area;
}
}
}
}
ref_data.error = error;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
public TCFDataCache<TCFFunctionRef> getFuncInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFFunctionRef> ref_cache;
if (func_info_lookup_cache != null) {
ref_cache = func_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ISymbols syms = launch.getService(ISymbols.class);
if (syms == null) return null;
if (func_info_lookup_cache == null) {
func_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFFunctionRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
func_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFFunctionRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFFunctionRef ref_data = new TCFFunctionRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = syms.findByAddr(id, addr, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
ref_data.address = addr;
ref_data.error = error;
ref_data.symbol_id = symbol_id;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
private void clearLookupCaches() {
if (syms_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFSymFileRef>> i = syms_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFSymFileRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (syms_info_lookup_cache.size() == 0) syms_info_lookup_cache = null;
}
if (line_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFSourceRef>> i = line_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFSourceRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (line_info_lookup_cache.size() == 0) line_info_lookup_cache = null;
}
if (func_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFFunctionRef>> i = func_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFFunctionRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (func_info_lookup_cache.size() == 0) func_info_lookup_cache = null;
}
}
@Override
public TCFNode getParent(IPresentationContext ctx) {
assert Protocol.isDispatchThread();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(ctx.getId())) {
Set<String> ids = launch.getContextFilter();
if (ids != null) {
if (ids.contains(id)) return model.getRootNode();
if (parent instanceof TCFNodeLaunch) return null;
}
}
return parent;
}
public TCFDataCache<IRunControl.RunControlContext> getRunContext() {
return run_context;
}
public TCFDataCache<IProcesses.ProcessContext> getProcessContext() {
return prs_context;
}
public TCFDataCache<IMemory.MemoryContext> getMemoryContext() {
return mem_context;
}
public TCFDataCache<BigInteger> getAddress() {
return address;
}
public TCFDataCache<TCFContextState> getState() {
return state;
}
public TCFChildrenStackTrace getStackTrace() {
return children_stack;
}
public TCFChildren getRegisters() {
return children_regs;
}
public TCFChildren getModules() {
return children_modules;
}
public TCFChildren getChildren() {
return children_exec;
}
public TCFNodeStackFrame getLastTopFrame() {
if (!resume_pending) return null;
if (last_stack_trace == null || last_stack_trace.length == 0) return null;
return (TCFNodeStackFrame)last_stack_trace[0];
}
public TCFNodeStackFrame getViewBottomFrame() {
if (last_stack_trace == null || last_stack_trace.length == 0) return null;
return (TCFNodeStackFrame)last_stack_trace[last_stack_trace.length - 1];
}
/**
* Get context full name - including all ancestor names.
* Return context ID if the context does not have a name.
* @return cache item with the context full name.
*/
public TCFDataCache<String> getFullName() {
return full_name;
}
public void addSymbol(TCFNodeSymbol s) {
assert symbols.get(s.id) == null;
symbols.put(s.id, s);
}
public void removeSymbol(TCFNodeSymbol s) {
assert symbols.get(s.id) == s;
symbols.remove(s.id);
}
/**
* Return true if this context cannot be accessed because it is not active.
* Not active means the target is suspended, but this context is not one that is
* currently scheduled to run on a target CPU, and the debuggers don't support
* access to register values and other properties of such contexts.
*/
public boolean isNotActive() {
TCFContextState state_data = state.getData();
if (state_data != null) return state_data.isNotActive();
return false;
}
private boolean okToShowLastStack() {
return resume_pending && last_stack_trace != null;
}
private boolean okToHideStack() {
TCFContextState state_data = state.getData();
if (state_data == null) return true;
if (!state_data.is_suspended) return true;
if (state_data.isNotActive()) return true;
return false;
}
@Override
protected boolean getData(IChildrenCountUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
result.setChildCount(last_stack_trace.length);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
result.setChildCount(0);
return true;
}
children = children_stack;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
result.setChildCount(last_children_list.length);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children != null) {
if (!children.validate(done)) return false;
if (children == children_stack) last_stack_trace = children_stack.toArray();
if (children == children_exec) last_children_list = children_exec.toArray();
result.setChildCount(children.size());
}
else {
result.setChildCount(0);
}
return true;
}
private void setResultChildren(IChildrenUpdate result, TCFNode[] arr) {
int offset = 0;
int r_offset = result.getOffset();
int r_length = result.getLength();
for (TCFNode n : arr) {
if (offset >= r_offset && offset < r_offset + r_length) {
result.setChild(n, offset);
}
offset++;
}
}
@Override
protected boolean getData(IChildrenUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
setResultChildren(result, last_stack_trace);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
return true;
}
// Force creation of register nodes.
// It helps dispatching of registerChanged events to stack frames.
if (!children_regs.validate(done)) return false;
children = children_stack;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
setResultChildren(result, last_children_list);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children == null) return true;
if (children == children_stack) {
if (!children.validate(done)) return false;
last_stack_trace = children_stack.toArray();
}
if (children == children_exec) {
if (!children.validate(done)) return false;
last_children_list = children_exec.toArray();
}
return children.getData(result, done);
}
@Override
protected boolean getData(IHasChildrenUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
result.setHasChilren(last_stack_trace.length > 0);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
result.setHasChilren(false);
return true;
}
Boolean has_children = children_stack.checkHasChildren(done);
if (has_children == null) return false;
result.setHasChilren(has_children);
return true;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
result.setHasChilren(last_children_list.length > 0);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children != null) {
if (!children.validate(done)) return false;
if (children == children_stack) last_stack_trace = children_stack.toArray();
if (children == children_exec) last_children_list = children_exec.toArray();
result.setHasChilren(children.size() > 0);
}
else {
result.setHasChilren(false);
}
return true;
}
@Override
protected boolean getData(ILabelUpdate result, Runnable done) {
if (!run_context.validate(done)) return false;
String image_name = null;
boolean suspended_by_bp = false;
ChildrenStateInfo children_state_info = null;
StringBuffer label = new StringBuffer();
Throwable error = run_context.getError();
if (error != null) {
result.setForeground(ColorCache.rgb_error, 0);
label.append(id);
label.append(": ");
label.append(TCFModel.getErrorMessage(error, false));
}
else {
String view_id = result.getPresentationContext().getId();
if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
TCFChildrenContextQuery.Descendants des = TCFChildrenContextQuery.getDescendants(this, result, done);
if (des == null) return false;
if (des.map != null && des.map.size() > 0) {
label.append("(");
label.append(des.map.size());
label.append(") ");
}
if (!des.include_parent) result.setForeground(ColorCache.rgb_disabled, 0);
}
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null) {
label.append(id);
}
else {
String nm = ctx.getName();
if (nm == null && !ctx.hasState()) {
String prs = ctx.getProcessID();
if (prs != null) {
if (!prs_context.validate(done)) return false;
IProcesses.ProcessContext pctx = prs_context.getData();
if (pctx != null) nm = pctx.getName();
}
}
label.append(nm != null ? nm : id);
Object info = ctx.getProperties().get("AdditionalInfo");
if (info != null) label.append(info.toString());
if (TCFModel.ID_PINNED_VIEW.equals(view_id) || ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
image_name = ctx.hasState() ? ImageCache.IMG_THREAD_UNKNOWN_STATE : ImageCache.IMG_PROCESS_RUNNING;
}
else if (ctx.hasState()) {
// Thread
if (resume_pending && resumed_by_action || model.getActiveAction(id) != null) {
if (!state.validate(done)) return false;
TCFContextState state_data = state.getData();
image_name = ImageCache.IMG_THREAD_UNKNOWN_STATE;
if (state_data != null && !state_data.is_suspended) {
if (state_data.isReversing()) {
image_name = ImageCache.IMG_THREAD_REVERSING;
label.append(" (Reversing)");
}
else {
image_name = ImageCache.IMG_THREAD_RUNNNIG;
label.append(" (Running)");
}
}
if (resume_pending && last_label != null) {
result.setImageDescriptor(ImageCache.getImageDescriptor(image_name), 0);
result.setLabel(last_label, 0);
return true;
}
}
else if (resume_pending && last_label != null && last_image != null) {
result.setImageDescriptor(last_image, 0);
result.setLabel(last_label, 0);
return true;
}
else {
if (!state.validate(done)) return false;
TCFContextState state_data = state.getData();
if (isNotActive()) {
image_name = ImageCache.IMG_THREAD_NOT_ACTIVE;
label.append(" (Not active)");
if (state_data.suspend_reason != null && !state_data.suspend_reason.equals(IRunControl.REASON_USER_REQUEST)) {
label.append(" - ");
label.append(state_data.suspend_reason);
}
}
else {
image_name = ImageCache.IMG_THREAD_UNKNOWN_STATE;
if (state_data != null) {
if (!state_data.is_suspended) {
if (state_data.isReversing()) {
image_name = ImageCache.IMG_THREAD_REVERSING;
label.append(" (Reversing)");
}
else {
image_name = ImageCache.IMG_THREAD_RUNNNIG;
label.append(" (Running)");
}
}
else {
image_name = ImageCache.IMG_THREAD_SUSPENDED;
String s = null;
String r = model.getContextActionResult(id);
if (r == null) {
r = state_data.suspend_reason;
if (state_data.suspend_params != null) {
s = (String)state_data.suspend_params.get(IRunControl.STATE_SIGNAL_DESCRIPTION);
if (s == null) s = (String)state_data.suspend_params.get(IRunControl.STATE_SIGNAL_NAME);
}
}
suspended_by_bp = IRunControl.REASON_BREAKPOINT.equals(r);
if (r == null) r = "Suspended";
if (s != null) r += ": " + s;
label.append(" (");
label.append(r);
if (state_data.suspend_params != null) {
String prs = (String)state_data.suspend_params.get("Context");
if (prs != null) {
label.append(", ");
label.append(prs);
}
String cpu = (String)state_data.suspend_params.get("CPU");
if (cpu != null) {
label.append(", ");
label.append(cpu);
}
}
label.append(")");
}
}
}
}
}
else {
// Thread container (process)
children_state_info = new ChildrenStateInfo();
if (!hasSuspendedChildren(children_state_info, done)) return false;
if (children_state_info.suspended) image_name = ImageCache.IMG_PROCESS_SUSPENDED;
else image_name = ImageCache.IMG_PROCESS_RUNNING;
suspended_by_bp = children_state_info.breakpoint;
}
}
}
last_children_state_info = children_state_info;
last_image = ImageCache.getImageDescriptor(image_name);
if (suspended_by_bp) last_image = ImageCache.addOverlay(last_image, ImageCache.IMG_BREAKPOINT_OVERLAY);
result.setImageDescriptor(last_image, 0);
result.setLabel(last_label = label.toString(), 0);
return true;
}
@Override
protected boolean getData(IViewerInputUpdate result, Runnable done) {
result.setInputElement(this);
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_VARIABLE_VIEW.equals(view_id)) {
if (!children_stack.validate(done)) return false;
TCFNodeStackFrame frame = children_stack.getTopFrame();
if (frame != null) result.setInputElement(frame);
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
// TODO: need to post view input delta when memory context changes
TCFDataCache<TCFNodeExecContext> mem = model.searchMemoryContext(this);
if (mem == null) return true;
if (!mem.validate(done)) return false;
if (mem.getData() == null) return true;
result.setInputElement(mem.getData());
}
return true;
}
@Override
public void refresh(IWorkbenchPart part) {
if (part instanceof IMemoryRenderingSite) {
model.onMemoryChanged(id, false, false, false);
}
else {
last_children_list = null;
last_children_state_info = null;
last_stack_trace = null;
last_label = null;
last_image = null;
super.refresh(part);
}
}
void postAllChangedDelta() {
postContentChangedDelta();
postStateChangedDelta();
}
void postContextAddedDelta() {
if (parent instanceof TCFNodeExecContext) {
TCFNodeExecContext exe = (TCFNodeExecContext)parent;
ChildrenStateInfo info = exe.last_children_state_info;
if (info != null) {
if (!model.getAutoChildrenListUpdates()) {
// Manual updates.
return;
}
if (!info.suspended && !info.not_active && model.getDelayChildrenListUpdates()) {
// Delay content update until a child is suspended.
exe.delayed_children_list_delta = true;
return;
}
}
}
for (TCFModelProxy p : model.getModelProxies()) {
String view_id = p.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
/* Note: should use IModelDelta.INSERTED but it is broken in Eclipse 3.6 */
p.addDelta(this, IModelDelta.ADDED);
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
p.addDelta(parent, IModelDelta.CONTENT);
}
}
}
private void postContextRemovedDelta() {
if (parent instanceof TCFNodeExecContext) {
TCFNodeExecContext exe = (TCFNodeExecContext)parent;
ChildrenStateInfo info = exe.last_children_state_info;
if (info != null) {
if (!model.getAutoChildrenListUpdates()) {
// Manual updates.
return;
}
if (!info.suspended && !info.not_active && model.getDelayChildrenListUpdates()) {
// Delay content update until a child is suspended.
exe.delayed_children_list_delta = true;
return;
}
}
}
for (TCFModelProxy p : model.getModelProxies()) {
String view_id = p.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
p.addDelta(this, IModelDelta.REMOVED);
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
p.addDelta(parent, IModelDelta.CONTENT);
}
}
// Update parent icon overlays
TCFNode n = parent;
while (n instanceof TCFNodeExecContext) {
TCFNodeExecContext e = (TCFNodeExecContext)n;
ChildrenStateInfo info = e.last_children_state_info;
if (info != null && info.suspended) e.postStateChangedDelta();
n = n.parent;
}
}
private void postContentChangedDelta() {
delayed_children_list_delta = false;
for (TCFModelProxy p : model.getModelProxies()) {
int flags = 0;
String view_id = p.getPresentationContext().getId();
if ( (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id) ||
ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) &&
(launch.getContextActionsCount(id) == 0 || !model.getDelayStackUpdateUtilLastStep()))
{
flags |= IModelDelta.CONTENT;
}
if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id) ||
IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id) ||
TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (p.getInput() == this) flags |= IModelDelta.CONTENT;
}
if (flags == 0) continue;
p.addDelta(this, flags);
}
}
private void postAllAndParentsChangedDelta() {
postContentChangedDelta();
TCFNode n = this;
while (n instanceof TCFNodeExecContext) {
TCFNodeExecContext e = (TCFNodeExecContext)n;
if (e.delayed_children_list_delta) e.postContentChangedDelta();
e.postStateChangedDelta();
n = n.parent;
}
}
public void postStateChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.STATE);
}
}
}
private void postModulesChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_MODULE_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.CONTENT);
}
}
}
private void postStackChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.CONTENT);
}
}
}
void onContextAdded(IRunControl.RunControlContext context) {
model.setDebugViewSelection(this, IRunControl.REASON_USER_REQUEST);
children_exec.onContextAdded(context);
}
void onContextChanged(IRunControl.RunControlContext context) {
assert !isDisposed();
full_name.reset();
run_context.reset(context);
symbols_node.reset();
memory_node.reset();
signal_mask.reset();
if (state.isValid()) {
TCFContextState s = state.getData();
if (s == null || s.is_suspended) state.reset();
}
children_stack.reset();
children_stack.onSourceMappingChange();
children_regs.reset();
children_exec.onAncestorContextChanged();
for (TCFNodeSymbol s : symbols.values()) s.onMemoryMapChanged();
postAllChangedDelta();
}
void onAncestorContextChanged() {
full_name.reset();
}
void onContextAdded(IMemory.MemoryContext context) {
children_exec.onContextAdded(context);
}
void onContextChanged(IMemory.MemoryContext context) {
assert !isDisposed();
clearLookupCaches();
mem_context.reset(context);
for (TCFNodeSymbol s : symbols.values()) s.onMemoryMapChanged();
postAllChangedDelta();
}
void onContextRemoved() {
assert !isDisposed();
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
dispose();
postContextRemovedDelta();
launch.removeContextActions(id);
}
void onExpressionAddedOrRemoved() {
children_exps.cancel();
children_stack.onExpressionAddedOrRemoved();
}
void onContainerSuspended(boolean func_call) {
assert !isDisposed();
if (run_context.isValid()) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && !ctx.hasState()) return;
}
onContextSuspended(null, null, null, func_call);
}
void onContainerResumed() {
assert !isDisposed();
if (run_context.isValid()) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && !ctx.hasState()) return;
}
onContextResumed();
}
void onContextSuspended(String pc, String reason, Map<String,Object> params, boolean func_call) {
assert !isDisposed();
if (pc != null) {
TCFContextState s = new TCFContextState();
s.is_suspended = true;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
state.reset(s);
}
else {
state.reset();
}
address.reset();
signal_mask.reset();
children_stack.onSuspended(func_call);
children_exps.onSuspended(func_call);
children_hover_exps.onSuspended(func_call);
children_regs.onSuspended(func_call);
if (!func_call) {
children_log_exps.onSuspended();
}
for (TCFNodeSymbol s : symbols.values()) s.onExeStateChange();
if (model.getActiveAction(id) == null) {
boolean update_now = pc != null || resumed_by_action;
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
if (update_now) {
children_stack.postAllChangedDelta();
postAllAndParentsChangedDelta();
}
else {
final int cnt = resumed_cnt;
Protocol.invokeLater(500, new Runnable() {
public void run() {
if (cnt != resumed_cnt) return;
if (isDisposed()) return;
children_stack.postAllChangedDelta();
postAllAndParentsChangedDelta();
}
});
}
}
}
void onContextResumed() {
assert !isDisposed();
state.reset();
if (!resume_pending) {
final int cnt = ++resumed_cnt;
resume_pending = true;
resumed_by_action = model.getActiveAction(id) != null;
if (resumed_by_action) postAllChangedDelta();
Protocol.invokeLater(400, new Runnable() {
public void run() {
if (cnt != resumed_cnt) return;
if (isDisposed()) return;
resume_pending = false;
postAllAndParentsChangedDelta();
model.onContextRunning();
}
});
}
}
void onContextActionDone() {
assert state.isValid();
if (state.getData() == null || state.getData().is_suspended) {
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
}
postAllChangedDelta();
children_stack.postAllChangedDelta();
}
void onContextException(String msg) {
}
void onMemoryChanged(Number[] addr, long[] size) {
assert !isDisposed();
children_stack.onMemoryChanged();
children_exps.onMemoryChanged();
children_hover_exps.onMemoryChanged();
children_log_exps.onMemoryChanged();
postContentChangedDelta();
}
void onMemoryMapChanged() {
clearLookupCaches();
memory_map.reset();
children_modules.onMemoryMapChanged();
children_stack.onMemoryMapChanged();
children_exps.onMemoryMapChanged();
children_hover_exps.onMemoryMapChanged();
children_log_exps.onMemoryMapChanged();
postContentChangedDelta();
postModulesChangedDelta();
}
void onRegistersChanged() {
children_stack.onRegistersChanged();
postContentChangedDelta();
}
void onRegisterValueChanged() {
if (state.isValid()) {
TCFContextState s = state.getData();
if (s == null || s.is_suspended) state.reset();
}
address.reset();
children_stack.onRegisterValueChanged();
children_exps.onRegisterValueChanged();
children_hover_exps.onRegisterValueChanged();
children_log_exps.onRegisterValueChanged();
postContentChangedDelta();
}
void onPreferencesChanged() {
if (delayed_children_list_delta && !model.getDelayChildrenListUpdates() ||
model.getAutoChildrenListUpdates()) postContentChangedDelta();
children_stack.onPreferencesChanged();
postStackChangedDelta();
}
void riseTraceLimit() {
children_stack.riseTraceLimit();
postStackChangedDelta();
}
public boolean hasSuspendedChildren(ChildrenStateInfo info, Runnable done) {
if (!children_exec.validate(done)) return false;
Map<String,TCFNode> m = children_exec.getData();
if (m == null || m.size() == 0) return true;
for (TCFNode n : m.values()) {
if (!(n instanceof TCFNodeExecContext)) continue;
TCFNodeExecContext e = (TCFNodeExecContext)n;
if (!e.run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = e.run_context.getData();
if (ctx != null && ctx.hasState()) {
TCFDataCache<TCFContextState> state_cache = e.getState();
if (!state_cache.validate(done)) return false;
TCFContextState state_data = state_cache.getData();
if (state_data != null) {
if (!state_data.is_suspended) {
info.running = true;
}
else if (e.isNotActive()) {
info.not_active = true;
}
else {
info.suspended = true;
String r = model.getContextActionResult(e.id);
if (r == null) r = state_data.suspend_reason;
if (IRunControl.REASON_BREAKPOINT.equals(r)) info.breakpoint = true;
}
}
}
else {
if (!e.hasSuspendedChildren(info, done)) return false;
}
if (info.breakpoint && info.running) break;
}
return true;
}
@Override
public int compareTo(TCFNode n) {
if (n instanceof TCFNodeExecContext) {
TCFNodeExecContext f = (TCFNodeExecContext)n;
if (mem_seq_no < f.mem_seq_no) return -1;
if (mem_seq_no > f.mem_seq_no) return +1;
if (exe_seq_no < f.exe_seq_no) return -1;
if (exe_seq_no > f.exe_seq_no) return +1;
}
return id.compareTo(n.id);
}
}
| false | true | TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
if (res.contains("/")) res = "\"" + res + "\"";
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
if (name.contains("/")) name = "\"" + name + "\"";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
String name = lst.get(i - 1);
boolean quote = name.indexOf('/') >= 0;
bf.append('/');
if (quote) bf.append('"');
bf.append(name);
if (quote) bf.append('"');
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
| TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
String name = lst.get(i - 1);
boolean quote = name.indexOf('/') >= 0;
bf.append('/');
if (quote) bf.append('"');
bf.append(name);
if (quote) bf.append('"');
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
|
diff --git a/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java b/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
index e39cca3..6299e4e 100644
--- a/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
+++ b/src/org/treblefrei/kedr/database/musicdns/DigestMaker.java
@@ -1,82 +1,83 @@
package org.treblefrei.kedr.database.musicdns;
import org.treblefrei.kedr.audio.AudioDecoder;
import org.treblefrei.kedr.audio.AudioDecoderException;
import org.treblefrei.kedr.audio.DecodedAudioData;
import org.treblefrei.kedr.database.musicdns.ofa.Ofa;
import org.treblefrei.kedr.model.Album;
import org.treblefrei.kedr.model.Track;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class DigestMakerRunnable implements Runnable {
private Track track;
private Map<Track, Digest> store;
public DigestMakerRunnable(Track track, Map<Track, Digest> store) {
this.track = track;
this.store = store;
}
public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
+ String digestString = Ofa.createPrint(audioData);
synchronized (store) {
try {
- store.put(track, new Digest(Ofa.createPrint(audioData)));
+ store.put(track, new Digest(digestString));
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
public class DigestMaker {
public static Map<Track, Digest> getAlbumDigest(Album album) throws AudioDecoderException, FileNotFoundException {
List<Track> tracks = album.getTracks();
Map<Track, Digest> digests = new HashMap<Track, Digest>();
for (Track track : tracks) {
DecodedAudioData audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
digests.put(track, new Digest(Ofa.createPrint(audioData)));
}
return digests;
}
public static Map<Track, Digest> getAlbumDigestThreaded(Album album) {
List<Track> tracks = album.getTracks();
Map<Track, Digest> digests = new HashMap<Track, Digest>();
ExecutorService executor = Executors.newCachedThreadPool();
for (Track track : tracks) {
executor.execute(new DigestMakerRunnable(track, digests));
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
return digests;
}
}
| false | true | public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
synchronized (store) {
try {
store.put(track, new Digest(Ofa.createPrint(audioData)));
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| public void run() {
DecodedAudioData audioData = null;
try {
audioData = AudioDecoder.getSamples(track.getFilepath(), 135);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
track.setDuration(audioData.getDuration());
track.setFormat(audioData.getFormat());
String digestString = Ofa.createPrint(audioData);
synchronized (store) {
try {
store.put(track, new Digest(digestString));
} catch (AudioDecoderException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
|
diff --git a/java5/org/directwebremoting/annotations/AnnotationsConfigurator.java b/java5/org/directwebremoting/annotations/AnnotationsConfigurator.java
index 23e5d42b..b9c91590 100644
--- a/java5/org/directwebremoting/annotations/AnnotationsConfigurator.java
+++ b/java5/org/directwebremoting/annotations/AnnotationsConfigurator.java
@@ -1,336 +1,336 @@
/*
* Copyright 2006 Maik Schreiber <blizzy AT blizzy DOT de>
*
* 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.directwebremoting.annotations;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.directwebremoting.AjaxFilter;
import org.directwebremoting.Container;
import org.directwebremoting.convert.BeanConverter;
import org.directwebremoting.create.NewCreator;
import org.directwebremoting.extend.AccessControl;
import org.directwebremoting.extend.AjaxFilterManager;
import org.directwebremoting.extend.Configurator;
import org.directwebremoting.extend.Converter;
import org.directwebremoting.extend.ConverterManager;
import org.directwebremoting.extend.Creator;
import org.directwebremoting.extend.CreatorManager;
import org.directwebremoting.util.LocalUtil;
import org.directwebremoting.util.Logger;
/**
* A Configurator that works off Annotations.
* @author Maik Schreiber [blizzy AT blizzy DOT de]
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class AnnotationsConfigurator implements Configurator
{
/* (non-Javadoc)
* @see org.directwebremoting.Configurator#configure(org.directwebremoting.Container)
*/
public void configure(Container container)
{
Object data = container.getBean("classes");
if (data == null)
{
return;
}
if (data instanceof String)
{
String classesStr = (String) data;
String[] classNames = classesStr.split(",");
for (int i = 0; i < classNames.length; i++)
{
String className = classNames[i].trim();
try
{
Class<?> clazz = LocalUtil.classForName(className);
processClass(clazz, container);
}
catch (Exception ex)
{
log.error("Failed to process class: " + className, ex);
}
}
}
else
{
try
{
processClass(data.getClass(), container);
}
catch (Exception ex)
{
log.error("Failed to process class: " + data.getClass().getName(), ex);
}
}
}
/**
* Process the annotations on a given class
* @param clazz The class to search for annotations
* @param container The IoC container to configure
* @throws IllegalAccessException If annotation processing fails
* @throws InstantiationException If annotation processing fails
*/
private void processClass(Class<?> clazz, Container container) throws InstantiationException, IllegalAccessException
{
RemoteProxy createAnn = clazz.getAnnotation(RemoteProxy.class);
if (createAnn != null)
{
processCreate(clazz, createAnn, container);
}
DataTransferObject convertAnn = clazz.getAnnotation(DataTransferObject.class);
if (convertAnn != null)
{
processConvert(clazz, convertAnn, container);
}
GlobalFilter globalFilterAnn = clazz.getAnnotation(GlobalFilter.class);
if (globalFilterAnn != null)
{
processGlobalFilter(clazz, globalFilterAnn, container);
}
}
/**
* Process the @RemoteProxy annotaion on a given class
* @param clazz The class annotated with @RemoteProxy
* @param createAnn The annotation
* @param container The IoC container to configure
*/
private void processCreate(Class<?> clazz, RemoteProxy createAnn, Container container)
{
Class<? extends Creator> creator = createAnn.creator();
String creatorClass = creator.getName();
Map<String, String> creatorParams = getParamsMap(createAnn.creatorParams());
ScriptScope scope = createAnn.scope();
CreatorManager creatorManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
String creatorName = LocalUtil.replace(creatorClass, ".", "_");
creatorManager.addCreatorType(creatorName, creatorClass);
Map<String, String> params = new HashMap<String, String>();
- if (NewCreator.class.isAssignableFrom(NewCreator.class))
+ if (NewCreator.class.isAssignableFrom(creator))
{
params.put("class", clazz.getName());
}
params.putAll(creatorParams);
params.put("scope", scope.getValue());
String name = createAnn.name();
if (name == null || name.length() == 0)
{
name = LocalUtil.getShortClassName(clazz);
}
try
{
log.info("Adding class " + clazz.getName() + " as " + name);
creatorManager.addCreator(name, creatorName, params);
}
catch (Exception ex)
{
log.error("Failed to add class as Creator: " + clazz.getName(), ex);
}
AccessControl accessControl = (AccessControl) container.getBean(AccessControl.class.getName());
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++)
{
if (methods[i].getAnnotation(RemoteMethod.class) != null)
{
accessControl.addIncludeRule(name, methods[i].getName());
Auth authAnn = methods[i].getAnnotation(Auth.class);
if (authAnn != null)
{
accessControl.addRoleRestriction(name, methods[i].getName(), authAnn.role());
}
}
}
Filters filtersAnn = clazz.getAnnotation(Filters.class);
if (filtersAnn != null)
{
Filter[] fs = filtersAnn.value();
for (int i = 0; i < fs.length; i++)
{
processFilter(fs[i], name, container);
}
}
// process single filter for convenience
else
{
Filter filterAnn = clazz.getAnnotation(Filter.class);
if (filterAnn != null)
{
processFilter(filterAnn, name, container);
}
}
}
/**
* Process the @Filter annotaion
* @param filterAnn The filter annotation
* @param name The Javascript name of the class to filter
* @param container The IoC container to configure
*/
private void processFilter(Filter filterAnn, String name, Container container)
{
Map<String, String> filterParams = getParamsMap(filterAnn.params());
AjaxFilter filter = (AjaxFilter) LocalUtil.classNewInstance(name, filterAnn.type().getName(), AjaxFilter.class);
if (filter != null)
{
LocalUtil.setParams(filter, filterParams, null);
AjaxFilterManager filterManager = (AjaxFilterManager) container.getBean(AjaxFilterManager.class.getName());
filterManager.addAjaxFilter(filter, name);
}
}
/**
* Process the @DataTransferObject annotaion on a given class
* @param clazz The class annotated with @DataTransferObject
* @param convertAnn The annotation
* @param container The IoC container to configure
* @throws InstantiationException
* @throws IllegalAccessException
*/
private void processConvert(Class<?> clazz, DataTransferObject convertAnn, Container container) throws InstantiationException, IllegalAccessException
{
Class<? extends Converter> converter = convertAnn.converter();
String converterClass = converter.getName();
Map<String, String> params = getParamsMap(convertAnn.params());
ConverterManager converterManager = (ConverterManager) container.getBean(ConverterManager.class.getName());
String converterName = LocalUtil.replace(converterClass, ".", "_");
converterManager.addConverterType(converterName, converterClass);
if (BeanConverter.class.isAssignableFrom(converter))
{
StringBuilder properties = new StringBuilder();
Set<Field> fields = new HashSet<Field>();
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
fields.addAll(Arrays.asList(clazz.getFields()));
for (Field field : fields)
{
if (field.getAnnotation(RemoteProperty.class) != null)
{
properties.append(',').append(field.getName());
}
}
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++)
{
if (methods[i].getAnnotation(RemoteProperty.class) != null)
{
String name = methods[i].getName();
if (name.startsWith(METHOD_PREFIX_GET) || name.startsWith(METHOD_PREFIX_IS))
{
if (name.startsWith(METHOD_PREFIX_GET))
{
name = name.substring(3);
}
else
{
name = name.substring(2);
}
name = Introspector.decapitalize(name);
properties.append(',').append(name);
}
}
}
if (properties.length() > 0)
{
properties.deleteCharAt(0);
params.put("include", properties.toString());
}
}
converterManager.addConverter(clazz.getName(), converterName, params);
}
/**
* Global Filters apply to all classes
* @param clazz The class to use as a filter
* @param globalFilterAnn The filter annotation
* @param container The IoC container to configure
* @throws InstantiationException In case we can't create the given clazz
* @throws IllegalAccessException In case we can't create the given clazz
*/
private void processGlobalFilter(Class<?> clazz, GlobalFilter globalFilterAnn, Container container) throws InstantiationException, IllegalAccessException
{
if (!AjaxFilter.class.isAssignableFrom(clazz))
{
throw new IllegalArgumentException(clazz.getName() + " is not an AjaxFilter implementation");
}
Map<String, String> filterParams = getParamsMap(globalFilterAnn.params());
AjaxFilter filter = (AjaxFilter) clazz.newInstance();
if (filter != null)
{
LocalUtil.setParams(filter, filterParams, null);
AjaxFilterManager filterManager = (AjaxFilterManager) container.getBean(AjaxFilterManager.class.getName());
filterManager.addAjaxFilter(filter);
}
}
/**
* Utility to turn a Param array into a Map<String, String>.
* TODO: Should we move this code into Param? Is that even possible?
* @param params The params array from annotations
* @return A Map<String, String>
*/
private Map<String, String> getParamsMap(Param[] params)
{
Map<String, String> result = new HashMap<String, String>();
if (params != null)
{
for (int i = 0; i < params.length; i++)
{
Param p = params[i];
result.put(p.name(), p.value());
}
}
return result;
}
/**
* The getter prefix for boolean variables
*/
private static final String METHOD_PREFIX_IS = "is";
/**
* The getter prefix for non-boolean variables
*/
private static final String METHOD_PREFIX_GET = "get";
/**
* The log stream
*/
private static final Logger log = Logger.getLogger(AnnotationsConfigurator.class);
}
| true | true | private void processCreate(Class<?> clazz, RemoteProxy createAnn, Container container)
{
Class<? extends Creator> creator = createAnn.creator();
String creatorClass = creator.getName();
Map<String, String> creatorParams = getParamsMap(createAnn.creatorParams());
ScriptScope scope = createAnn.scope();
CreatorManager creatorManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
String creatorName = LocalUtil.replace(creatorClass, ".", "_");
creatorManager.addCreatorType(creatorName, creatorClass);
Map<String, String> params = new HashMap<String, String>();
if (NewCreator.class.isAssignableFrom(NewCreator.class))
{
params.put("class", clazz.getName());
}
params.putAll(creatorParams);
params.put("scope", scope.getValue());
String name = createAnn.name();
if (name == null || name.length() == 0)
{
name = LocalUtil.getShortClassName(clazz);
}
try
{
log.info("Adding class " + clazz.getName() + " as " + name);
creatorManager.addCreator(name, creatorName, params);
}
catch (Exception ex)
{
log.error("Failed to add class as Creator: " + clazz.getName(), ex);
}
AccessControl accessControl = (AccessControl) container.getBean(AccessControl.class.getName());
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++)
{
if (methods[i].getAnnotation(RemoteMethod.class) != null)
{
accessControl.addIncludeRule(name, methods[i].getName());
Auth authAnn = methods[i].getAnnotation(Auth.class);
if (authAnn != null)
{
accessControl.addRoleRestriction(name, methods[i].getName(), authAnn.role());
}
}
}
Filters filtersAnn = clazz.getAnnotation(Filters.class);
if (filtersAnn != null)
{
Filter[] fs = filtersAnn.value();
for (int i = 0; i < fs.length; i++)
{
processFilter(fs[i], name, container);
}
}
// process single filter for convenience
else
{
Filter filterAnn = clazz.getAnnotation(Filter.class);
if (filterAnn != null)
{
processFilter(filterAnn, name, container);
}
}
}
| private void processCreate(Class<?> clazz, RemoteProxy createAnn, Container container)
{
Class<? extends Creator> creator = createAnn.creator();
String creatorClass = creator.getName();
Map<String, String> creatorParams = getParamsMap(createAnn.creatorParams());
ScriptScope scope = createAnn.scope();
CreatorManager creatorManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
String creatorName = LocalUtil.replace(creatorClass, ".", "_");
creatorManager.addCreatorType(creatorName, creatorClass);
Map<String, String> params = new HashMap<String, String>();
if (NewCreator.class.isAssignableFrom(creator))
{
params.put("class", clazz.getName());
}
params.putAll(creatorParams);
params.put("scope", scope.getValue());
String name = createAnn.name();
if (name == null || name.length() == 0)
{
name = LocalUtil.getShortClassName(clazz);
}
try
{
log.info("Adding class " + clazz.getName() + " as " + name);
creatorManager.addCreator(name, creatorName, params);
}
catch (Exception ex)
{
log.error("Failed to add class as Creator: " + clazz.getName(), ex);
}
AccessControl accessControl = (AccessControl) container.getBean(AccessControl.class.getName());
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++)
{
if (methods[i].getAnnotation(RemoteMethod.class) != null)
{
accessControl.addIncludeRule(name, methods[i].getName());
Auth authAnn = methods[i].getAnnotation(Auth.class);
if (authAnn != null)
{
accessControl.addRoleRestriction(name, methods[i].getName(), authAnn.role());
}
}
}
Filters filtersAnn = clazz.getAnnotation(Filters.class);
if (filtersAnn != null)
{
Filter[] fs = filtersAnn.value();
for (int i = 0; i < fs.length; i++)
{
processFilter(fs[i], name, container);
}
}
// process single filter for convenience
else
{
Filter filterAnn = clazz.getAnnotation(Filter.class);
if (filterAnn != null)
{
processFilter(filterAnn, name, container);
}
}
}
|
diff --git a/opensearch/jaxrs/src/main/java/com/smartitengineering/util/opensearch/jaxrs/OpenSearchDescriptorProvider.java b/opensearch/jaxrs/src/main/java/com/smartitengineering/util/opensearch/jaxrs/OpenSearchDescriptorProvider.java
index b2f222e..ad17f62 100644
--- a/opensearch/jaxrs/src/main/java/com/smartitengineering/util/opensearch/jaxrs/OpenSearchDescriptorProvider.java
+++ b/opensearch/jaxrs/src/main/java/com/smartitengineering/util/opensearch/jaxrs/OpenSearchDescriptorProvider.java
@@ -1,84 +1,85 @@
/*
* This is a utility project for wide range of applications
*
* Copyright (C) 2010 Imran M Yousuf (imyousuf@smartitengineering.com)
*
* 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 3 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., 51 Franklin Street, Fifth Floor, Boston, MA 10-1 USA
*/
package com.smartitengineering.util.opensearch.jaxrs;
import com.smartitengineering.util.opensearch.api.OpenSearchDescriptor;
import com.smartitengineering.util.opensearch.io.impl.dom.DomIOImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
/**
*
* @author imyousuf
*/
@Provider
@Produces(com.smartitengineering.util.opensearch.jaxrs.MediaType.APPLICATION_OPENSEARCHDESCRIPTION_XML)
public class OpenSearchDescriptorProvider implements MessageBodyWriter<OpenSearchDescriptor>,
MessageBodyReader<OpenSearchDescriptor> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
if (com.smartitengineering.util.opensearch.jaxrs.MediaType.APPLICATION_OPENSEARCHDESCRIPTION_XML_TYPE.equals(
mediaType) && OpenSearchDescriptor.class.isAssignableFrom(type)) {
return true;
}
return false;
}
@Override
public long getSize(OpenSearchDescriptor t,
Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
@Override
public void writeTo(OpenSearchDescriptor t,
Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
WebApplicationException {
if (isWriteable(type, genericType, annotations, mediaType)) {
DomIOImpl impl = new DomIOImpl();
impl.writeOpenSearchDescriptor(entityStream, t);
+ return;
}
throw new IOException("Write not supported!");
}
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return isWriteable(type, genericType, annotations, mediaType);
}
@Override
public OpenSearchDescriptor readFrom(Class<OpenSearchDescriptor> type, Type genericType, Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws
IOException,
WebApplicationException {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| true | true | public void writeTo(OpenSearchDescriptor t,
Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
WebApplicationException {
if (isWriteable(type, genericType, annotations, mediaType)) {
DomIOImpl impl = new DomIOImpl();
impl.writeOpenSearchDescriptor(entityStream, t);
}
throw new IOException("Write not supported!");
}
| public void writeTo(OpenSearchDescriptor t,
Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
WebApplicationException {
if (isWriteable(type, genericType, annotations, mediaType)) {
DomIOImpl impl = new DomIOImpl();
impl.writeOpenSearchDescriptor(entityStream, t);
return;
}
throw new IOException("Write not supported!");
}
|
diff --git a/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/UpdateDatabaseCommandImpl.java b/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/UpdateDatabaseCommandImpl.java
index 55b7288..8ba1630 100644
--- a/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/UpdateDatabaseCommandImpl.java
+++ b/src/main/java/net/paguo/trafshow/backend/snmp/summary/commands/impl/UpdateDatabaseCommandImpl.java
@@ -1,75 +1,76 @@
package net.paguo.trafshow.backend.snmp.summary.commands.impl;
import net.paguo.trafshow.backend.snmp.summary.commands.UpdateDatabaseCommand;
import net.paguo.trafshow.backend.snmp.summary.database.DBProxy;
import net.paguo.trafshow.backend.snmp.summary.database.DBProxyFactory;
import net.paguo.trafshow.backend.snmp.summary.model.TrafficCollector;
import net.paguo.trafshow.backend.snmp.summary.model.RouterSummaryTraffic;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Date;
/**
* @author Reyentenko
*/
public class UpdateDatabaseCommandImpl implements UpdateDatabaseCommand<TrafficCollector> {
public static final Log log = LogFactory.getLog(UpdateDatabaseCommandImpl.class);
public void doUpdate(TrafficCollector commandObject) {
log.debug("doUpdate() <<<<");
DBProxy proxy = DBProxyFactory.getDBProxy();
Connection con = null;
try{
con = proxy.getConnection();
PreparedStatement ipst = con.prepareStatement("insert into aggreg(dat, cisco, iface, t_in, t_out)" +
" values(?, ?, ?, ?, ?)");
PreparedStatement upst = con.prepareStatement("update aggreg set t_in = ?, t_out = ? where a_id = ?");
SearchTrafficDataCommandImpl search = new SearchTrafficDataCommandImpl();
boolean inserts = false;
boolean updates = false;
for (RouterSummaryTraffic o : commandObject.getTraffic().values()) {
Long id = search.findRecordId(o);
if (id != null){
upst.setLong(3, id);
upst.setLong(1, o.getTotalInput());
upst.setLong(2, o.getTotalOutput());
upst.addBatch();
updates = true;
}else{
ipst.setDate(1, new Date(o.getDate().getTime()));
ipst.setString(2, o.getRouter());
ipst.setString(3, o.getIface());
ipst.setLong(4, o.getTotalInput());
ipst.setLong(5, o.getTotalOutput());
+ ipst.addBatch();
inserts = true;
}
}
search.closeConnection();
if (inserts){
int[] i = ipst.executeBatch();
log.debug(i.length + " records inserted");
}
if (updates){
int[] i = upst.executeBatch();
log.debug(i.length + " records updated");
}
ipst.close();
upst.close();
} catch (SQLException e) {
log.error(e);
} finally {
if (con != null){
try {
con.close();
} catch (SQLException e) {
log.error(e);
}
}
}
log.debug("doUpdate() >>>>");
}
}
| true | true | public void doUpdate(TrafficCollector commandObject) {
log.debug("doUpdate() <<<<");
DBProxy proxy = DBProxyFactory.getDBProxy();
Connection con = null;
try{
con = proxy.getConnection();
PreparedStatement ipst = con.prepareStatement("insert into aggreg(dat, cisco, iface, t_in, t_out)" +
" values(?, ?, ?, ?, ?)");
PreparedStatement upst = con.prepareStatement("update aggreg set t_in = ?, t_out = ? where a_id = ?");
SearchTrafficDataCommandImpl search = new SearchTrafficDataCommandImpl();
boolean inserts = false;
boolean updates = false;
for (RouterSummaryTraffic o : commandObject.getTraffic().values()) {
Long id = search.findRecordId(o);
if (id != null){
upst.setLong(3, id);
upst.setLong(1, o.getTotalInput());
upst.setLong(2, o.getTotalOutput());
upst.addBatch();
updates = true;
}else{
ipst.setDate(1, new Date(o.getDate().getTime()));
ipst.setString(2, o.getRouter());
ipst.setString(3, o.getIface());
ipst.setLong(4, o.getTotalInput());
ipst.setLong(5, o.getTotalOutput());
inserts = true;
}
}
search.closeConnection();
if (inserts){
int[] i = ipst.executeBatch();
log.debug(i.length + " records inserted");
}
if (updates){
int[] i = upst.executeBatch();
log.debug(i.length + " records updated");
}
ipst.close();
upst.close();
} catch (SQLException e) {
log.error(e);
} finally {
if (con != null){
try {
con.close();
} catch (SQLException e) {
log.error(e);
}
}
}
log.debug("doUpdate() >>>>");
}
| public void doUpdate(TrafficCollector commandObject) {
log.debug("doUpdate() <<<<");
DBProxy proxy = DBProxyFactory.getDBProxy();
Connection con = null;
try{
con = proxy.getConnection();
PreparedStatement ipst = con.prepareStatement("insert into aggreg(dat, cisco, iface, t_in, t_out)" +
" values(?, ?, ?, ?, ?)");
PreparedStatement upst = con.prepareStatement("update aggreg set t_in = ?, t_out = ? where a_id = ?");
SearchTrafficDataCommandImpl search = new SearchTrafficDataCommandImpl();
boolean inserts = false;
boolean updates = false;
for (RouterSummaryTraffic o : commandObject.getTraffic().values()) {
Long id = search.findRecordId(o);
if (id != null){
upst.setLong(3, id);
upst.setLong(1, o.getTotalInput());
upst.setLong(2, o.getTotalOutput());
upst.addBatch();
updates = true;
}else{
ipst.setDate(1, new Date(o.getDate().getTime()));
ipst.setString(2, o.getRouter());
ipst.setString(3, o.getIface());
ipst.setLong(4, o.getTotalInput());
ipst.setLong(5, o.getTotalOutput());
ipst.addBatch();
inserts = true;
}
}
search.closeConnection();
if (inserts){
int[] i = ipst.executeBatch();
log.debug(i.length + " records inserted");
}
if (updates){
int[] i = upst.executeBatch();
log.debug(i.length + " records updated");
}
ipst.close();
upst.close();
} catch (SQLException e) {
log.error(e);
} finally {
if (con != null){
try {
con.close();
} catch (SQLException e) {
log.error(e);
}
}
}
log.debug("doUpdate() >>>>");
}
|
diff --git a/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java b/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java
index 2adccaa51..1bca4a6b4 100644
--- a/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java
+++ b/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java
@@ -1,109 +1,109 @@
package cgeo.geocaching.geopoint;
import java.util.Locale;
/**
* Formatting of Geopoint.
*/
public class GeopointFormatter
{
/**
* Predefined formats.
*/
public static enum Format {
/** Example: "10,123456 -0,123456" */
LAT_LON_DECDEGREE,
/** Example: "10.123456,-0.123456" (unlocalized) */
LAT_LON_DECDEGREE_COMMA,
/** Example: "N 10° 12,345 W 5° 12,345" */
LAT_LON_DECMINUTE,
/** Example: "N 10° 12' 34" W 5° 12' 34"" */
LAT_LON_DECSECOND,
/** Example: "-0.123456" (unlocalized latitude) */
LAT_DECDEGREE_RAW,
/** Example: "N 10° 12,345" */
LAT_DECMINUTE,
/** Example: "N 10 12,345" */
LAT_DECMINUTE_RAW,
/** Example: "-0.123456" (unlocalized longitude) */
LON_DECDEGREE_RAW,
/** Example: "W 5° 12,345" */
LON_DECMINUTE,
/** Example: "W 5 12,345" */
LON_DECMINUTE_RAW;
}
/**
* Formats a Geopoint.
*
* @param gp
* the Geopoint to format
* @param format
* one of the predefined formats
* @return the formatted coordinates
*/
public static String format(final Format format, final Geopoint gp)
{
final double latSigned = gp.getLatitude();
final double lonSigned = gp.getLongitude();
final double lat = Math.abs(latSigned);
final double lon = Math.abs(lonSigned);
final double latFloor = Math.floor(lat);
final double lonFloor = Math.floor(lon);
final double latMin = (lat - latFloor) * 60;
final double lonMin = (lon - lonFloor) * 60;
final double latMinFloor = Math.floor(latMin);
final double lonMinFloor = Math.floor(lonMin);
final double latSec = (latMin - latMinFloor) * 60;
final double lonSec = (lonMin - lonMinFloor) * 60;
final char latDir = latSigned < 0 ? 'S' : 'N';
final char lonDir = lonSigned < 0 ? 'W' : 'E';
switch (format) {
case LAT_LON_DECDEGREE:
return String.format("%.6f %.6f", latSigned, lonSigned);
case LAT_LON_DECDEGREE_COMMA:
return String.format((Locale) null, "%.6f,%.6f", latSigned, lonSigned);
case LAT_LON_DECMINUTE:
- return String.format("%c %02.0f° %.3f %c %03.0f° %.3f",
+ return String.format("%c %02.0f° %06.3f %c %03.0f° %06.3f",
latDir, latFloor, latMin, lonDir, lonFloor, lonMin);
case LAT_LON_DECSECOND:
- return String.format("%c %02.0f° %02.0f' %.3f\" %c %03.0f° %02.0f' %.3f\"",
+ return String.format("%c %02.0f° %02.0f' %06.3f\" %c %03.0f° %02.0f' %06.3f\"",
latDir, latFloor, latMinFloor, latSec, lonDir, lonFloor, lonMinFloor, lonSec);
case LAT_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", latSigned);
case LAT_DECMINUTE:
- return String.format("%c %02.0f° %.3f", latDir, latFloor, latMin);
+ return String.format("%c %02.0f° %06.3f", latDir, latFloor, latMin);
case LAT_DECMINUTE_RAW:
- return String.format("%c %02.0f %.3f", latDir, latFloor, latMin);
+ return String.format("%c %02.0f %06.3f", latDir, latFloor, latMin);
case LON_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", lonSigned);
case LON_DECMINUTE:
- return String.format("%c %03.0f° %.3f", lonDir, lonFloor, lonMin);
+ return String.format("%c %03.0f° %06.3f", lonDir, lonFloor, lonMin);
case LON_DECMINUTE_RAW:
- return String.format("%c %03.0f %.3f", lonDir, lonFloor, lonMin);
+ return String.format("%c %03.0f %06.3f", lonDir, lonFloor, lonMin);
}
// Keep the compiler happy even though it cannot happen
return null;
}
}
| false | true | public static String format(final Format format, final Geopoint gp)
{
final double latSigned = gp.getLatitude();
final double lonSigned = gp.getLongitude();
final double lat = Math.abs(latSigned);
final double lon = Math.abs(lonSigned);
final double latFloor = Math.floor(lat);
final double lonFloor = Math.floor(lon);
final double latMin = (lat - latFloor) * 60;
final double lonMin = (lon - lonFloor) * 60;
final double latMinFloor = Math.floor(latMin);
final double lonMinFloor = Math.floor(lonMin);
final double latSec = (latMin - latMinFloor) * 60;
final double lonSec = (lonMin - lonMinFloor) * 60;
final char latDir = latSigned < 0 ? 'S' : 'N';
final char lonDir = lonSigned < 0 ? 'W' : 'E';
switch (format) {
case LAT_LON_DECDEGREE:
return String.format("%.6f %.6f", latSigned, lonSigned);
case LAT_LON_DECDEGREE_COMMA:
return String.format((Locale) null, "%.6f,%.6f", latSigned, lonSigned);
case LAT_LON_DECMINUTE:
return String.format("%c %02.0f° %.3f %c %03.0f° %.3f",
latDir, latFloor, latMin, lonDir, lonFloor, lonMin);
case LAT_LON_DECSECOND:
return String.format("%c %02.0f° %02.0f' %.3f\" %c %03.0f° %02.0f' %.3f\"",
latDir, latFloor, latMinFloor, latSec, lonDir, lonFloor, lonMinFloor, lonSec);
case LAT_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", latSigned);
case LAT_DECMINUTE:
return String.format("%c %02.0f° %.3f", latDir, latFloor, latMin);
case LAT_DECMINUTE_RAW:
return String.format("%c %02.0f %.3f", latDir, latFloor, latMin);
case LON_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", lonSigned);
case LON_DECMINUTE:
return String.format("%c %03.0f° %.3f", lonDir, lonFloor, lonMin);
case LON_DECMINUTE_RAW:
return String.format("%c %03.0f %.3f", lonDir, lonFloor, lonMin);
}
// Keep the compiler happy even though it cannot happen
return null;
}
| public static String format(final Format format, final Geopoint gp)
{
final double latSigned = gp.getLatitude();
final double lonSigned = gp.getLongitude();
final double lat = Math.abs(latSigned);
final double lon = Math.abs(lonSigned);
final double latFloor = Math.floor(lat);
final double lonFloor = Math.floor(lon);
final double latMin = (lat - latFloor) * 60;
final double lonMin = (lon - lonFloor) * 60;
final double latMinFloor = Math.floor(latMin);
final double lonMinFloor = Math.floor(lonMin);
final double latSec = (latMin - latMinFloor) * 60;
final double lonSec = (lonMin - lonMinFloor) * 60;
final char latDir = latSigned < 0 ? 'S' : 'N';
final char lonDir = lonSigned < 0 ? 'W' : 'E';
switch (format) {
case LAT_LON_DECDEGREE:
return String.format("%.6f %.6f", latSigned, lonSigned);
case LAT_LON_DECDEGREE_COMMA:
return String.format((Locale) null, "%.6f,%.6f", latSigned, lonSigned);
case LAT_LON_DECMINUTE:
return String.format("%c %02.0f° %06.3f %c %03.0f° %06.3f",
latDir, latFloor, latMin, lonDir, lonFloor, lonMin);
case LAT_LON_DECSECOND:
return String.format("%c %02.0f° %02.0f' %06.3f\" %c %03.0f° %02.0f' %06.3f\"",
latDir, latFloor, latMinFloor, latSec, lonDir, lonFloor, lonMinFloor, lonSec);
case LAT_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", latSigned);
case LAT_DECMINUTE:
return String.format("%c %02.0f° %06.3f", latDir, latFloor, latMin);
case LAT_DECMINUTE_RAW:
return String.format("%c %02.0f %06.3f", latDir, latFloor, latMin);
case LON_DECDEGREE_RAW:
return String.format((Locale) null, "%.6f", lonSigned);
case LON_DECMINUTE:
return String.format("%c %03.0f° %06.3f", lonDir, lonFloor, lonMin);
case LON_DECMINUTE_RAW:
return String.format("%c %03.0f %06.3f", lonDir, lonFloor, lonMin);
}
// Keep the compiler happy even though it cannot happen
return null;
}
|
diff --git a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxComponentEventRequestHandler.java b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxComponentEventRequestHandler.java
index 7845ca6a9..1d98da722 100644
--- a/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxComponentEventRequestHandler.java
+++ b/tapestry-core/src/main/java/org/apache/tapestry5/internal/services/AjaxComponentEventRequestHandler.java
@@ -1,138 +1,138 @@
// Copyright 2007, 2008, 2010 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry5.internal.services;
import org.apache.tapestry5.ContentType;
import org.apache.tapestry5.TrackableComponentEventCallback;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.internal.structure.ComponentPageElement;
import org.apache.tapestry5.internal.structure.Page;
import org.apache.tapestry5.internal.util.Holder;
import org.apache.tapestry5.ioc.internal.util.TapestryException;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.*;
import java.io.IOException;
/**
* Similar to {@link ComponentEventRequestHandlerImpl}, but built around the Ajax request cycle, where the action
* request sends back an immediate JSON response containing the new content.
*/
@SuppressWarnings("unchecked")
public class AjaxComponentEventRequestHandler implements ComponentEventRequestHandler
{
private final RequestPageCache cache;
private final Request request;
private final PageRenderQueue queue;
private final ComponentEventResultProcessor resultProcessor;
private final PageContentTypeAnalyzer pageContentTypeAnalyzer;
private final Environment environment;
private final AjaxPartialResponseRenderer partialRenderer;
private final PageActivator pageActivator;
public AjaxComponentEventRequestHandler(RequestPageCache cache, Request request, PageRenderQueue queue, @Ajax
ComponentEventResultProcessor resultProcessor, PageActivator pageActivator,
PageContentTypeAnalyzer pageContentTypeAnalyzer, Environment environment,
AjaxPartialResponseRenderer partialRenderer)
{
this.cache = cache;
this.queue = queue;
this.resultProcessor = resultProcessor;
this.pageActivator = pageActivator;
this.pageContentTypeAnalyzer = pageContentTypeAnalyzer;
this.request = request;
this.environment = environment;
this.partialRenderer = partialRenderer;
}
public void handle(ComponentEventRequestParameters parameters) throws IOException
{
Page activePage = cache.get(parameters.getActivePageName());
final Holder<Boolean> resultProcessorInvoked = Holder.create();
resultProcessorInvoked.put(false);
ComponentEventResultProcessor interceptor = new ComponentEventResultProcessor()
{
public void processResultValue(Object value) throws IOException
{
resultProcessorInvoked.put(true);
resultProcessor.processResultValue(value);
}
};
// If we end up doing a partial render, the page render queue service needs to know the
// page that will be rendered (for logging purposes, if nothing else).
queue.setRenderingPage(activePage);
if (pageActivator.activatePage(activePage.getRootElement().getComponentResources(), parameters
.getPageActivationContext(), interceptor))
return;
ContentType contentType = pageContentTypeAnalyzer.findContentType(activePage);
request.setAttribute(InternalConstants.CONTENT_TYPE_ATTRIBUTE_NAME, contentType);
Page containerPage = cache.get(parameters.getContainingPageName());
ComponentPageElement element = containerPage.getComponentElementByNestedId(parameters.getNestedComponentId());
// In many cases, the triggered element is a Form that needs to be able to
// pass its event handler return values to the correct result processor.
// This is certainly the case for forms.
TrackableComponentEventCallback callback = new ComponentResultProcessorWrapper(interceptor);
environment.push(ComponentEventResultProcessor.class, interceptor);
environment.push(TrackableComponentEventCallback.class, callback);
boolean handled = element
.triggerContextEvent(parameters.getEventType(), parameters.getEventContext(), callback);
if (!handled)
throw new TapestryException(ServicesMessages.eventNotHandled(element, parameters.getEventType()), element,
null);
environment.pop(TrackableComponentEventCallback.class);
environment.pop(ComponentEventResultProcessor.class);
- // If the result processor was passed a value, then it will already have rendered. Otherise it was not passed a value,
+ // If the result processor was passed a value, then it will already have rendered. Otherwise it was not passed a value,
// but it's still possible that we still want to do a partial page render ... if filters were added to the render queue.
// In that event, run the partial page render now and return.
if ((!resultProcessorInvoked.get()) && queue.isPartialRenderInitialized())
{
partialRenderer.renderPartialPageMarkup();
return;
}
// Send an empty JSON reply if no value was returned from the component event handler method.
// This is the typical behavior when an Ajax component event handler returns null.
JSONObject reply = new JSONObject();
resultProcessor.processResultValue(reply);
}
}
| true | true | public void handle(ComponentEventRequestParameters parameters) throws IOException
{
Page activePage = cache.get(parameters.getActivePageName());
final Holder<Boolean> resultProcessorInvoked = Holder.create();
resultProcessorInvoked.put(false);
ComponentEventResultProcessor interceptor = new ComponentEventResultProcessor()
{
public void processResultValue(Object value) throws IOException
{
resultProcessorInvoked.put(true);
resultProcessor.processResultValue(value);
}
};
// If we end up doing a partial render, the page render queue service needs to know the
// page that will be rendered (for logging purposes, if nothing else).
queue.setRenderingPage(activePage);
if (pageActivator.activatePage(activePage.getRootElement().getComponentResources(), parameters
.getPageActivationContext(), interceptor))
return;
ContentType contentType = pageContentTypeAnalyzer.findContentType(activePage);
request.setAttribute(InternalConstants.CONTENT_TYPE_ATTRIBUTE_NAME, contentType);
Page containerPage = cache.get(parameters.getContainingPageName());
ComponentPageElement element = containerPage.getComponentElementByNestedId(parameters.getNestedComponentId());
// In many cases, the triggered element is a Form that needs to be able to
// pass its event handler return values to the correct result processor.
// This is certainly the case for forms.
TrackableComponentEventCallback callback = new ComponentResultProcessorWrapper(interceptor);
environment.push(ComponentEventResultProcessor.class, interceptor);
environment.push(TrackableComponentEventCallback.class, callback);
boolean handled = element
.triggerContextEvent(parameters.getEventType(), parameters.getEventContext(), callback);
if (!handled)
throw new TapestryException(ServicesMessages.eventNotHandled(element, parameters.getEventType()), element,
null);
environment.pop(TrackableComponentEventCallback.class);
environment.pop(ComponentEventResultProcessor.class);
// If the result processor was passed a value, then it will already have rendered. Otherise it was not passed a value,
// but it's still possible that we still want to do a partial page render ... if filters were added to the render queue.
// In that event, run the partial page render now and return.
if ((!resultProcessorInvoked.get()) && queue.isPartialRenderInitialized())
{
partialRenderer.renderPartialPageMarkup();
return;
}
// Send an empty JSON reply if no value was returned from the component event handler method.
// This is the typical behavior when an Ajax component event handler returns null.
JSONObject reply = new JSONObject();
resultProcessor.processResultValue(reply);
}
| public void handle(ComponentEventRequestParameters parameters) throws IOException
{
Page activePage = cache.get(parameters.getActivePageName());
final Holder<Boolean> resultProcessorInvoked = Holder.create();
resultProcessorInvoked.put(false);
ComponentEventResultProcessor interceptor = new ComponentEventResultProcessor()
{
public void processResultValue(Object value) throws IOException
{
resultProcessorInvoked.put(true);
resultProcessor.processResultValue(value);
}
};
// If we end up doing a partial render, the page render queue service needs to know the
// page that will be rendered (for logging purposes, if nothing else).
queue.setRenderingPage(activePage);
if (pageActivator.activatePage(activePage.getRootElement().getComponentResources(), parameters
.getPageActivationContext(), interceptor))
return;
ContentType contentType = pageContentTypeAnalyzer.findContentType(activePage);
request.setAttribute(InternalConstants.CONTENT_TYPE_ATTRIBUTE_NAME, contentType);
Page containerPage = cache.get(parameters.getContainingPageName());
ComponentPageElement element = containerPage.getComponentElementByNestedId(parameters.getNestedComponentId());
// In many cases, the triggered element is a Form that needs to be able to
// pass its event handler return values to the correct result processor.
// This is certainly the case for forms.
TrackableComponentEventCallback callback = new ComponentResultProcessorWrapper(interceptor);
environment.push(ComponentEventResultProcessor.class, interceptor);
environment.push(TrackableComponentEventCallback.class, callback);
boolean handled = element
.triggerContextEvent(parameters.getEventType(), parameters.getEventContext(), callback);
if (!handled)
throw new TapestryException(ServicesMessages.eventNotHandled(element, parameters.getEventType()), element,
null);
environment.pop(TrackableComponentEventCallback.class);
environment.pop(ComponentEventResultProcessor.class);
// If the result processor was passed a value, then it will already have rendered. Otherwise it was not passed a value,
// but it's still possible that we still want to do a partial page render ... if filters were added to the render queue.
// In that event, run the partial page render now and return.
if ((!resultProcessorInvoked.get()) && queue.isPartialRenderInitialized())
{
partialRenderer.renderPartialPageMarkup();
return;
}
// Send an empty JSON reply if no value was returned from the component event handler method.
// This is the typical behavior when an Ajax component event handler returns null.
JSONObject reply = new JSONObject();
resultProcessor.processResultValue(reply);
}
|
diff --git a/src/java/fedora/server/storage/METSDOSerializer.java b/src/java/fedora/server/storage/METSDOSerializer.java
index a226c4ee9..3c6ba1895 100755
--- a/src/java/fedora/server/storage/METSDOSerializer.java
+++ b/src/java/fedora/server/storage/METSDOSerializer.java
@@ -1,636 +1,636 @@
package fedora.server.storage;
import fedora.server.errors.ObjectIntegrityException;
import fedora.server.errors.StreamIOException;
import fedora.server.errors.StreamWriteException;
import fedora.server.storage.types.AuditRecord;
import fedora.server.storage.types.DigitalObject;
import fedora.server.storage.types.Datastream;
import fedora.server.storage.types.DatastreamContent;
import fedora.server.storage.types.DatastreamReferencedContent;
import fedora.server.storage.types.DatastreamXMLMetadata;
import fedora.server.storage.types.Disseminator;
import fedora.server.storage.types.DSBinding;
import fedora.server.utilities.DateUtility;
import fedora.server.utilities.StreamUtility;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A DigitalObject serializer that outputs to a format similar to METS XML v1_1.
* <p></p>
* In order to support the following features of Fedora, we don't strictly
* adhere to the METS schema.
* <p></p>
* <h3>Inline XML Datastream Versioning for Descriptive Metadata</h3>
* <dir>
* All datastreams in a Fedora object can be versioned. When the METS format
* is used to encode Fedora objects, we go outside the METS schema because
* it currently has no provision for versioning inline XML datastreams that
* are descriptive metadata. This exception to our use of the METS schema
* is described below.
* <p></p>
* The METS schema doesn't allow for the GROUPID attribute on amdSec or dmdSec
* elements. Now, because of the way we are encoding multi-versioned
* _administrative_ metadata[1], we are ok on this front. But when it comes
* to _descriptive_ metadata, we are using a GROUPID attribute[2] that isn't
* METS schema-valid[3,4].
* <p></p>
* [1] The amdSec element allows for a set of metadata (where each is of type
* techMD, sourceMD, rightsMD, or digiprovMD). We put all versions of one
* administrative datastream into a single amdSec, where the ID is the
* datastream id, and each version of a specific datastream member is indicated
* by it's surrounding techMD, sourceMD, rightsMD, or digiprovMD element's ID
* attribute.
* <p></p>
* [2] The dmdSec element may contain only one chunk of METS-element-surrounded
* metadata, so we create a separate dmdSec element for each version of a
* particular datastream. Since they are not all grouped together in the METS
* document, we group them via a "GROUPID" attribute in the dmdSec
* <p></p>
* [3] The METS schema: (As of 2002-10-13 the version at this URL is 1.1)
* <a href="http://www.loc.gov/standards/mets/mets.xsd">http://www.loc.gov/standards/mets/mets.xsd</a>
* <p></p>
* [4] The Fedora tech. spec., v1.0, section 2.4, paragraph 2
* <a href="http://www.fedora.info/documents/master-spec.html#_Toc11835694">http://www.fedora.info/documents/master-spec.html#_Toc11835694</a>
* </dir>
* <p></p>
* <h3>Describing Content Datastreams with Inline XML Metadata</h3>
* <dir>
* Fedora supports arbitrary content datastreams that can either be repository-
* managed (internal to the repository) or referenced
* (external to the repository). These datastreams can additionally be
* described inside the object by one or more inline XML metadata datastreams.
* <p></p>
* We represent part of this "is described by" relationship in METS via the
* ADMID attribute in the file element for each content datastream. This
* covers a content stream's relationship to administrative metadata, but not
* descriptive metadata. We use an additional attribute in this element, DMDID,
* to similarly represent a content stream's relationship with descriptive
* metadata. Used in this location in the METS document, the DMDID attribute
* is not METS schema-valid.
*
* </dir>
*
* @author cwilper@cs.cornell.edu
*/
public class METSDOSerializer
implements DOSerializer {
// test object says this.. but it should be
// http://www.fedora.info/definitions/1/0/auditing/
private final static String FEDORA_AUDIT_NAMESPACE_URI=
"http://fedora.comm.nsdlib.org/audit";
/** The namespace for XLINK */
private final static String METS_XLINK_NAMESPACE="http://www.w3.org/TR/xlink";
// Mets says the above, but the spec at http://www.w3.org/TR/xlink/
// says it's http://www.w3.org/1999/xlink
private final static String REAL_XLINK_NAMESPACE="http://www.w3.org/1999/xlink";
private String m_xlinkPrefix;
private String m_characterEncoding;
public METSDOSerializer() {
System.out.println("Mets do serializer constructed.");
}
/**
* Constructs a METS serializer.
*
* @param characterEncoding The character encoding to use when sending
* the objects to OutputStreams.
* @throw UnsupportedEncodingException If the provided encoding is
* not supported or recognized.
*/
public METSDOSerializer(String characterEncoding)
throws UnsupportedEncodingException {
m_characterEncoding=characterEncoding;
StringBuffer buf=new StringBuffer();
buf.append("test");
byte[] temp=buf.toString().getBytes(m_characterEncoding);
}
public String getEncoding() {
return m_characterEncoding;
}
// subclasses should override this
public static String getVersion() {
return "1.0";
}
/**
* Serializes the given Fedora object to an OutputStream.
*/
public void serialize(DigitalObject obj, OutputStream out, String encoding)
throws ObjectIntegrityException, StreamIOException,
UnsupportedEncodingException {
m_characterEncoding=encoding;
StringBuffer buf1=new StringBuffer();
buf1.append("test");
byte[] temp=buf1.toString().getBytes(m_characterEncoding);
try {
StringBuffer buf=new StringBuffer();
m_xlinkPrefix="xlink"; // default if can't figger it
//
// Serialize root element and header
//
buf.append("<?xml version=\"1.0\" ");
buf.append("encoding=\"");
buf.append(m_characterEncoding);
buf.append("\" ?>\n");
buf.append("<mets xmlns=\"http://www.loc.gov/METS/\"\n");
Iterator nsIter=obj.getNamespaceMapping().keySet().iterator();
boolean didXlink=false;
while (nsIter.hasNext()) {
String uri=(String) nsIter.next();
String prefix=(String) obj.getNamespaceMapping().get(uri);
if ( (uri.equals(METS_XLINK_NAMESPACE))
|| (uri.equals(REAL_XLINK_NAMESPACE)) ) {
m_xlinkPrefix=prefix;
didXlink=true;
}
buf.append(" xmlns:");
buf.append(prefix);
buf.append("=\"");
buf.append(uri);
buf.append("\"\n");
}
if (!didXlink) {
buf.append(" xmlns:xlink=\"" + REAL_XLINK_NAMESPACE + "\"\n");
}
buf.append(" OBJID=\"");
buf.append(obj.getPid());
buf.append("\"\n LABEL=\"");
StreamUtility.enc(obj.getLabel(), buf);
buf.append("\"\n TYPE=\"");
if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BDEF_OBJECT) {
buf.append("FedoraBDefObject");
} else if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BMECH_OBJECT) {
buf.append("FedoraBMechObject");
} else {
buf.append("FedoraObject");
}
buf.append("\"\n PROFILE=\"");
StreamUtility.enc(obj.getContentModelId(), buf);
buf.append("\">\n <metsHdr CREATEDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getCreateDate()));
buf.append("\" LASTMODDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getLastModDate()));
buf.append("\" RECORDSTATUS=\"");
buf.append(obj.getState());
buf.append("\">\n <!-- This info can't be set via API-M. If it existed, it was ignored during import -->\n");
buf.append(" </metsHdr>\n");
//
// Serialize Audit Records
//
if (obj.getAuditRecords().size()>0) {
buf.append(" <amdSec ID=\"FEDORA-AUDITTRAIL\">\n");
String auditPrefix=(String) obj.getNamespaceMapping().get(FEDORA_AUDIT_NAMESPACE_URI);
Iterator iter=obj.getAuditRecords().iterator();
while (iter.hasNext()) {
AuditRecord audit=(AuditRecord) iter.next();
buf.append(" <digiprovMD ID=\"");
buf.append(audit.id);
buf.append("\" CREATED=\"");
String createDate=DateUtility.convertDateToString(audit.date);
buf.append(createDate);
buf.append("\" STATUS=\"A\">\n"); // status is always A
buf.append(" <mdWrap MIMETYPE=\"text/xml\" MDTYPE=\"OTHER\" LABEL=\"Fedora Object Audit Trail Record\">\n");
buf.append(" <xmlData>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":process type=\"");
StreamUtility.enc(audit.processType, buf);
buf.append("\"/>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":action>");
StreamUtility.enc(audit.action, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":action>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":responsibility>");
StreamUtility.enc(audit.responsibility, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":responsibility>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":date>");
buf.append(createDate);
buf.append("</");
buf.append(auditPrefix);
buf.append(":date>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":justification>");
StreamUtility.enc(audit.justification, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":justification>\n");
buf.append(" </");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" </xmlData>\n");
buf.append(" </mdWrap>\n");
buf.append(" </digiprovMD>\n");
}
buf.append(" </amdSec>\n");
}
//
// Serialize Datastreams
//
Iterator idIter=obj.datastreamIdIterator();
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one with this id,
// first decide if its an inline xml
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp==Datastream.XML_METADATA) {
if (ds.DSControlGrp.equalsIgnoreCase("X")) {
//
// Serialize inline XML datastream
// - dmdSec || amdSec?
//
DatastreamXMLMetadata mds=(DatastreamXMLMetadata) ds;
if (mds.DSMDClass==DatastreamXMLMetadata.DESCRIPTIVE) {
//
// Descriptive inline XML Metadata
//
// <!-- For each version with this dsId -->
// <dmdSec GROUPID=dsId
// ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </dmdSec>
//
Iterator dmdIter=obj.datastreams(id).iterator();
while (dmdIter.hasNext()) {
mds=(DatastreamXMLMetadata) dmdIter.next();
buf.append(" <dmdSec ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" GROUPID=\"");
buf.append(mds.DatastreamID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </dmdsec>\n");
}
} else {
//
// Administrative inline XML Metadata
//
// Technical ($mdClass$=techMD)
// Source ($mdClass$=sourceMD)
// Rights ($mdClass$=rightsMD)
// Digital Provenance ($mdClass$=digiprovMD)
//
// <amdSec ID=dsId>
// <!-- For each version with this dsId -->
// <$mdClass$ ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </techMd>
// </amdSec>
//
String mdClass;
if (mds.DSMDClass==DatastreamXMLMetadata.TECHNICAL) {
mdClass="techMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.SOURCE) {
mdClass="sourceMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.RIGHTS) {
mdClass="rightsMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.DIGIPROV) {
mdClass="digiprovMD";
} else {
throw new ObjectIntegrityException(
"Datastreams must have a class");
}
buf.append(" <amdSec ID=\"");
buf.append(mds.DatastreamID);
buf.append("\">\n");
Iterator amdIter=obj.datastreams(id).iterator();
while (amdIter.hasNext()) {
mds=(DatastreamXMLMetadata) amdIter.next();
buf.append(" <");
buf.append(mdClass);
buf.append(" ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </");
buf.append(mdClass);
buf.append(">\n");
}
buf.append(" </amdSec>\n");
}
}
}
// Now iterate through datastreams a second time, doing the fileSec
idIter=obj.datastreamIdIterator();
boolean didFileSec=false;
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one in the version group with this id, check its type
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp!=Datastream.XML_METADATA) { // must be ext ref or managed (so needs mets fileSec)
if (!ds.DSControlGrp.equalsIgnoreCase("X")) { // must be ext ref or managed (so needs mets fileSec)
//
// Externally-referenced or managed datastreams (fileSec)
//
if (!didFileSec) {
buf.append(" <fileSec>\n");
buf.append(" <fileGrp ID=\"DATASTREAMS\">\n");
didFileSec=true;
}
buf.append(" <fileGrp ID=\"");
buf.append(ds.DatastreamID);
buf.append("\">\n");
Iterator contentIter=obj.datastreams(id).iterator();
while (contentIter.hasNext()) {
DatastreamContent dsc=(DatastreamContent) contentIter.next();
buf.append(" <file ID=\"");
buf.append(dsc.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(dsc.DSCreateDT));
buf.append("\" MIMETYPE=\"");
buf.append(dsc.DSMIME);
buf.append("\" STATUS=\"");
buf.append(dsc.DSState);
buf.append("\" SIZE=\"" + dsc.DSSize);
buf.append("\" ADMID=\"");
Iterator admIdIter=getIds(obj, dsc, true).iterator();
int admNum=0;
while (admIdIter.hasNext()) {
String admId=(String) admIdIter.next();
if (admNum>0) {
buf.append(' ');
}
buf.append(admId);
admNum++;
}
buf.append("\" DMDID=\"");
Iterator dmdIdIter=getIds(obj, dsc, false).iterator();
int dmdNum=0;
while (dmdIdIter.hasNext()) {
String dmdId=(String) dmdIdIter.next();
if (dmdNum>0) {
buf.append(' ');
}
buf.append(dmdId);
dmdNum++;
}
//
// other attrs
//
buf.append("\">\n");
//if (dsc.DSControlGrp==Datastream.EXTERNAL_REF) {
// External (E) or External-Protected (P) Datastreams
if (dsc.DSControlGrp.equalsIgnoreCase("E") ||
dsc.DSControlGrp.equalsIgnoreCase("P")) {
DatastreamReferencedContent dsec=(DatastreamReferencedContent) dsc;
// xlink:title, xlink:href
buf.append(" <FLocat ");
buf.append(m_xlinkPrefix);
buf.append(":title=\"");
buf.append(dsec.DSLabel);
buf.append("\" ");
buf.append(m_xlinkPrefix);
buf.append(":href=\"");
if (dsec.DSLocation==null) {
throw new ObjectIntegrityException("Externally referenced content (ID=" + dsc.DSVersionID + ") must have a URL defined.");
}
buf.append(dsec.DSLocation.toString());
- buf.append("\">\n");
+ buf.append("\"/>\n");
} else {
// FContent=base64 encoded
}
buf.append(" </file>\n");
}
buf.append(" </fileGrp>\n");
}
}
if (didFileSec) {
buf.append(" </fileGrp>\n");
buf.append(" </fileSec>\n");
}
// Now do structmap...one for each disseminator
Iterator dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <structMap ID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" TYPE=\"fedora:dsBindingMap\">\n");
buf.append(" <div TYPE=\"");
buf.append(diss.bMechID);
buf.append("\" LABEL=\"");
buf.append(diss.dsBindMap.dsBindMapLabel);
buf.append("\">\n");
// iterate through diss.dsBindMap.dsBindings[]
DSBinding[] bindings=diss.dsBindMap.dsBindings;
for (int i=0; i<bindings.length; i++) {
buf.append(" <div TYPE=\"");
buf.append(bindings[i].bindKeyName);
buf.append("\" LABEL=\"");
buf.append(bindings[i].bindLabel);
buf.append("\" ORDER=\"");
buf.append(bindings[i].seqNo);
buf.append("\">\n");
buf.append(" <fptr FILEID=\"");
buf.append(bindings[i].datastreamID);
buf.append("\"/>\n");
buf.append(" </div>\n");
}
buf.append(" </div>\n");
buf.append(" </structMap>\n");
}
}
// Last, do disseminators
dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <behaviorSec ID=\"");
buf.append(diss.dissVersionID);
buf.append("\" STRUCTID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" BTYPE=\"");
buf.append(diss.bDefID);
buf.append("\" CREATED=\"");
String strDate=DateUtility.convertDateToString(diss.dissCreateDT);
buf.append(strDate);
buf.append("\" LABEL=\"");
buf.append(diss.dissLabel);
buf.append("\" GROUPID=\"");
buf.append(diss.dissID);
buf.append("\" STATUS=\"");
buf.append(diss.dissState);
buf.append("\">\n");
buf.append(" <interfaceDef LABEL=\"");
buf.append(diss.bDefLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bDefID);
buf.append("\"/>\n");
buf.append(" <mechanism LABEL=\"");
buf.append(diss.bMechLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bMechID);
buf.append("\"/>\n");
buf.append(" </behaviorSec>\n");
}
}
/*
<behaviorSec ID="DISS1.0" STRUCTID="S1" BTYPE="test:1" CREATED="2002-05-20T06:32:00" LABEL="UVA Std Image Behaviors" GROUPID="DISS1" STATUS="">
<interfaceDef LABEL="UVA Std Image Behavior Definition" LOCTYPE="URN" xlink:href="test:1"/>
<mechanism LABEL="UVA Std Image Behavior Mechanism" LOCTYPE="URN" xlink:href="test:2"/>
</behaviorSec>
*/
//
// Serialization Complete
//
buf.append("</mets>");
out.write(buf.toString().getBytes(m_characterEncoding));
out.flush();
} catch (UnsupportedEncodingException uee) {
throw uee;
} catch (IOException ioe) {
throw new StreamWriteException("Problem writing to outputstream "
+ "while serializing to mets: " + ioe.getMessage());
} finally {
try {
out.close();
} catch (IOException ioe2) {
throw new StreamIOException("Problem closing outputstream "
+ "after attempting to serialize to mets: "
+ ioe2.getMessage());
}
}
if (1==2) throw new ObjectIntegrityException("bad object");
}
/**
* Gets administrative or descriptive metadata ids for a datastream.
*/
private List getIds(DigitalObject obj, DatastreamContent content, boolean adm) {
ArrayList ret;
if (adm) {
ret=new ArrayList(content.auditRecordIdList());
} else {
ret=new ArrayList();
}
try {
Iterator mdIdIter=content.metadataIdList().iterator();
while (mdIdIter.hasNext()) {
String mdId=(String) mdIdIter.next();
List datastreams=obj.datastreams(mdId);
if (datastreams!=null) {
Datastream ds=(Datastream) datastreams.get(0); // this throws ArrayIndexOutOfBoundsException on the sample watermark img.. why?
if (ds!=null) {
//if (ds.DSControlGrp==Datastream.XML_METADATA) {
if (ds.DSControlGrp.equalsIgnoreCase("X")) {
DatastreamXMLMetadata mds=(DatastreamXMLMetadata) ds;
if (mds.DSMDClass == DatastreamXMLMetadata.DESCRIPTIVE) {
if (!adm) {
ret.add(mdId);
}
}
else {
if (adm) {
ret.add(mdId);
}
}
}
}
}
}
} catch (Throwable th) {
// ignore so test works..bleh
}
return ret;
}
private void mdWrap(DatastreamXMLMetadata mds, StringBuffer buf)
throws StreamIOException {
buf.append(" <mdWrap MIMETYPE=\"");
buf.append(mds.DSMIME);
buf.append("\" MDTYPE=\"");
buf.append(mds.DSInfoType);
buf.append("\" LABEL=\"");
StreamUtility.enc(mds.DSLabel, buf);
buf.append("\">\n");
buf.append(" <xmlData>");
InputStream in=mds.getContentStream();
try {
byte[] byteBuf = new byte[4096];
int len;
while ( ( len = in.read( byteBuf ) ) != -1 ) {
buf.append(new String(byteBuf, 0, len, m_characterEncoding));
}
} catch (IOException ioe) {
throw new StreamIOException("Error reading from datastream");
} finally {
try {
in.close();
} catch (IOException closeProb) {
throw new StreamIOException("Error closing read stream");
// ignore problems while closing
}
}
buf.append(" </xmlData>\n");
buf.append(" </mdWrap>\n");
}
public boolean equals(Object o) {
if (this==o) { return true; }
try {
return equals((METSDOSerializer) o);
} catch (ClassCastException cce) {
return false;
}
}
public boolean equals(METSDOSerializer o) {
return (o.getEncoding().equals(getEncoding())
&& o.getVersion().equals(getVersion()));
}
}
| true | true | public void serialize(DigitalObject obj, OutputStream out, String encoding)
throws ObjectIntegrityException, StreamIOException,
UnsupportedEncodingException {
m_characterEncoding=encoding;
StringBuffer buf1=new StringBuffer();
buf1.append("test");
byte[] temp=buf1.toString().getBytes(m_characterEncoding);
try {
StringBuffer buf=new StringBuffer();
m_xlinkPrefix="xlink"; // default if can't figger it
//
// Serialize root element and header
//
buf.append("<?xml version=\"1.0\" ");
buf.append("encoding=\"");
buf.append(m_characterEncoding);
buf.append("\" ?>\n");
buf.append("<mets xmlns=\"http://www.loc.gov/METS/\"\n");
Iterator nsIter=obj.getNamespaceMapping().keySet().iterator();
boolean didXlink=false;
while (nsIter.hasNext()) {
String uri=(String) nsIter.next();
String prefix=(String) obj.getNamespaceMapping().get(uri);
if ( (uri.equals(METS_XLINK_NAMESPACE))
|| (uri.equals(REAL_XLINK_NAMESPACE)) ) {
m_xlinkPrefix=prefix;
didXlink=true;
}
buf.append(" xmlns:");
buf.append(prefix);
buf.append("=\"");
buf.append(uri);
buf.append("\"\n");
}
if (!didXlink) {
buf.append(" xmlns:xlink=\"" + REAL_XLINK_NAMESPACE + "\"\n");
}
buf.append(" OBJID=\"");
buf.append(obj.getPid());
buf.append("\"\n LABEL=\"");
StreamUtility.enc(obj.getLabel(), buf);
buf.append("\"\n TYPE=\"");
if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BDEF_OBJECT) {
buf.append("FedoraBDefObject");
} else if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BMECH_OBJECT) {
buf.append("FedoraBMechObject");
} else {
buf.append("FedoraObject");
}
buf.append("\"\n PROFILE=\"");
StreamUtility.enc(obj.getContentModelId(), buf);
buf.append("\">\n <metsHdr CREATEDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getCreateDate()));
buf.append("\" LASTMODDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getLastModDate()));
buf.append("\" RECORDSTATUS=\"");
buf.append(obj.getState());
buf.append("\">\n <!-- This info can't be set via API-M. If it existed, it was ignored during import -->\n");
buf.append(" </metsHdr>\n");
//
// Serialize Audit Records
//
if (obj.getAuditRecords().size()>0) {
buf.append(" <amdSec ID=\"FEDORA-AUDITTRAIL\">\n");
String auditPrefix=(String) obj.getNamespaceMapping().get(FEDORA_AUDIT_NAMESPACE_URI);
Iterator iter=obj.getAuditRecords().iterator();
while (iter.hasNext()) {
AuditRecord audit=(AuditRecord) iter.next();
buf.append(" <digiprovMD ID=\"");
buf.append(audit.id);
buf.append("\" CREATED=\"");
String createDate=DateUtility.convertDateToString(audit.date);
buf.append(createDate);
buf.append("\" STATUS=\"A\">\n"); // status is always A
buf.append(" <mdWrap MIMETYPE=\"text/xml\" MDTYPE=\"OTHER\" LABEL=\"Fedora Object Audit Trail Record\">\n");
buf.append(" <xmlData>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":process type=\"");
StreamUtility.enc(audit.processType, buf);
buf.append("\"/>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":action>");
StreamUtility.enc(audit.action, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":action>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":responsibility>");
StreamUtility.enc(audit.responsibility, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":responsibility>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":date>");
buf.append(createDate);
buf.append("</");
buf.append(auditPrefix);
buf.append(":date>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":justification>");
StreamUtility.enc(audit.justification, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":justification>\n");
buf.append(" </");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" </xmlData>\n");
buf.append(" </mdWrap>\n");
buf.append(" </digiprovMD>\n");
}
buf.append(" </amdSec>\n");
}
//
// Serialize Datastreams
//
Iterator idIter=obj.datastreamIdIterator();
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one with this id,
// first decide if its an inline xml
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp==Datastream.XML_METADATA) {
if (ds.DSControlGrp.equalsIgnoreCase("X")) {
//
// Serialize inline XML datastream
// - dmdSec || amdSec?
//
DatastreamXMLMetadata mds=(DatastreamXMLMetadata) ds;
if (mds.DSMDClass==DatastreamXMLMetadata.DESCRIPTIVE) {
//
// Descriptive inline XML Metadata
//
// <!-- For each version with this dsId -->
// <dmdSec GROUPID=dsId
// ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </dmdSec>
//
Iterator dmdIter=obj.datastreams(id).iterator();
while (dmdIter.hasNext()) {
mds=(DatastreamXMLMetadata) dmdIter.next();
buf.append(" <dmdSec ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" GROUPID=\"");
buf.append(mds.DatastreamID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </dmdsec>\n");
}
} else {
//
// Administrative inline XML Metadata
//
// Technical ($mdClass$=techMD)
// Source ($mdClass$=sourceMD)
// Rights ($mdClass$=rightsMD)
// Digital Provenance ($mdClass$=digiprovMD)
//
// <amdSec ID=dsId>
// <!-- For each version with this dsId -->
// <$mdClass$ ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </techMd>
// </amdSec>
//
String mdClass;
if (mds.DSMDClass==DatastreamXMLMetadata.TECHNICAL) {
mdClass="techMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.SOURCE) {
mdClass="sourceMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.RIGHTS) {
mdClass="rightsMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.DIGIPROV) {
mdClass="digiprovMD";
} else {
throw new ObjectIntegrityException(
"Datastreams must have a class");
}
buf.append(" <amdSec ID=\"");
buf.append(mds.DatastreamID);
buf.append("\">\n");
Iterator amdIter=obj.datastreams(id).iterator();
while (amdIter.hasNext()) {
mds=(DatastreamXMLMetadata) amdIter.next();
buf.append(" <");
buf.append(mdClass);
buf.append(" ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </");
buf.append(mdClass);
buf.append(">\n");
}
buf.append(" </amdSec>\n");
}
}
}
// Now iterate through datastreams a second time, doing the fileSec
idIter=obj.datastreamIdIterator();
boolean didFileSec=false;
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one in the version group with this id, check its type
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp!=Datastream.XML_METADATA) { // must be ext ref or managed (so needs mets fileSec)
if (!ds.DSControlGrp.equalsIgnoreCase("X")) { // must be ext ref or managed (so needs mets fileSec)
//
// Externally-referenced or managed datastreams (fileSec)
//
if (!didFileSec) {
buf.append(" <fileSec>\n");
buf.append(" <fileGrp ID=\"DATASTREAMS\">\n");
didFileSec=true;
}
buf.append(" <fileGrp ID=\"");
buf.append(ds.DatastreamID);
buf.append("\">\n");
Iterator contentIter=obj.datastreams(id).iterator();
while (contentIter.hasNext()) {
DatastreamContent dsc=(DatastreamContent) contentIter.next();
buf.append(" <file ID=\"");
buf.append(dsc.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(dsc.DSCreateDT));
buf.append("\" MIMETYPE=\"");
buf.append(dsc.DSMIME);
buf.append("\" STATUS=\"");
buf.append(dsc.DSState);
buf.append("\" SIZE=\"" + dsc.DSSize);
buf.append("\" ADMID=\"");
Iterator admIdIter=getIds(obj, dsc, true).iterator();
int admNum=0;
while (admIdIter.hasNext()) {
String admId=(String) admIdIter.next();
if (admNum>0) {
buf.append(' ');
}
buf.append(admId);
admNum++;
}
buf.append("\" DMDID=\"");
Iterator dmdIdIter=getIds(obj, dsc, false).iterator();
int dmdNum=0;
while (dmdIdIter.hasNext()) {
String dmdId=(String) dmdIdIter.next();
if (dmdNum>0) {
buf.append(' ');
}
buf.append(dmdId);
dmdNum++;
}
//
// other attrs
//
buf.append("\">\n");
//if (dsc.DSControlGrp==Datastream.EXTERNAL_REF) {
// External (E) or External-Protected (P) Datastreams
if (dsc.DSControlGrp.equalsIgnoreCase("E") ||
dsc.DSControlGrp.equalsIgnoreCase("P")) {
DatastreamReferencedContent dsec=(DatastreamReferencedContent) dsc;
// xlink:title, xlink:href
buf.append(" <FLocat ");
buf.append(m_xlinkPrefix);
buf.append(":title=\"");
buf.append(dsec.DSLabel);
buf.append("\" ");
buf.append(m_xlinkPrefix);
buf.append(":href=\"");
if (dsec.DSLocation==null) {
throw new ObjectIntegrityException("Externally referenced content (ID=" + dsc.DSVersionID + ") must have a URL defined.");
}
buf.append(dsec.DSLocation.toString());
buf.append("\">\n");
} else {
// FContent=base64 encoded
}
buf.append(" </file>\n");
}
buf.append(" </fileGrp>\n");
}
}
if (didFileSec) {
buf.append(" </fileGrp>\n");
buf.append(" </fileSec>\n");
}
// Now do structmap...one for each disseminator
Iterator dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <structMap ID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" TYPE=\"fedora:dsBindingMap\">\n");
buf.append(" <div TYPE=\"");
buf.append(diss.bMechID);
buf.append("\" LABEL=\"");
buf.append(diss.dsBindMap.dsBindMapLabel);
buf.append("\">\n");
// iterate through diss.dsBindMap.dsBindings[]
DSBinding[] bindings=diss.dsBindMap.dsBindings;
for (int i=0; i<bindings.length; i++) {
buf.append(" <div TYPE=\"");
buf.append(bindings[i].bindKeyName);
buf.append("\" LABEL=\"");
buf.append(bindings[i].bindLabel);
buf.append("\" ORDER=\"");
buf.append(bindings[i].seqNo);
buf.append("\">\n");
buf.append(" <fptr FILEID=\"");
buf.append(bindings[i].datastreamID);
buf.append("\"/>\n");
buf.append(" </div>\n");
}
buf.append(" </div>\n");
buf.append(" </structMap>\n");
}
}
// Last, do disseminators
dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <behaviorSec ID=\"");
buf.append(diss.dissVersionID);
buf.append("\" STRUCTID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" BTYPE=\"");
buf.append(diss.bDefID);
buf.append("\" CREATED=\"");
String strDate=DateUtility.convertDateToString(diss.dissCreateDT);
buf.append(strDate);
buf.append("\" LABEL=\"");
buf.append(diss.dissLabel);
buf.append("\" GROUPID=\"");
buf.append(diss.dissID);
buf.append("\" STATUS=\"");
buf.append(diss.dissState);
buf.append("\">\n");
buf.append(" <interfaceDef LABEL=\"");
buf.append(diss.bDefLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bDefID);
buf.append("\"/>\n");
buf.append(" <mechanism LABEL=\"");
buf.append(diss.bMechLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bMechID);
buf.append("\"/>\n");
buf.append(" </behaviorSec>\n");
}
}
/*
<behaviorSec ID="DISS1.0" STRUCTID="S1" BTYPE="test:1" CREATED="2002-05-20T06:32:00" LABEL="UVA Std Image Behaviors" GROUPID="DISS1" STATUS="">
<interfaceDef LABEL="UVA Std Image Behavior Definition" LOCTYPE="URN" xlink:href="test:1"/>
<mechanism LABEL="UVA Std Image Behavior Mechanism" LOCTYPE="URN" xlink:href="test:2"/>
</behaviorSec>
*/
//
// Serialization Complete
//
buf.append("</mets>");
out.write(buf.toString().getBytes(m_characterEncoding));
out.flush();
} catch (UnsupportedEncodingException uee) {
throw uee;
} catch (IOException ioe) {
throw new StreamWriteException("Problem writing to outputstream "
+ "while serializing to mets: " + ioe.getMessage());
} finally {
try {
out.close();
} catch (IOException ioe2) {
throw new StreamIOException("Problem closing outputstream "
+ "after attempting to serialize to mets: "
+ ioe2.getMessage());
}
}
if (1==2) throw new ObjectIntegrityException("bad object");
}
| public void serialize(DigitalObject obj, OutputStream out, String encoding)
throws ObjectIntegrityException, StreamIOException,
UnsupportedEncodingException {
m_characterEncoding=encoding;
StringBuffer buf1=new StringBuffer();
buf1.append("test");
byte[] temp=buf1.toString().getBytes(m_characterEncoding);
try {
StringBuffer buf=new StringBuffer();
m_xlinkPrefix="xlink"; // default if can't figger it
//
// Serialize root element and header
//
buf.append("<?xml version=\"1.0\" ");
buf.append("encoding=\"");
buf.append(m_characterEncoding);
buf.append("\" ?>\n");
buf.append("<mets xmlns=\"http://www.loc.gov/METS/\"\n");
Iterator nsIter=obj.getNamespaceMapping().keySet().iterator();
boolean didXlink=false;
while (nsIter.hasNext()) {
String uri=(String) nsIter.next();
String prefix=(String) obj.getNamespaceMapping().get(uri);
if ( (uri.equals(METS_XLINK_NAMESPACE))
|| (uri.equals(REAL_XLINK_NAMESPACE)) ) {
m_xlinkPrefix=prefix;
didXlink=true;
}
buf.append(" xmlns:");
buf.append(prefix);
buf.append("=\"");
buf.append(uri);
buf.append("\"\n");
}
if (!didXlink) {
buf.append(" xmlns:xlink=\"" + REAL_XLINK_NAMESPACE + "\"\n");
}
buf.append(" OBJID=\"");
buf.append(obj.getPid());
buf.append("\"\n LABEL=\"");
StreamUtility.enc(obj.getLabel(), buf);
buf.append("\"\n TYPE=\"");
if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BDEF_OBJECT) {
buf.append("FedoraBDefObject");
} else if (obj.getFedoraObjectType()==DigitalObject.FEDORA_BMECH_OBJECT) {
buf.append("FedoraBMechObject");
} else {
buf.append("FedoraObject");
}
buf.append("\"\n PROFILE=\"");
StreamUtility.enc(obj.getContentModelId(), buf);
buf.append("\">\n <metsHdr CREATEDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getCreateDate()));
buf.append("\" LASTMODDATE=\"");
buf.append(DateUtility.convertDateToString(obj.getLastModDate()));
buf.append("\" RECORDSTATUS=\"");
buf.append(obj.getState());
buf.append("\">\n <!-- This info can't be set via API-M. If it existed, it was ignored during import -->\n");
buf.append(" </metsHdr>\n");
//
// Serialize Audit Records
//
if (obj.getAuditRecords().size()>0) {
buf.append(" <amdSec ID=\"FEDORA-AUDITTRAIL\">\n");
String auditPrefix=(String) obj.getNamespaceMapping().get(FEDORA_AUDIT_NAMESPACE_URI);
Iterator iter=obj.getAuditRecords().iterator();
while (iter.hasNext()) {
AuditRecord audit=(AuditRecord) iter.next();
buf.append(" <digiprovMD ID=\"");
buf.append(audit.id);
buf.append("\" CREATED=\"");
String createDate=DateUtility.convertDateToString(audit.date);
buf.append(createDate);
buf.append("\" STATUS=\"A\">\n"); // status is always A
buf.append(" <mdWrap MIMETYPE=\"text/xml\" MDTYPE=\"OTHER\" LABEL=\"Fedora Object Audit Trail Record\">\n");
buf.append(" <xmlData>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":process type=\"");
StreamUtility.enc(audit.processType, buf);
buf.append("\"/>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":action>");
StreamUtility.enc(audit.action, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":action>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":responsibility>");
StreamUtility.enc(audit.responsibility, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":responsibility>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":date>");
buf.append(createDate);
buf.append("</");
buf.append(auditPrefix);
buf.append(":date>\n");
buf.append(" <");
buf.append(auditPrefix);
buf.append(":justification>");
StreamUtility.enc(audit.justification, buf);
buf.append("</");
buf.append(auditPrefix);
buf.append(":justification>\n");
buf.append(" </");
buf.append(auditPrefix);
buf.append(":record>\n");
buf.append(" </xmlData>\n");
buf.append(" </mdWrap>\n");
buf.append(" </digiprovMD>\n");
}
buf.append(" </amdSec>\n");
}
//
// Serialize Datastreams
//
Iterator idIter=obj.datastreamIdIterator();
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one with this id,
// first decide if its an inline xml
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp==Datastream.XML_METADATA) {
if (ds.DSControlGrp.equalsIgnoreCase("X")) {
//
// Serialize inline XML datastream
// - dmdSec || amdSec?
//
DatastreamXMLMetadata mds=(DatastreamXMLMetadata) ds;
if (mds.DSMDClass==DatastreamXMLMetadata.DESCRIPTIVE) {
//
// Descriptive inline XML Metadata
//
// <!-- For each version with this dsId -->
// <dmdSec GROUPID=dsId
// ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </dmdSec>
//
Iterator dmdIter=obj.datastreams(id).iterator();
while (dmdIter.hasNext()) {
mds=(DatastreamXMLMetadata) dmdIter.next();
buf.append(" <dmdSec ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" GROUPID=\"");
buf.append(mds.DatastreamID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </dmdsec>\n");
}
} else {
//
// Administrative inline XML Metadata
//
// Technical ($mdClass$=techMD)
// Source ($mdClass$=sourceMD)
// Rights ($mdClass$=rightsMD)
// Digital Provenance ($mdClass$=digiprovMD)
//
// <amdSec ID=dsId>
// <!-- For each version with this dsId -->
// <$mdClass$ ID=dsVersionId
// CREATED=dsCreateDate
// STATUS=dsState>
// <mdWrap....>
// ...
// </mdWrap>
// </techMd>
// </amdSec>
//
String mdClass;
if (mds.DSMDClass==DatastreamXMLMetadata.TECHNICAL) {
mdClass="techMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.SOURCE) {
mdClass="sourceMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.RIGHTS) {
mdClass="rightsMD";
} else if (mds.DSMDClass==DatastreamXMLMetadata.DIGIPROV) {
mdClass="digiprovMD";
} else {
throw new ObjectIntegrityException(
"Datastreams must have a class");
}
buf.append(" <amdSec ID=\"");
buf.append(mds.DatastreamID);
buf.append("\">\n");
Iterator amdIter=obj.datastreams(id).iterator();
while (amdIter.hasNext()) {
mds=(DatastreamXMLMetadata) amdIter.next();
buf.append(" <");
buf.append(mdClass);
buf.append(" ID=\"");
buf.append(mds.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(
mds.DSCreateDT));
buf.append("\" STATUS=\"");
buf.append(mds.DSState);
buf.append("\">\n");
mdWrap(mds, buf);
buf.append(" </");
buf.append(mdClass);
buf.append(">\n");
}
buf.append(" </amdSec>\n");
}
}
}
// Now iterate through datastreams a second time, doing the fileSec
idIter=obj.datastreamIdIterator();
boolean didFileSec=false;
while (idIter.hasNext()) {
String id=(String) idIter.next();
// from the first one in the version group with this id, check its type
Datastream ds=(Datastream) obj.datastreams(id).get(0);
//if (ds.DSControlGrp!=Datastream.XML_METADATA) { // must be ext ref or managed (so needs mets fileSec)
if (!ds.DSControlGrp.equalsIgnoreCase("X")) { // must be ext ref or managed (so needs mets fileSec)
//
// Externally-referenced or managed datastreams (fileSec)
//
if (!didFileSec) {
buf.append(" <fileSec>\n");
buf.append(" <fileGrp ID=\"DATASTREAMS\">\n");
didFileSec=true;
}
buf.append(" <fileGrp ID=\"");
buf.append(ds.DatastreamID);
buf.append("\">\n");
Iterator contentIter=obj.datastreams(id).iterator();
while (contentIter.hasNext()) {
DatastreamContent dsc=(DatastreamContent) contentIter.next();
buf.append(" <file ID=\"");
buf.append(dsc.DSVersionID);
buf.append("\" CREATED=\"");
buf.append(DateUtility.convertDateToString(dsc.DSCreateDT));
buf.append("\" MIMETYPE=\"");
buf.append(dsc.DSMIME);
buf.append("\" STATUS=\"");
buf.append(dsc.DSState);
buf.append("\" SIZE=\"" + dsc.DSSize);
buf.append("\" ADMID=\"");
Iterator admIdIter=getIds(obj, dsc, true).iterator();
int admNum=0;
while (admIdIter.hasNext()) {
String admId=(String) admIdIter.next();
if (admNum>0) {
buf.append(' ');
}
buf.append(admId);
admNum++;
}
buf.append("\" DMDID=\"");
Iterator dmdIdIter=getIds(obj, dsc, false).iterator();
int dmdNum=0;
while (dmdIdIter.hasNext()) {
String dmdId=(String) dmdIdIter.next();
if (dmdNum>0) {
buf.append(' ');
}
buf.append(dmdId);
dmdNum++;
}
//
// other attrs
//
buf.append("\">\n");
//if (dsc.DSControlGrp==Datastream.EXTERNAL_REF) {
// External (E) or External-Protected (P) Datastreams
if (dsc.DSControlGrp.equalsIgnoreCase("E") ||
dsc.DSControlGrp.equalsIgnoreCase("P")) {
DatastreamReferencedContent dsec=(DatastreamReferencedContent) dsc;
// xlink:title, xlink:href
buf.append(" <FLocat ");
buf.append(m_xlinkPrefix);
buf.append(":title=\"");
buf.append(dsec.DSLabel);
buf.append("\" ");
buf.append(m_xlinkPrefix);
buf.append(":href=\"");
if (dsec.DSLocation==null) {
throw new ObjectIntegrityException("Externally referenced content (ID=" + dsc.DSVersionID + ") must have a URL defined.");
}
buf.append(dsec.DSLocation.toString());
buf.append("\"/>\n");
} else {
// FContent=base64 encoded
}
buf.append(" </file>\n");
}
buf.append(" </fileGrp>\n");
}
}
if (didFileSec) {
buf.append(" </fileGrp>\n");
buf.append(" </fileSec>\n");
}
// Now do structmap...one for each disseminator
Iterator dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <structMap ID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" TYPE=\"fedora:dsBindingMap\">\n");
buf.append(" <div TYPE=\"");
buf.append(diss.bMechID);
buf.append("\" LABEL=\"");
buf.append(diss.dsBindMap.dsBindMapLabel);
buf.append("\">\n");
// iterate through diss.dsBindMap.dsBindings[]
DSBinding[] bindings=diss.dsBindMap.dsBindings;
for (int i=0; i<bindings.length; i++) {
buf.append(" <div TYPE=\"");
buf.append(bindings[i].bindKeyName);
buf.append("\" LABEL=\"");
buf.append(bindings[i].bindLabel);
buf.append("\" ORDER=\"");
buf.append(bindings[i].seqNo);
buf.append("\">\n");
buf.append(" <fptr FILEID=\"");
buf.append(bindings[i].datastreamID);
buf.append("\"/>\n");
buf.append(" </div>\n");
}
buf.append(" </div>\n");
buf.append(" </structMap>\n");
}
}
// Last, do disseminators
dissIdIter=obj.disseminatorIdIterator();
while (dissIdIter.hasNext()) {
String did=(String) dissIdIter.next();
Iterator dissIter=obj.disseminators(did).iterator();
while (dissIter.hasNext()) {
Disseminator diss=(Disseminator) dissIter.next();
buf.append(" <behaviorSec ID=\"");
buf.append(diss.dissVersionID);
buf.append("\" STRUCTID=\"");
buf.append(diss.dsBindMapID);
buf.append("\" BTYPE=\"");
buf.append(diss.bDefID);
buf.append("\" CREATED=\"");
String strDate=DateUtility.convertDateToString(diss.dissCreateDT);
buf.append(strDate);
buf.append("\" LABEL=\"");
buf.append(diss.dissLabel);
buf.append("\" GROUPID=\"");
buf.append(diss.dissID);
buf.append("\" STATUS=\"");
buf.append(diss.dissState);
buf.append("\">\n");
buf.append(" <interfaceDef LABEL=\"");
buf.append(diss.bDefLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bDefID);
buf.append("\"/>\n");
buf.append(" <mechanism LABEL=\"");
buf.append(diss.bMechLabel);
buf.append("\" LOCTYPE=\"URN\" xlink:href=\"");
buf.append(diss.bMechID);
buf.append("\"/>\n");
buf.append(" </behaviorSec>\n");
}
}
/*
<behaviorSec ID="DISS1.0" STRUCTID="S1" BTYPE="test:1" CREATED="2002-05-20T06:32:00" LABEL="UVA Std Image Behaviors" GROUPID="DISS1" STATUS="">
<interfaceDef LABEL="UVA Std Image Behavior Definition" LOCTYPE="URN" xlink:href="test:1"/>
<mechanism LABEL="UVA Std Image Behavior Mechanism" LOCTYPE="URN" xlink:href="test:2"/>
</behaviorSec>
*/
//
// Serialization Complete
//
buf.append("</mets>");
out.write(buf.toString().getBytes(m_characterEncoding));
out.flush();
} catch (UnsupportedEncodingException uee) {
throw uee;
} catch (IOException ioe) {
throw new StreamWriteException("Problem writing to outputstream "
+ "while serializing to mets: " + ioe.getMessage());
} finally {
try {
out.close();
} catch (IOException ioe2) {
throw new StreamIOException("Problem closing outputstream "
+ "after attempting to serialize to mets: "
+ ioe2.getMessage());
}
}
if (1==2) throw new ObjectIntegrityException("bad object");
}
|
diff --git a/contrib/tiles/src/share/org/apache/struts/tiles/xmlDefinition/XmlDefinition.java b/contrib/tiles/src/share/org/apache/struts/tiles/xmlDefinition/XmlDefinition.java
index 61ae2703b..8d72d85db 100644
--- a/contrib/tiles/src/share/org/apache/struts/tiles/xmlDefinition/XmlDefinition.java
+++ b/contrib/tiles/src/share/org/apache/struts/tiles/xmlDefinition/XmlDefinition.java
@@ -1,158 +1,161 @@
//Source file: D:\\tmp\\generated\\s1\\struts\\component\\xmlDefinition\\XmlDefinition.java
package org.apache.struts.tiles.xmlDefinition;
import org.apache.struts.tiles.ComponentDefinition;
import org.apache.struts.tiles.NoSuchDefinitionException;
import java.util.Iterator;
/**
A definition red from an XML definitions file.
*/
public class XmlDefinition extends ComponentDefinition
{
/** Debug flag */
static public final boolean debug = false;
/**
* Extends attribute value.
*/
private String inherit;
/**
* Use for resolving inheritance.
*/
private boolean isVisited=false;
/**
* Constructor.
*/
public XmlDefinition()
{
super();
//if(debug)
//System.out.println( "create definition" );
}
/**
* add an attribute to this component
*
* @param attribute Attribute to add.
*/
public void addAttribute( XmlAttribute attribute)
{
putAttribute( attribute.getName(), attribute.getValue() );
}
/**
* Sets the value of the extend and path property.
*
* @param aPath the new value of the path property
*/
public void setExtends(String name)
{
inherit = name;
}
/**
* Access method for the path property.
*
* @return the current value of the path property
*/
public String getExtends()
{
return inherit;
}
/**
* Get the value of the extendproperty.
*
*/
public boolean isExtending( )
{
return inherit!=null;
}
/**
* Get the value of the extendproperty.
*
*/
public void setIsVisited( boolean isVisited )
{
this.isVisited = isVisited;
}
/**
* Resolve inheritance.
* First, resolve parent's inheritance, then set path to the parent's path.
* Also copy attributes setted in parent, and not set in child
* If instance doesn't extends something, do nothing.
* @throw NoSuchInstanceException If a inheritance can be solved.
*/
public void resolveInheritance( XmlDefinitionsSet definitionsSet )
throws NoSuchDefinitionException
{
// Already done, or not needed ?
if( isVisited || !isExtending() )
return;
if( debug)
System.out.println( "Resolve definition for child name='"
+ getName() + "' extends='"
+ getExtends() + "'." );
// Set as visited to avoid endless recurisvity.
setIsVisited( true );
// Resolve parent before itself.
XmlDefinition parent = definitionsSet.getDefinition( getExtends() );
if( parent == null )
{ // error
String msg = "Error while resolving definition inheritance: child '"
+ getName() + "' can't find its ancestor '"
+ getExtends() + "'. Please check your description file.";
System.out.println( msg );
// to do : find better exception
throw new NoSuchDefinitionException( msg );
}
parent.resolveInheritance( definitionsSet );
// Iterate on each parent's attribute, and add it if not defined in child.
Iterator parentAttributes = parent.getAttributes().keySet().iterator();
while( parentAttributes.hasNext() )
{
String name = (String)parentAttributes.next();
if( !getAttributes().containsKey(name) )
putAttribute( name, parent.getAttribute(name) );
}
- // Set path
- setPath( parent.getPath() );
+ // Set path and role if not setted
+ if( path == null )
+ setPath( parent.getPath() );
+ if( role == null )
+ setRole( parent.getRole() );
}
/**
* Overload this definition with passed child.
* All attributes from child are copied to this definition. Previous attribute with
* same name are disguarded.
* Special attribute 'path','role' and 'extends' are overloaded if defined in child.
* @param child Child used to overload this definition.
*/
public void overload( XmlDefinition child )
{
if( child.getPath() != null )
{
path = child.getPath();
}
if( child.getExtends() != null )
{
inherit = child.getExtends();
}
if( child.getRole() != null )
{
role = child.getRole();
}
// put all child attributes in parent.
attributes.putAll( child.getAttributes());
}
}
| true | true | public void resolveInheritance( XmlDefinitionsSet definitionsSet )
throws NoSuchDefinitionException
{
// Already done, or not needed ?
if( isVisited || !isExtending() )
return;
if( debug)
System.out.println( "Resolve definition for child name='"
+ getName() + "' extends='"
+ getExtends() + "'." );
// Set as visited to avoid endless recurisvity.
setIsVisited( true );
// Resolve parent before itself.
XmlDefinition parent = definitionsSet.getDefinition( getExtends() );
if( parent == null )
{ // error
String msg = "Error while resolving definition inheritance: child '"
+ getName() + "' can't find its ancestor '"
+ getExtends() + "'. Please check your description file.";
System.out.println( msg );
// to do : find better exception
throw new NoSuchDefinitionException( msg );
}
parent.resolveInheritance( definitionsSet );
// Iterate on each parent's attribute, and add it if not defined in child.
Iterator parentAttributes = parent.getAttributes().keySet().iterator();
while( parentAttributes.hasNext() )
{
String name = (String)parentAttributes.next();
if( !getAttributes().containsKey(name) )
putAttribute( name, parent.getAttribute(name) );
}
// Set path
setPath( parent.getPath() );
}
| public void resolveInheritance( XmlDefinitionsSet definitionsSet )
throws NoSuchDefinitionException
{
// Already done, or not needed ?
if( isVisited || !isExtending() )
return;
if( debug)
System.out.println( "Resolve definition for child name='"
+ getName() + "' extends='"
+ getExtends() + "'." );
// Set as visited to avoid endless recurisvity.
setIsVisited( true );
// Resolve parent before itself.
XmlDefinition parent = definitionsSet.getDefinition( getExtends() );
if( parent == null )
{ // error
String msg = "Error while resolving definition inheritance: child '"
+ getName() + "' can't find its ancestor '"
+ getExtends() + "'. Please check your description file.";
System.out.println( msg );
// to do : find better exception
throw new NoSuchDefinitionException( msg );
}
parent.resolveInheritance( definitionsSet );
// Iterate on each parent's attribute, and add it if not defined in child.
Iterator parentAttributes = parent.getAttributes().keySet().iterator();
while( parentAttributes.hasNext() )
{
String name = (String)parentAttributes.next();
if( !getAttributes().containsKey(name) )
putAttribute( name, parent.getAttribute(name) );
}
// Set path and role if not setted
if( path == null )
setPath( parent.getPath() );
if( role == null )
setRole( parent.getRole() );
}
|
diff --git a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/IncludingConfigHandler.java b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/IncludingConfigHandler.java
index 341831681..981d04dc8 100644
--- a/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/IncludingConfigHandler.java
+++ b/sphinx4/src/sphinx4/edu/cmu/sphinx/util/props/IncludingConfigHandler.java
@@ -1,88 +1,88 @@
package edu.cmu.sphinx.util.props;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
/**
* Handles configurations like the old one but is also able to process a new "include"-field
*
* @author Holger Brandl
*/
public class IncludingConfigHandler extends ConfigHandler {
public IncludingConfigHandler(Map<String, RawPropertyData> rpdMap, GlobalProperties globalProperties) {
super(rpdMap, globalProperties);
}
/* (non-Javadoc)
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("config")) {
// nothing to do
} else if (qName.equals("include")) {
String includeFileName = attributes.getValue("file");
try {
URL fileURL = new File(includeFileName).toURI().toURL();
SaxLoader saxLoader = new SaxLoader(fileURL, globalProperties, rpdMap);
saxLoader.load();
} catch (IOException e) {
- throw new RuntimeException("Error while processing <include file=\"" + includeFileName + "\">", e);
+ throw new RuntimeException("Error while processing <include file=\"" + includeFileName + "\">: " + e.toString(), e);
}
} else if (qName.equals("component")) {
String curComponent = attributes.getValue("name");
String curType = attributes.getValue("type");
if (rpdMap.get(curComponent) != null) {
throw new SAXParseException(
"duplicate definition for " + curComponent, locator);
}
rpd = new RawPropertyData(curComponent, curType);
} else if (qName.equals("property")) {
String name = attributes.getValue("name");
String value = attributes.getValue("value");
if (attributes.getLength() != 2 || name == null
|| value == null) {
throw new SAXParseException(
"property element must only have "
+ "'name' and 'value' attributes", locator);
}
if (rpd == null) {
// we are not in a component so add this to the global
// set of symbols
// String symbolName = "${" + name + "}"; // why should we warp the global props here
globalProperties.setValue(name, value);
} else if (rpd.contains(name)) {
throw new SAXParseException("Duplicate property: " + name,
locator);
} else {
rpd.add(name, value);
}
} else if (qName.equals("propertylist")) {
itemListName = attributes.getValue("name");
if (attributes.getLength() != 1 || itemListName == null) {
throw new SAXParseException("list element must only have "
+ "the 'name' attribute", locator);
}
itemList = new ArrayList<String>();
} else if (qName.equals("item")) {
if (attributes.getLength() != 0) {
throw new SAXParseException("unknown 'item' attribute",
locator);
}
curItem = new StringBuffer();
} else {
throw new SAXParseException("Unknown element '" + qName + "'",
locator);
}
}
}
| true | true | public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("config")) {
// nothing to do
} else if (qName.equals("include")) {
String includeFileName = attributes.getValue("file");
try {
URL fileURL = new File(includeFileName).toURI().toURL();
SaxLoader saxLoader = new SaxLoader(fileURL, globalProperties, rpdMap);
saxLoader.load();
} catch (IOException e) {
throw new RuntimeException("Error while processing <include file=\"" + includeFileName + "\">", e);
}
} else if (qName.equals("component")) {
String curComponent = attributes.getValue("name");
String curType = attributes.getValue("type");
if (rpdMap.get(curComponent) != null) {
throw new SAXParseException(
"duplicate definition for " + curComponent, locator);
}
rpd = new RawPropertyData(curComponent, curType);
} else if (qName.equals("property")) {
String name = attributes.getValue("name");
String value = attributes.getValue("value");
if (attributes.getLength() != 2 || name == null
|| value == null) {
throw new SAXParseException(
"property element must only have "
+ "'name' and 'value' attributes", locator);
}
if (rpd == null) {
// we are not in a component so add this to the global
// set of symbols
// String symbolName = "${" + name + "}"; // why should we warp the global props here
globalProperties.setValue(name, value);
} else if (rpd.contains(name)) {
throw new SAXParseException("Duplicate property: " + name,
locator);
} else {
rpd.add(name, value);
}
} else if (qName.equals("propertylist")) {
itemListName = attributes.getValue("name");
if (attributes.getLength() != 1 || itemListName == null) {
throw new SAXParseException("list element must only have "
+ "the 'name' attribute", locator);
}
itemList = new ArrayList<String>();
} else if (qName.equals("item")) {
if (attributes.getLength() != 0) {
throw new SAXParseException("unknown 'item' attribute",
locator);
}
curItem = new StringBuffer();
} else {
throw new SAXParseException("Unknown element '" + qName + "'",
locator);
}
}
| public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("config")) {
// nothing to do
} else if (qName.equals("include")) {
String includeFileName = attributes.getValue("file");
try {
URL fileURL = new File(includeFileName).toURI().toURL();
SaxLoader saxLoader = new SaxLoader(fileURL, globalProperties, rpdMap);
saxLoader.load();
} catch (IOException e) {
throw new RuntimeException("Error while processing <include file=\"" + includeFileName + "\">: " + e.toString(), e);
}
} else if (qName.equals("component")) {
String curComponent = attributes.getValue("name");
String curType = attributes.getValue("type");
if (rpdMap.get(curComponent) != null) {
throw new SAXParseException(
"duplicate definition for " + curComponent, locator);
}
rpd = new RawPropertyData(curComponent, curType);
} else if (qName.equals("property")) {
String name = attributes.getValue("name");
String value = attributes.getValue("value");
if (attributes.getLength() != 2 || name == null
|| value == null) {
throw new SAXParseException(
"property element must only have "
+ "'name' and 'value' attributes", locator);
}
if (rpd == null) {
// we are not in a component so add this to the global
// set of symbols
// String symbolName = "${" + name + "}"; // why should we warp the global props here
globalProperties.setValue(name, value);
} else if (rpd.contains(name)) {
throw new SAXParseException("Duplicate property: " + name,
locator);
} else {
rpd.add(name, value);
}
} else if (qName.equals("propertylist")) {
itemListName = attributes.getValue("name");
if (attributes.getLength() != 1 || itemListName == null) {
throw new SAXParseException("list element must only have "
+ "the 'name' attribute", locator);
}
itemList = new ArrayList<String>();
} else if (qName.equals("item")) {
if (attributes.getLength() != 0) {
throw new SAXParseException("unknown 'item' attribute",
locator);
}
curItem = new StringBuffer();
} else {
throw new SAXParseException("Unknown element '" + qName + "'",
locator);
}
}
|
diff --git a/jOOQ-meta/src/main/java/org/jooq/util/oracle/OracleRoutineDefinition.java b/jOOQ-meta/src/main/java/org/jooq/util/oracle/OracleRoutineDefinition.java
index 47d7035b1..70d4138a4 100644
--- a/jOOQ-meta/src/main/java/org/jooq/util/oracle/OracleRoutineDefinition.java
+++ b/jOOQ-meta/src/main/java/org/jooq/util/oracle/OracleRoutineDefinition.java
@@ -1,155 +1,155 @@
/**
* Copyright (c) 2009-2012, Lukas Eder, lukas.eder@gmail.com
* All rights reserved.
*
* This software is licensed to you under the Apache License, Version 2.0
* (the "License"); You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* . Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* . Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* . Neither the name "jOOQ" nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jooq.util.oracle;
import static org.jooq.impl.Factory.inline;
import static org.jooq.util.oracle.sys.Tables.ALL_ARGUMENTS;
import static org.jooq.util.oracle.sys.Tables.ALL_COL_COMMENTS;
import java.math.BigDecimal;
import java.sql.SQLException;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.tools.StringUtils;
import org.jooq.util.AbstractRoutineDefinition;
import org.jooq.util.DataTypeDefinition;
import org.jooq.util.DefaultDataTypeDefinition;
import org.jooq.util.DefaultParameterDefinition;
import org.jooq.util.InOutDefinition;
import org.jooq.util.PackageDefinition;
import org.jooq.util.ParameterDefinition;
import org.jooq.util.SchemaDefinition;
/**
* @author Lukas Eder
*/
public class OracleRoutineDefinition extends AbstractRoutineDefinition {
private static Boolean is11g;
private final BigDecimal objectId;
public OracleRoutineDefinition(SchemaDefinition schema, PackageDefinition pkg, String name, String comment, BigDecimal objectId, String overload) {
this(schema, pkg, name, comment, objectId, overload, false);
}
public OracleRoutineDefinition(SchemaDefinition schema, PackageDefinition pkg, String name, String comment, BigDecimal objectId, String overload, boolean aggregate) {
super(schema, pkg, name, comment, overload, aggregate);
this.objectId = objectId;
}
@Override
protected void init0() throws SQLException {
// [#1324] The ALL_ARGUMENTS.DEFAULTED column is available in Oracle 11g
// only. This feature should thus be deactivated for older versions
Field<String> defaulted = is11g()
? ALL_ARGUMENTS.DEFAULTED
: inline("N");
Result<Record> result = create().select(
ALL_ARGUMENTS.IN_OUT,
ALL_ARGUMENTS.ARGUMENT_NAME,
ALL_ARGUMENTS.DATA_TYPE,
ALL_ARGUMENTS.DATA_LENGTH,
ALL_ARGUMENTS.DATA_PRECISION,
ALL_ARGUMENTS.DATA_SCALE,
ALL_ARGUMENTS.TYPE_NAME,
ALL_ARGUMENTS.POSITION,
defaulted)
.from(ALL_ARGUMENTS)
.where(ALL_ARGUMENTS.OWNER.equal(getSchema().getName()))
.and(ALL_ARGUMENTS.OBJECT_NAME.equal(getName()))
.and(ALL_ARGUMENTS.OBJECT_ID.equal(objectId))
- .and(ALL_ARGUMENTS.OVERLOAD.equal(getOverload()))
+ .and(ALL_ARGUMENTS.OVERLOAD.isNotDistinctFrom(getOverload()))
.and(ALL_ARGUMENTS.DATA_LEVEL.equal(BigDecimal.ZERO))
// [#284] In packages, procedures without arguments may have a
// single data type entry that does not mean anything...?
.and(ALL_ARGUMENTS.DATA_TYPE.isNotNull())
.orderBy(ALL_ARGUMENTS.POSITION.asc()).fetch();
for (Record record : result) {
InOutDefinition inOut =
InOutDefinition.getFromString(record.getValue(ALL_ARGUMENTS.IN_OUT));
DataTypeDefinition type = new DefaultDataTypeDefinition(
getDatabase(),
getSchema(),
record.getValue(ALL_ARGUMENTS.DATA_TYPE),
record.getValue(ALL_ARGUMENTS.DATA_LENGTH),
record.getValue(ALL_ARGUMENTS.DATA_PRECISION),
record.getValue(ALL_ARGUMENTS.DATA_SCALE),
record.getValue(ALL_ARGUMENTS.TYPE_NAME));
String name = record.getValue(ALL_ARGUMENTS.ARGUMENT_NAME);
int position = record.getValue(ALL_ARGUMENTS.POSITION, int.class);
// [#378] Oracle supports stored functions with OUT parameters.
// They are mapped to procedures in jOOQ
if (StringUtils.isBlank(name) && position == 0) {
inOut = InOutDefinition.RETURN;
name = "RETURN_VALUE";
}
ParameterDefinition parameter = new DefaultParameterDefinition(
this,
name,
position,
type,
record.getValue(defaulted, boolean.class));
addParameter(inOut, parameter);
}
}
private boolean is11g() {
if (is11g == null) {
is11g = create().selectCount()
.from(ALL_COL_COMMENTS)
.where(ALL_COL_COMMENTS.OWNER.equal(ALL_ARGUMENTS.getSchema().getName()))
.and(ALL_COL_COMMENTS.TABLE_NAME.equal(ALL_ARGUMENTS.getName()))
.and(ALL_COL_COMMENTS.COLUMN_NAME.equal(ALL_ARGUMENTS.DEFAULTED.getName()))
.fetchOne(0, boolean.class);
}
return is11g;
}
}
| true | true | protected void init0() throws SQLException {
// [#1324] The ALL_ARGUMENTS.DEFAULTED column is available in Oracle 11g
// only. This feature should thus be deactivated for older versions
Field<String> defaulted = is11g()
? ALL_ARGUMENTS.DEFAULTED
: inline("N");
Result<Record> result = create().select(
ALL_ARGUMENTS.IN_OUT,
ALL_ARGUMENTS.ARGUMENT_NAME,
ALL_ARGUMENTS.DATA_TYPE,
ALL_ARGUMENTS.DATA_LENGTH,
ALL_ARGUMENTS.DATA_PRECISION,
ALL_ARGUMENTS.DATA_SCALE,
ALL_ARGUMENTS.TYPE_NAME,
ALL_ARGUMENTS.POSITION,
defaulted)
.from(ALL_ARGUMENTS)
.where(ALL_ARGUMENTS.OWNER.equal(getSchema().getName()))
.and(ALL_ARGUMENTS.OBJECT_NAME.equal(getName()))
.and(ALL_ARGUMENTS.OBJECT_ID.equal(objectId))
.and(ALL_ARGUMENTS.OVERLOAD.equal(getOverload()))
.and(ALL_ARGUMENTS.DATA_LEVEL.equal(BigDecimal.ZERO))
// [#284] In packages, procedures without arguments may have a
// single data type entry that does not mean anything...?
.and(ALL_ARGUMENTS.DATA_TYPE.isNotNull())
.orderBy(ALL_ARGUMENTS.POSITION.asc()).fetch();
for (Record record : result) {
InOutDefinition inOut =
InOutDefinition.getFromString(record.getValue(ALL_ARGUMENTS.IN_OUT));
DataTypeDefinition type = new DefaultDataTypeDefinition(
getDatabase(),
getSchema(),
record.getValue(ALL_ARGUMENTS.DATA_TYPE),
record.getValue(ALL_ARGUMENTS.DATA_LENGTH),
record.getValue(ALL_ARGUMENTS.DATA_PRECISION),
record.getValue(ALL_ARGUMENTS.DATA_SCALE),
record.getValue(ALL_ARGUMENTS.TYPE_NAME));
String name = record.getValue(ALL_ARGUMENTS.ARGUMENT_NAME);
int position = record.getValue(ALL_ARGUMENTS.POSITION, int.class);
// [#378] Oracle supports stored functions with OUT parameters.
// They are mapped to procedures in jOOQ
if (StringUtils.isBlank(name) && position == 0) {
inOut = InOutDefinition.RETURN;
name = "RETURN_VALUE";
}
ParameterDefinition parameter = new DefaultParameterDefinition(
this,
name,
position,
type,
record.getValue(defaulted, boolean.class));
addParameter(inOut, parameter);
}
}
| protected void init0() throws SQLException {
// [#1324] The ALL_ARGUMENTS.DEFAULTED column is available in Oracle 11g
// only. This feature should thus be deactivated for older versions
Field<String> defaulted = is11g()
? ALL_ARGUMENTS.DEFAULTED
: inline("N");
Result<Record> result = create().select(
ALL_ARGUMENTS.IN_OUT,
ALL_ARGUMENTS.ARGUMENT_NAME,
ALL_ARGUMENTS.DATA_TYPE,
ALL_ARGUMENTS.DATA_LENGTH,
ALL_ARGUMENTS.DATA_PRECISION,
ALL_ARGUMENTS.DATA_SCALE,
ALL_ARGUMENTS.TYPE_NAME,
ALL_ARGUMENTS.POSITION,
defaulted)
.from(ALL_ARGUMENTS)
.where(ALL_ARGUMENTS.OWNER.equal(getSchema().getName()))
.and(ALL_ARGUMENTS.OBJECT_NAME.equal(getName()))
.and(ALL_ARGUMENTS.OBJECT_ID.equal(objectId))
.and(ALL_ARGUMENTS.OVERLOAD.isNotDistinctFrom(getOverload()))
.and(ALL_ARGUMENTS.DATA_LEVEL.equal(BigDecimal.ZERO))
// [#284] In packages, procedures without arguments may have a
// single data type entry that does not mean anything...?
.and(ALL_ARGUMENTS.DATA_TYPE.isNotNull())
.orderBy(ALL_ARGUMENTS.POSITION.asc()).fetch();
for (Record record : result) {
InOutDefinition inOut =
InOutDefinition.getFromString(record.getValue(ALL_ARGUMENTS.IN_OUT));
DataTypeDefinition type = new DefaultDataTypeDefinition(
getDatabase(),
getSchema(),
record.getValue(ALL_ARGUMENTS.DATA_TYPE),
record.getValue(ALL_ARGUMENTS.DATA_LENGTH),
record.getValue(ALL_ARGUMENTS.DATA_PRECISION),
record.getValue(ALL_ARGUMENTS.DATA_SCALE),
record.getValue(ALL_ARGUMENTS.TYPE_NAME));
String name = record.getValue(ALL_ARGUMENTS.ARGUMENT_NAME);
int position = record.getValue(ALL_ARGUMENTS.POSITION, int.class);
// [#378] Oracle supports stored functions with OUT parameters.
// They are mapped to procedures in jOOQ
if (StringUtils.isBlank(name) && position == 0) {
inOut = InOutDefinition.RETURN;
name = "RETURN_VALUE";
}
ParameterDefinition parameter = new DefaultParameterDefinition(
this,
name,
position,
type,
record.getValue(defaulted, boolean.class));
addParameter(inOut, parameter);
}
}
|
diff --git a/app/models/transit/Stop.java b/app/models/transit/Stop.java
index d67884a..cd701bf 100644
--- a/app/models/transit/Stop.java
+++ b/app/models/transit/Stop.java
@@ -1,223 +1,223 @@
package models.transit;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ManyToOne;
import javax.persistence.Query;
import com.mysql.jdbc.log.Log;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;
import org.codehaus.groovy.tools.shell.util.Logger;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.hibernate.annotations.Type;
import play.db.jpa.Model;
@JsonIgnoreProperties({"entityId", "persistent"})
@Entity
public class Stop extends Model {
public String gtfsStopId;
public String stopCode;
public String stopName;
public String stopDesc;
public String zoneId;
public String stopUrl;
public String stopIconUrl;
@ManyToOne
public Agency agency;
@Enumerated(EnumType.STRING)
public LocationType locationType;
@Enumerated(EnumType.STRING)
public AttributeAvailabilityType bikeParking;
@Enumerated(EnumType.STRING)
public AttributeAvailabilityType wheelchairBoarding;
public String parentStation;
// Major stop is a custom field; it has no corralary in the GTFS.
public Boolean majorStop;
@JsonCreator
public static Stop factory(long id) {
return Stop.findById(id);
}
@JsonCreator
public static Stop factory(String id) {
return Stop.findById(Long.parseLong(id));
}
@JsonIgnore
@Type(type = "org.hibernatespatial.GeometryUserType")
public Point location;
@JsonProperty("location")
public Hashtable getLocation() {
Hashtable loc = new Hashtable();
loc.put("lat", this.location.getY());
loc.put("lng", this.location.getX());
return loc;
}
public void merge(Stop mergedStop) {
// find replace references to mergedStop
StopTime.replaceStop(this, mergedStop);
TripPatternStop.replaceStop(this, mergedStop);
mergedStop.delete();
}
public void setLocation(Hashtable<String, Double> loc) {
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
this.location = geometryFactory.createPoint(new Coordinate(loc.get("lng"), loc.get("lat")));;
}
public Point locationPoint() {
Hashtable<String, Double> loc = this.getLocation();
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
return geometryFactory.createPoint(new Coordinate(loc.get("lat"), loc.get("lng")));
}
public Stop(org.onebusaway.gtfs.model.Stop stop, GeometryFactory geometryFactory) {
this.gtfsStopId = stop.getId().toString();
this.stopCode = stop.getCode();
this.stopName = stop.getName();
this.stopDesc = stop.getDesc();
this.zoneId = stop.getZoneId();
this.stopUrl = stop.getUrl();
this.locationType = stop.getLocationType() == 1 ? LocationType.STATION : LocationType.STOP;
this.parentStation = stop.getParentStation();
this.location = geometryFactory.createPoint(new Coordinate(stop.getLat(),stop.getLon()));
}
public Stop(Agency agency,String stopName, String stopCode, String stopUrl, String stopDesc, Double lat, Double lon) {
this.agency = agency;
this.stopCode = stopCode;
this.stopName = stopName;
this.stopDesc = stopDesc;
this.stopUrl = stopUrl;
this.locationType = LocationType.STOP;
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), 4326);
this.location = geometryFactory.createPoint(new Coordinate(lon, lat));;
}
public static BigInteger nativeInsert(EntityManager em, org.onebusaway.gtfs.model.Stop gtfsStop, BigInteger agencyId)
{
Query idQuery = em.createNativeQuery("SELECT NEXTVAL('hibernate_sequence');");
BigInteger nextId = (BigInteger)idQuery.getSingleResult();
em.createNativeQuery("INSERT INTO stop (id, locationtype, parentstation, stopcode, stopdesc, gtfsstopid, stopname, stopurl, zoneid, location, agency_id)" +
" VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ST_GeomFromText( ? , 4326), ?);")
.setParameter(1, nextId)
.setParameter(2, gtfsStop.getLocationType() == 1 ? LocationType.STATION.name() : LocationType.STOP.name())
.setParameter(3, gtfsStop.getParentStation())
.setParameter(4, gtfsStop.getCode())
.setParameter(5, gtfsStop.getDesc())
.setParameter(6, gtfsStop.getId().toString())
.setParameter(7, gtfsStop.getName())
.setParameter(8, gtfsStop.getUrl())
.setParameter(9, gtfsStop.getZoneId())
.setParameter(10, "POINT(" + gtfsStop.getLon() + " " + gtfsStop.getLat() + ")")
.setParameter(11, agencyId)
.executeUpdate();
return nextId;
}
public static List<List<Stop>> findDuplicateStops(BigInteger agencyId) {
// !!! need to autodetect proper SRID for UTM Zone
Query q = Stop.em().createNativeQuery("SELECT s1_id, s2_id, dist FROM " +
"(SELECT s1.id as s1_id, s2.id as s2_id, st_distance(transform(s1.location, 32614), transform(s2.location, 32614)) as dist " +
- "FROM stop as s1, stop as s2 WHERE s1.agency_id = s2.agency_id and s1.agency_id = ?) AS calcdist WHERE dist < 15 and dist > 0;");
+ "FROM stop as s1, stop as s2 WHERE s1.agency_id = s2.agency_id and s1.agency_id = ? and s1.id != s2.id) AS calcdist WHERE dist < 15;");
q.setParameter(1, agencyId);
List<Object[]> pairsResults = q.getResultList();
ArrayList<List<Stop>> stopPairs = new ArrayList<List<Stop>>();
for(Object[] cols : pairsResults) {
Stop s1 = Stop.findById(((BigInteger)cols[0]).longValue());
Stop s2 = Stop.findById(((BigInteger)cols[1]).longValue());
if(s1 != null && s2 != null) {
List<Stop> pair = new ArrayList<Stop>();
pair.add(s1);
pair.add(s2);
stopPairs.add(pair);
}
}
return stopPairs;
}
public Set<Route> routesServed()
{
List<TripPatternStop> stops = TripPatternStop.find("stop = ?", this).fetch();
HashSet<Route> routes = new HashSet<Route>();
for(TripPatternStop patternStop : stops)
{
if(patternStop.pattern == null)
continue;
if(patternStop.pattern.longest != null && patternStop.pattern.longest == true)
routes.add(patternStop.pattern.route);
}
return routes;
}
public Set<TripPattern> tripPatternsServed(Boolean weekday, Boolean saturday, Boolean sunday)
{
List<TripPatternStop> stops = TripPatternStop.find("stop = ?", this).fetch();
HashSet<TripPattern> patterns = new HashSet<TripPattern>();
for(TripPatternStop patternStop : stops)
{
if(patternStop.pattern == null)
continue;
if(patternStop.pattern.longest == true)
{
if((weekday && patternStop.pattern.weekday) || (saturday && patternStop.pattern.saturday) || (sunday && patternStop.pattern.sunday))
patterns.add(patternStop.pattern);
}
}
return patterns;
}
}
| true | true | public static List<List<Stop>> findDuplicateStops(BigInteger agencyId) {
// !!! need to autodetect proper SRID for UTM Zone
Query q = Stop.em().createNativeQuery("SELECT s1_id, s2_id, dist FROM " +
"(SELECT s1.id as s1_id, s2.id as s2_id, st_distance(transform(s1.location, 32614), transform(s2.location, 32614)) as dist " +
"FROM stop as s1, stop as s2 WHERE s1.agency_id = s2.agency_id and s1.agency_id = ?) AS calcdist WHERE dist < 15 and dist > 0;");
q.setParameter(1, agencyId);
List<Object[]> pairsResults = q.getResultList();
ArrayList<List<Stop>> stopPairs = new ArrayList<List<Stop>>();
for(Object[] cols : pairsResults) {
Stop s1 = Stop.findById(((BigInteger)cols[0]).longValue());
Stop s2 = Stop.findById(((BigInteger)cols[1]).longValue());
if(s1 != null && s2 != null) {
List<Stop> pair = new ArrayList<Stop>();
pair.add(s1);
pair.add(s2);
stopPairs.add(pair);
}
}
return stopPairs;
}
| public static List<List<Stop>> findDuplicateStops(BigInteger agencyId) {
// !!! need to autodetect proper SRID for UTM Zone
Query q = Stop.em().createNativeQuery("SELECT s1_id, s2_id, dist FROM " +
"(SELECT s1.id as s1_id, s2.id as s2_id, st_distance(transform(s1.location, 32614), transform(s2.location, 32614)) as dist " +
"FROM stop as s1, stop as s2 WHERE s1.agency_id = s2.agency_id and s1.agency_id = ? and s1.id != s2.id) AS calcdist WHERE dist < 15;");
q.setParameter(1, agencyId);
List<Object[]> pairsResults = q.getResultList();
ArrayList<List<Stop>> stopPairs = new ArrayList<List<Stop>>();
for(Object[] cols : pairsResults) {
Stop s1 = Stop.findById(((BigInteger)cols[0]).longValue());
Stop s2 = Stop.findById(((BigInteger)cols[1]).longValue());
if(s1 != null && s2 != null) {
List<Stop> pair = new ArrayList<Stop>();
pair.add(s1);
pair.add(s2);
stopPairs.add(pair);
}
}
return stopPairs;
}
|
diff --git a/src/admin/panel/general/GeneralPanel.java b/src/admin/panel/general/GeneralPanel.java
index 68b94c0..75823b1 100644
--- a/src/admin/panel/general/GeneralPanel.java
+++ b/src/admin/panel/general/GeneralPanel.java
@@ -1,502 +1,503 @@
package admin.panel.general;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableModel;
import admin.MainFrame;
import admin.Utils;
import data.GameData;
import data.GameData.UpdateTag;
import data.Person;
import data.User;
public class GeneralPanel extends JPanel implements Observer {
private static final long serialVersionUID = 1L;
Integer viewWeek = 0;
String winnerString = "";
private JLabel lblWeek;
private JTextField tfTribe1;
private JTextField tfTribe2;
private JButton btnStartSn;
private JButton btnAdvWk;
private JButton btnChangeTribeName;
private SpinnerNumberModel weekModel; // default,low,min,step
private JSpinner spnWeek;
private JPanel pnlRemCons;
private JPanel pnlCastOffs;
private JPanel pnlTribes;
private JPanel pnlWinners;
private TribeWinnerCont contTribeWin;
private JPanel pnlWeekCtrl;
private JPanel pnlHistory;
private JPanel pnlCenter;
private JLabel lblTribe1;
private JLabel lblTribe2;
private JTable activeTable;
private JTable castTable;
protected static final String TOOL_START = "Start the Season",
TOOL_ADV = "Advance the Season week",
TOOL_FIN_ADV = "Advance the final week",
TOOL_TRIBE = "Change the tribe names",
TOOL_WKSPINNER = "Scroll through the weeks";
public GeneralPanel() {
setLayout(new BorderLayout(10, 10));
pnlTribes = buildTribePanel();
pnlWinners = buildWinnerPanel();
contTribeWin = new TribeWinnerCont(pnlTribes, pnlWinners, true);
pnlWeekCtrl = buildCtrlPanel();
pnlHistory = buildHistory();
pnlCenter = new JPanel();
pnlCenter.setLayout(new BoxLayout(pnlCenter, BoxLayout.PAGE_AXIS));
JPanel subFrame = new JPanel();
subFrame.setLayout(new GridLayout(1, 2, 10, 5));
subFrame.add(pnlWeekCtrl);
subFrame.add(contTribeWin);
pnlCenter.add(subFrame);
pnlCenter.add(Box.createVerticalStrut(10));
pnlCenter.add(pnlHistory);
add(pnlCenter, BorderLayout.CENTER);
GameData.getCurrentGame().addObserver(this);
setToolTips();
GameData g = GameData.getCurrentGame();
if (g.isSeasonEnded()) { // game end
update(GameData.getCurrentGame(), EnumSet.of(UpdateTag.END_GAME));
} else if (g.isFinalWeek()) { // final week
update(GameData.getCurrentGame(), EnumSet.of(UpdateTag.FINAL_WEEK));
} else if (g.isSeasonStarted()){
update(GameData.getCurrentGame(), EnumSet.of(UpdateTag.START_SEASON));
}
initListeners();
}
/**
* Sets the tool tips for all the components.
*/
protected void setToolTips() {
if (GameData.getCurrentGame().isFinalWeek())
btnAdvWk.setToolTipText(TOOL_ADV);
else
btnAdvWk.setToolTipText(TOOL_FIN_ADV);
btnStartSn.setToolTipText(TOOL_START);
btnChangeTribeName.setToolTipText(TOOL_TRIBE);
spnWeek.setToolTipText(TOOL_WKSPINNER);
tfTribe1.setToolTipText(TOOL_TRIBE);
tfTribe2.setToolTipText(TOOL_TRIBE);
lblTribe1.setToolTipText(TOOL_TRIBE);
lblTribe2.setToolTipText(TOOL_TRIBE);
}
private JPanel buildTribePanel() {
GameData g = GameData.getCurrentGame();
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
lblTribe1 = new JLabel("Tribe 1:");
lblTribe2 = new JLabel("Tribe 2:");
tfTribe1 = new JTextField();
tfTribe2 = new JTextField();
btnChangeTribeName = new JButton("Save Tribes");
List<JLabel> lbls = Arrays.asList(lblTribe1, lblTribe2);
List<JTextField> tfs = Arrays.asList(tfTribe1, tfTribe2);
String[] tribes = g.getTribeNames();
for (int i = 0; i < 2; i++) {
tfs.get(i).setText(tribes[i]);
JPanel tPane = new JPanel();
tPane.setLayout(new BoxLayout(tPane, BoxLayout.LINE_AXIS));
tPane.add(lbls.get(i));
tPane.add(Box.createHorizontalStrut(5));
tPane.add(Box.createHorizontalGlue());
tPane.add(tfs.get(i));
pane.add(tPane);
pane.add(Box.createVerticalGlue());
}
btnChangeTribeName.setAlignmentX(JButton.RIGHT_ALIGNMENT);
pane.add(btnChangeTribeName);
return pane;
}
protected JPanel buildWinnerPanel() {
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout(5, 5));
JLabel stubLabel = new JLabel(winnerString);
pane.add(stubLabel, BorderLayout.CENTER);
return pane;
}
private JPanel buildCtrlPanel() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.setBorder(BorderFactory.createTitledBorder("Time"));
btnStartSn = new JButton("Start Season");
btnStartSn.setAlignmentX(JButton.CENTER_ALIGNMENT);
btnAdvWk = new JButton(getAdvWkString());
btnAdvWk.setAlignmentX(JButton.CENTER_ALIGNMENT);
btnStartSn.setPreferredSize(btnAdvWk.getPreferredSize());
// put into the panel
pane.add(Box.createVerticalGlue());
pane.add(btnStartSn);
pane.add(Box.createVerticalStrut(10));
pane.add(btnAdvWk);
pane.add(Box.createVerticalGlue());
// / init:
GameData g = GameData.getCurrentGame();
btnStartSn.setEnabled(!g.isSeasonStarted());
btnAdvWk.setEnabled(g.isSeasonStarted() && !g.isSeasonEnded());
return pane;
}
private JPanel buildHistory() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
pane.setBorder(BorderFactory.createTitledBorder("History"));
// / spinnner stuff
JPanel pnlSpin = new JPanel();
pnlSpin.setLayout(new BoxLayout(pnlSpin, BoxLayout.LINE_AXIS));
lblWeek = new JLabel("View Week:");
lblWeek.setAlignmentX(JLabel.LEFT_ALIGNMENT);
weekModel = new SpinnerNumberModel();
spnWeek = new JSpinner(weekModel);
spnWeek.setAlignmentX(JSpinner.LEFT_ALIGNMENT);
spnWeek.setEnabled(false);
pnlSpin.add(lblWeek);
pnlSpin.add(Box.createHorizontalStrut(10));
pnlSpin.add(spnWeek);
pnlSpin.add(Box.createHorizontalGlue());
// / panels
JPanel pnlCont = new JPanel();
pnlCont.setLayout(new GridLayout(1, 2, 10, 5));
buildHistoryTables();
pnlCont.add(pnlRemCons);
pnlCont.add(pnlCastOffs);
// put all together:
pane.add(pnlSpin);
pane.add(pnlCont);
/// init:
GameData g = GameData.getCurrentGame();
if (g.isSeasonStarted()) {
updateSpinnerModel(g.getCurrentWeek());
spnWeek.setValue(g.getCurrentWeek());
}
return pane;
}
private void buildHistoryTables() {
// build the encapsulating panels:
final Border bevB = BorderFactory
.createSoftBevelBorder(BevelBorder.LOWERED);
final Dimension displaySize = new Dimension(150, 200);
pnlRemCons = new JPanel();
pnlRemCons.setBorder(BorderFactory.createTitledBorder(bevB,
"Contestants"));
pnlRemCons.setPreferredSize(displaySize);
pnlCastOffs = new JPanel();
pnlCastOffs.setBorder(BorderFactory.createTitledBorder(bevB,
"Cast Offs"));
pnlCastOffs.setPreferredSize(displaySize);
// Tables:
activeTable = new JTable();
TableModel model = new HistoryConModel(activeTable, false);
activeTable.setModel(model);
castTable = new JTable();
model = new HistoryConModel(castTable, true);
castTable.setModel(model);
List<JTable> tables = Arrays.asList(activeTable, castTable);
List<JPanel> panes = Arrays.asList(pnlRemCons, pnlCastOffs);
for (int i = 0; i < 2; i++) {
JTable table = tables.get(i);
JPanel pane = panes.get(i);
table.getTableHeader().setReorderingAllowed(false); // no moving.
table.setColumnSelectionAllowed(true);
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setDefaultRenderer(Object.class, Utils.buildDefaultRenderer());
JScrollPane scroll = new JScrollPane(table);
pane.setLayout(new BorderLayout(5, 5));
pane.add(scroll, BorderLayout.CENTER);
}
}
private String getAdvWkString(){
GameData g = GameData.getCurrentGame();
String s = "Advance to Week";
if(g!=null){
if(g.isSeasonEnded())
s="Advance Week";
else
s += " "+g.getCurrentWeek();
}
return s;
}
private void initListeners() {
btnStartSn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.getAllContestants().size() == 0) {
JOptionPane
.showMessageDialog(null,
"This will be a boring game with no contestants. Add some!");
return;
}
if (g.getAllContestants().size() != g.getInitialContestants()) {
JOptionPane.showMessageDialog(null,
"You need to have " + g.getInitialContestants()
+ " contestants to start.");
return;
} else if (!g.isSeasonStarted()) {
String s = JOptionPane.showInputDialog("Enter weekly bet" +
" amount!");
if (Utils.checkString(s, "^[0-9]+$")) {
int t = Integer.parseInt(s);
if (t >= 0) {
g.startSeason(t);
+ btnStartSn.setText("Season started. Bet amount is $"+t);
}
return;
}
JOptionPane.showMessageDialog(null,
"Invalid amount entered.");
}
}
});
btnAdvWk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.isSeasonEnded()) { // if end of game
return;
}
if (!g.doesElimExist()) {
if (g.isFinalWeek()) {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be the winner.");
} else {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be cast off.");
}
} else {
g.advanceWeek();
btnAdvWk.setText(getAdvWkString());
}
}
});
btnChangeTribeName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
MainFrame mf = MainFrame.getRunningFrame();
if (!Utils.checkString(tfTribe1.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 1 name invalid.", tfTribe1);
} else if (!Utils.checkString(tfTribe2.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 2 name invalid.", tfTribe2);
} else if (tfTribe1.getText().equals(tfTribe2.getText())) {
mf.setStatusErrorMsg(
"Invalid tribe names, cannot be the same",
tfTribe1, tfTribe2);
return;
} else {
String[] txts = GameData.getCurrentGame().setTribeNames(
tfTribe1.getText(), tfTribe2.getText());
tfTribe1.setText(txts[0]);
tfTribe2.setText(txts[1]);
}
}
});
spnWeek.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
int w = (Integer)spnWeek.getValue();
((HistoryConModel)activeTable.getModel()).loadContestantByWeek(w);
((HistoryConModel)castTable.getModel()).loadContestantByWeek(w);
}
});
}
private void updateSpinnerModel(int w) {
weekModel.setMinimum(w > 0 ? 0 : 0);
weekModel.setMaximum(w-1 > 0 ? w-1 : 0);
weekModel.setStepSize(1);
}
@Override
public void update(Observable obs, Object arg) {
@SuppressWarnings("unchecked")
EnumSet<UpdateTag> update = (EnumSet<UpdateTag>) arg;
GameData g = (GameData) obs;
if (update.contains(UpdateTag.START_SEASON)) {
btnStartSn.setEnabled(false);
btnAdvWk.setEnabled(true);
spnWeek.setEnabled(true);
}
if (update.contains(UpdateTag.ADVANCE_WEEK)) {
// TODO: What should happen here?
btnAdvWk.setEnabled(true);
}
if (update.contains(UpdateTag.FINAL_WEEK)) {
// TODO: now its the final week:
btnAdvWk.setEnabled(true);
btnAdvWk.setText("Advance Final Week");
}
if (update.contains(UpdateTag.ADVANCE_WEEK)
|| update.contains(UpdateTag.FINAL_WEEK)
|| update.contains(UpdateTag.START_SEASON)
|| update.contains(UpdateTag.END_GAME)) {
updateSpinnerModel(g.getCurrentWeek());
}
if (update.contains(UpdateTag.END_GAME)) {
btnStartSn.setText("End of Season");
btnAdvWk.setEnabled(false);
User tempUser;
List<User> winners = g.determineWinners();
List<Integer> pool = g.determinePrizePool();
JTextArea winnerText = new JTextArea("");
winnerText.setEditable(false);
String tempString = "";
for (int i = 0; i<winners.size(); i++){
tempUser = (User) winners.get(i); // grab user
// build user's line
tempString = tempString + (i+1) + ". " + tempUser.getFirstName()
+ " " + tempUser.getLastName() + " - "
+ tempUser.getPoints() + "pts - $" + pool.get(i) + "\n";
}
// place user's line in the jtext area
winnerText.setText(tempString);
// place the textarea into the panel
pnlWinners.add(winnerText);
// show the winning panel
contTribeWin.showWinners();
}
if (update.contains(UpdateTag.ADVANCE_WEEK)) {
spnWeek.setValue(g.getCurrentWeek()-1);
}
}
}
| true | true | private void initListeners() {
btnStartSn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.getAllContestants().size() == 0) {
JOptionPane
.showMessageDialog(null,
"This will be a boring game with no contestants. Add some!");
return;
}
if (g.getAllContestants().size() != g.getInitialContestants()) {
JOptionPane.showMessageDialog(null,
"You need to have " + g.getInitialContestants()
+ " contestants to start.");
return;
} else if (!g.isSeasonStarted()) {
String s = JOptionPane.showInputDialog("Enter weekly bet" +
" amount!");
if (Utils.checkString(s, "^[0-9]+$")) {
int t = Integer.parseInt(s);
if (t >= 0) {
g.startSeason(t);
}
return;
}
JOptionPane.showMessageDialog(null,
"Invalid amount entered.");
}
}
});
btnAdvWk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.isSeasonEnded()) { // if end of game
return;
}
if (!g.doesElimExist()) {
if (g.isFinalWeek()) {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be the winner.");
} else {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be cast off.");
}
} else {
g.advanceWeek();
btnAdvWk.setText(getAdvWkString());
}
}
});
btnChangeTribeName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
MainFrame mf = MainFrame.getRunningFrame();
if (!Utils.checkString(tfTribe1.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 1 name invalid.", tfTribe1);
} else if (!Utils.checkString(tfTribe2.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 2 name invalid.", tfTribe2);
} else if (tfTribe1.getText().equals(tfTribe2.getText())) {
mf.setStatusErrorMsg(
"Invalid tribe names, cannot be the same",
tfTribe1, tfTribe2);
return;
} else {
String[] txts = GameData.getCurrentGame().setTribeNames(
tfTribe1.getText(), tfTribe2.getText());
tfTribe1.setText(txts[0]);
tfTribe2.setText(txts[1]);
}
}
});
spnWeek.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
int w = (Integer)spnWeek.getValue();
((HistoryConModel)activeTable.getModel()).loadContestantByWeek(w);
((HistoryConModel)castTable.getModel()).loadContestantByWeek(w);
}
});
}
| private void initListeners() {
btnStartSn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.getAllContestants().size() == 0) {
JOptionPane
.showMessageDialog(null,
"This will be a boring game with no contestants. Add some!");
return;
}
if (g.getAllContestants().size() != g.getInitialContestants()) {
JOptionPane.showMessageDialog(null,
"You need to have " + g.getInitialContestants()
+ " contestants to start.");
return;
} else if (!g.isSeasonStarted()) {
String s = JOptionPane.showInputDialog("Enter weekly bet" +
" amount!");
if (Utils.checkString(s, "^[0-9]+$")) {
int t = Integer.parseInt(s);
if (t >= 0) {
g.startSeason(t);
btnStartSn.setText("Season started. Bet amount is $"+t);
}
return;
}
JOptionPane.showMessageDialog(null,
"Invalid amount entered.");
}
}
});
btnAdvWk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
GameData g = GameData.getCurrentGame();
if (g.isSeasonEnded()) { // if end of game
return;
}
if (!g.doesElimExist()) {
if (g.isFinalWeek()) {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be the winner.");
} else {
JOptionPane
.showMessageDialog(null,
"No Contestant has been selected to be cast off.");
}
} else {
g.advanceWeek();
btnAdvWk.setText(getAdvWkString());
}
}
});
btnChangeTribeName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
MainFrame mf = MainFrame.getRunningFrame();
if (!Utils.checkString(tfTribe1.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 1 name invalid.", tfTribe1);
} else if (!Utils.checkString(tfTribe2.getText(),
Person.TRIBE_PATTERN)) {
mf.setStatusErrorMsg("Tribe 2 name invalid.", tfTribe2);
} else if (tfTribe1.getText().equals(tfTribe2.getText())) {
mf.setStatusErrorMsg(
"Invalid tribe names, cannot be the same",
tfTribe1, tfTribe2);
return;
} else {
String[] txts = GameData.getCurrentGame().setTribeNames(
tfTribe1.getText(), tfTribe2.getText());
tfTribe1.setText(txts[0]);
tfTribe2.setText(txts[1]);
}
}
});
spnWeek.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent ce) {
int w = (Integer)spnWeek.getValue();
((HistoryConModel)activeTable.getModel()).loadContestantByWeek(w);
((HistoryConModel)castTable.getModel()).loadContestantByWeek(w);
}
});
}
|
diff --git a/src/java/org/jamwiki/utils/ImageUtil.java b/src/java/org/jamwiki/utils/ImageUtil.java
index 04b5948b..77607790 100644
--- a/src/java/org/jamwiki/utils/ImageUtil.java
+++ b/src/java/org/jamwiki/utils/ImageUtil.java
@@ -1,188 +1,188 @@
/**
* 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.utils;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.WikiImage;
import org.jamwiki.model.WikiFile;
import org.springframework.util.StringUtils;
/**
*
*/
public class ImageUtil {
private static final Logger logger = Logger.getLogger(ImageUtil.class);
/**
*
*/
public static int calculateImageIncrement(int maxDimension) {
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
double result = Math.ceil((double)maxDimension / (double)increment) * increment;
return (int)result;
}
/**
* Convert a Java Image object to a Java BufferedImage object.
*/
public static BufferedImage imageToBufferedImage(Image image) throws Exception {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB );
Graphics2D graphics = bufferedImage.createGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
return bufferedImage;
}
/**
* Given a virtualWiki and topicName that correspond to an existing image,
* return the WikiImage object. In addition, an optional maxDimension
* parameter may be specified, in which case a resized version of the image
* may be created.
*/
public static WikiImage initializeImage(String virtualWiki, String topicName, int maxDimension) throws Exception {
WikiFile wikiFile = WikiBase.getHandler().lookupWikiFile(virtualWiki, topicName);
if (wikiFile == null) {
logger.warn("No image found for " + virtualWiki + " / " + topicName);
return null;
}
WikiImage wikiImage = new WikiImage(wikiFile);
BufferedImage imageObject = null;
if (maxDimension > 0) {
imageObject = ImageUtil.resizeImage(wikiImage, maxDimension);
setScaledDimensions(imageObject, wikiImage, maxDimension);
} else {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
imageObject = ImageUtil.loadImage(imageFile);
wikiImage.setWidth(imageObject.getWidth());
wikiImage.setHeight(imageObject.getHeight());
}
return wikiImage;
}
/**
* Given a file that corresponds to an existing image, return a
* BufferedImage object.
*/
public static BufferedImage loadImage(File file) throws Exception {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
return ImageIO.read(fis);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {}
}
}
}
/**
* Resize an image, using a maximum dimension value. Image dimensions will
* be constrained so that the proportions are the same, but neither the width
* or height exceeds the value specified.
*/
public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
- if (increment < 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
+ if (increment <= 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
/**
* Save an image to a specified file.
*/
public static void saveImage(BufferedImage image, File file) throws Exception {
String filename = file.getName();
int pos = filename.lastIndexOf(".");
if (pos == -1 || (pos + 1) >= filename.length()) {
throw new Exception("Unknown image type " + filename);
}
String imageType = filename.substring(pos + 1);
File imageFile = new File(file.getParent(), filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
ImageIO.write(image, imageType, fos);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {}
}
}
}
/**
*
*/
private static void setScaledDimensions(BufferedImage bufferedImage, WikiImage wikiImage, int maxDimension) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (width >= height) {
height = (int)Math.floor(((double)maxDimension / (double)width) * (double)height);
width = maxDimension;
} else {
width = (int)Math.floor(((double)maxDimension / (double)height) * (double)width);
height = maxDimension;
}
wikiImage.setWidth(width);
wikiImage.setHeight(height);
}
}
| true | true | public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
if (increment < 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
| public static BufferedImage resizeImage(WikiImage wikiImage, int maxDimension) throws Exception {
File imageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), wikiImage.getUrl());
BufferedImage original = ImageUtil.loadImage(imageFile);
maxDimension = calculateImageIncrement(maxDimension);
int increment = Environment.getIntValue(Environment.PROP_IMAGE_RESIZE_INCREMENT);
if (increment <= 0 || (maxDimension > original.getWidth() && maxDimension > original.getHeight())) {
// let the browser scale the image
return original;
}
String newUrl = wikiImage.getUrl();
int pos = newUrl.lastIndexOf(".");
if (pos > -1) {
newUrl = newUrl.substring(0, pos) + "-" + maxDimension + "px" + newUrl.substring(pos);
} else {
newUrl += "-" + maxDimension + "px";
}
wikiImage.setUrl(newUrl);
File newImageFile = new File(Environment.getValue(Environment.PROP_FILE_DIR_FULL_PATH), newUrl);
if (newImageFile.exists()) {
return ImageUtil.loadImage(newImageFile);
}
int width = -1;
int height = -1;
if (original.getWidth() >= original.getHeight()) {
width = maxDimension;
} else {
height = maxDimension;
}
Image resized = original.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);
BufferedImage bufferedImage = null;
if (resized instanceof BufferedImage) {
bufferedImage = (BufferedImage)resized;
} else {
bufferedImage = ImageUtil.imageToBufferedImage(resized);
}
ImageUtil.saveImage(bufferedImage, newImageFile);
return bufferedImage;
}
|
diff --git a/src/main/java/net/sf/webdav/methods/DoProppatch.java b/src/main/java/net/sf/webdav/methods/DoProppatch.java
index 0caa3c1..afeaca7 100644
--- a/src/main/java/net/sf/webdav/methods/DoProppatch.java
+++ b/src/main/java/net/sf/webdav/methods/DoProppatch.java
@@ -1,226 +1,228 @@
package net.sf.webdav.methods;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import net.sf.webdav.ITransaction;
import net.sf.webdav.IWebdavStore;
import net.sf.webdav.StoredObject;
import net.sf.webdav.WebdavStatus;
import net.sf.webdav.exceptions.AccessDeniedException;
import net.sf.webdav.exceptions.LockFailedException;
import net.sf.webdav.exceptions.WebdavException;
import net.sf.webdav.fromcatalina.XMLHelper;
import net.sf.webdav.fromcatalina.XMLWriter;
import net.sf.webdav.locking.LockedObject;
import net.sf.webdav.locking.ResourceLocks;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
public class DoProppatch extends AbstractMethod {
private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory
.getLogger(DoProppatch.class);
private boolean _readOnly;
private IWebdavStore _store;
private ResourceLocks _resourceLocks;
public DoProppatch(IWebdavStore store, ResourceLocks resLocks,
boolean readOnly) {
_readOnly = readOnly;
_store = store;
_resourceLocks = resLocks;
}
public void execute(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
LOG.trace("-- " + this.getClass().getName());
if (_readOnly) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
String parentPath = getParentPath(getCleanPath(path));
Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
if (!checkLocks(transaction, req, resp, _resourceLocks, parentPath)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // parent is locked
}
if (!checkLocks(transaction, req, resp, _resourceLocks, path)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // resource is locked
}
// TODO for now, PROPPATCH just sends a valid response, stating that
// everything is fine, but doesn't do anything.
// Retrieve the resources
String tempLockOwner = "doProppatch" + System.currentTimeMillis()
+ req.toString();
if (_resourceLocks.lock(transaction, path, tempLockOwner, false, 0,
TEMP_TIMEOUT, TEMPORARY)) {
StoredObject so = null;
LockedObject lo = null;
try {
so = _store.getStoredObject(transaction, path);
lo = _resourceLocks.getLockedObjectByPath(transaction,
getCleanPath(path));
if (so == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
// we do not to continue since there is no root
// resource
}
if (so.isNullResource()) {
String methodsAllowed = DeterminableMethod
.determineMethodsAllowed(so);
resp.addHeader("Allow", methodsAllowed);
resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
return;
}
- if (lo != null && lo.isExclusive()) {
+ String[] lockTokens = getLockIdFromIfHeader(req);
+ boolean lockTokenMatchesIfHeader = (lockTokens != null && lockTokens[0].equals(lo.getID()));
+ if (lo != null && lo.isExclusive() && !lockTokenMatchesIfHeader) {
// Object on specified path is LOCKED
errorList = new Hashtable<String, Integer>();
errorList.put(path, new Integer(WebdavStatus.SC_LOCKED));
sendReport(req, resp, errorList);
return;
}
List<String> toset = null;
List<String> toremove = null;
List<String> tochange = new Vector<String>();
// contains all properties from
// toset and toremove
path = getCleanPath(getRelativePath(req));
Node tosetNode = null;
Node toremoveNode = null;
if (req.getContentLength() != 0) {
DocumentBuilder documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder
.parse(new InputSource(req.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
tosetNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "set"), "prop");
toremoveNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "remove"), "prop");
} catch (Exception e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
// no content: error
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
HashMap<String, String> namespaces = new HashMap<String, String>();
namespaces.put("DAV:", "D");
if (tosetNode != null) {
toset = XMLHelper.getPropertiesFromXML(tosetNode);
tochange.addAll(toset);
}
if (toremoveNode != null) {
toremove = XMLHelper.getPropertiesFromXML(toremoveNode);
tochange.addAll(toremove);
}
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter(),
namespaces);
generatedXML.writeXMLHeader();
generatedXML
.writeElement("DAV::multistatus", XMLWriter.OPENING);
generatedXML.writeElement("DAV::response", XMLWriter.OPENING);
String status = new String("HTTP/1.1 " + WebdavStatus.SC_OK
+ " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK));
// Generating href element
generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
String href = req.getContextPath();
if ((href.endsWith("/")) && (path.startsWith("/")))
href += path.substring(1);
else
href += path;
if ((so.isFolder()) && (!href.endsWith("/")))
href += "/";
generatedXML.writeText(rewriteUrl(href));
generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
for (Iterator<String> iter = tochange.iterator(); iter
.hasNext();) {
String property = (String) iter.next();
generatedXML.writeElement("DAV::propstat",
XMLWriter.OPENING);
generatedXML.writeElement("DAV::prop", XMLWriter.OPENING);
generatedXML.writeElement(property, XMLWriter.NO_CONTENT);
generatedXML.writeElement("DAV::prop", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::status", XMLWriter.OPENING);
generatedXML.writeText(status);
generatedXML.writeElement("DAV::status", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::propstat",
XMLWriter.CLOSING);
}
generatedXML.writeElement("DAV::response", XMLWriter.CLOSING);
generatedXML
.writeElement("DAV::multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
} catch (AccessDeniedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
} catch (WebdavException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
} catch (ServletException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
} finally {
_resourceLocks.unlockTemporaryLockedObjects(transaction, path,
tempLockOwner);
}
} else {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
}
}
}
| true | true | public void execute(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
LOG.trace("-- " + this.getClass().getName());
if (_readOnly) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
String parentPath = getParentPath(getCleanPath(path));
Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
if (!checkLocks(transaction, req, resp, _resourceLocks, parentPath)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // parent is locked
}
if (!checkLocks(transaction, req, resp, _resourceLocks, path)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // resource is locked
}
// TODO for now, PROPPATCH just sends a valid response, stating that
// everything is fine, but doesn't do anything.
// Retrieve the resources
String tempLockOwner = "doProppatch" + System.currentTimeMillis()
+ req.toString();
if (_resourceLocks.lock(transaction, path, tempLockOwner, false, 0,
TEMP_TIMEOUT, TEMPORARY)) {
StoredObject so = null;
LockedObject lo = null;
try {
so = _store.getStoredObject(transaction, path);
lo = _resourceLocks.getLockedObjectByPath(transaction,
getCleanPath(path));
if (so == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
// we do not to continue since there is no root
// resource
}
if (so.isNullResource()) {
String methodsAllowed = DeterminableMethod
.determineMethodsAllowed(so);
resp.addHeader("Allow", methodsAllowed);
resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
return;
}
if (lo != null && lo.isExclusive()) {
// Object on specified path is LOCKED
errorList = new Hashtable<String, Integer>();
errorList.put(path, new Integer(WebdavStatus.SC_LOCKED));
sendReport(req, resp, errorList);
return;
}
List<String> toset = null;
List<String> toremove = null;
List<String> tochange = new Vector<String>();
// contains all properties from
// toset and toremove
path = getCleanPath(getRelativePath(req));
Node tosetNode = null;
Node toremoveNode = null;
if (req.getContentLength() != 0) {
DocumentBuilder documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder
.parse(new InputSource(req.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
tosetNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "set"), "prop");
toremoveNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "remove"), "prop");
} catch (Exception e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
// no content: error
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
HashMap<String, String> namespaces = new HashMap<String, String>();
namespaces.put("DAV:", "D");
if (tosetNode != null) {
toset = XMLHelper.getPropertiesFromXML(tosetNode);
tochange.addAll(toset);
}
if (toremoveNode != null) {
toremove = XMLHelper.getPropertiesFromXML(toremoveNode);
tochange.addAll(toremove);
}
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter(),
namespaces);
generatedXML.writeXMLHeader();
generatedXML
.writeElement("DAV::multistatus", XMLWriter.OPENING);
generatedXML.writeElement("DAV::response", XMLWriter.OPENING);
String status = new String("HTTP/1.1 " + WebdavStatus.SC_OK
+ " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK));
// Generating href element
generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
String href = req.getContextPath();
if ((href.endsWith("/")) && (path.startsWith("/")))
href += path.substring(1);
else
href += path;
if ((so.isFolder()) && (!href.endsWith("/")))
href += "/";
generatedXML.writeText(rewriteUrl(href));
generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
for (Iterator<String> iter = tochange.iterator(); iter
.hasNext();) {
String property = (String) iter.next();
generatedXML.writeElement("DAV::propstat",
XMLWriter.OPENING);
generatedXML.writeElement("DAV::prop", XMLWriter.OPENING);
generatedXML.writeElement(property, XMLWriter.NO_CONTENT);
generatedXML.writeElement("DAV::prop", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::status", XMLWriter.OPENING);
generatedXML.writeText(status);
generatedXML.writeElement("DAV::status", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::propstat",
XMLWriter.CLOSING);
}
generatedXML.writeElement("DAV::response", XMLWriter.CLOSING);
generatedXML
.writeElement("DAV::multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
} catch (AccessDeniedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
} catch (WebdavException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
} catch (ServletException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
} finally {
_resourceLocks.unlockTemporaryLockedObjects(transaction, path,
tempLockOwner);
}
} else {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
}
}
| public void execute(ITransaction transaction, HttpServletRequest req,
HttpServletResponse resp) throws IOException, LockFailedException {
LOG.trace("-- " + this.getClass().getName());
if (_readOnly) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
return;
}
String path = getRelativePath(req);
String parentPath = getParentPath(getCleanPath(path));
Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();
if (!checkLocks(transaction, req, resp, _resourceLocks, parentPath)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // parent is locked
}
if (!checkLocks(transaction, req, resp, _resourceLocks, path)) {
resp.setStatus(WebdavStatus.SC_LOCKED);
return; // resource is locked
}
// TODO for now, PROPPATCH just sends a valid response, stating that
// everything is fine, but doesn't do anything.
// Retrieve the resources
String tempLockOwner = "doProppatch" + System.currentTimeMillis()
+ req.toString();
if (_resourceLocks.lock(transaction, path, tempLockOwner, false, 0,
TEMP_TIMEOUT, TEMPORARY)) {
StoredObject so = null;
LockedObject lo = null;
try {
so = _store.getStoredObject(transaction, path);
lo = _resourceLocks.getLockedObjectByPath(transaction,
getCleanPath(path));
if (so == null) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
// we do not to continue since there is no root
// resource
}
if (so.isNullResource()) {
String methodsAllowed = DeterminableMethod
.determineMethodsAllowed(so);
resp.addHeader("Allow", methodsAllowed);
resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED);
return;
}
String[] lockTokens = getLockIdFromIfHeader(req);
boolean lockTokenMatchesIfHeader = (lockTokens != null && lockTokens[0].equals(lo.getID()));
if (lo != null && lo.isExclusive() && !lockTokenMatchesIfHeader) {
// Object on specified path is LOCKED
errorList = new Hashtable<String, Integer>();
errorList.put(path, new Integer(WebdavStatus.SC_LOCKED));
sendReport(req, resp, errorList);
return;
}
List<String> toset = null;
List<String> toremove = null;
List<String> tochange = new Vector<String>();
// contains all properties from
// toset and toremove
path = getCleanPath(getRelativePath(req));
Node tosetNode = null;
Node toremoveNode = null;
if (req.getContentLength() != 0) {
DocumentBuilder documentBuilder = getDocumentBuilder();
try {
Document document = documentBuilder
.parse(new InputSource(req.getInputStream()));
// Get the root element of the document
Element rootElement = document.getDocumentElement();
tosetNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "set"), "prop");
toremoveNode = XMLHelper.findSubElement(XMLHelper
.findSubElement(rootElement, "remove"), "prop");
} catch (Exception e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
} else {
// no content: error
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
return;
}
HashMap<String, String> namespaces = new HashMap<String, String>();
namespaces.put("DAV:", "D");
if (tosetNode != null) {
toset = XMLHelper.getPropertiesFromXML(tosetNode);
tochange.addAll(toset);
}
if (toremoveNode != null) {
toremove = XMLHelper.getPropertiesFromXML(toremoveNode);
tochange.addAll(toremove);
}
resp.setStatus(WebdavStatus.SC_MULTI_STATUS);
resp.setContentType("text/xml; charset=UTF-8");
// Create multistatus object
XMLWriter generatedXML = new XMLWriter(resp.getWriter(),
namespaces);
generatedXML.writeXMLHeader();
generatedXML
.writeElement("DAV::multistatus", XMLWriter.OPENING);
generatedXML.writeElement("DAV::response", XMLWriter.OPENING);
String status = new String("HTTP/1.1 " + WebdavStatus.SC_OK
+ " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK));
// Generating href element
generatedXML.writeElement("DAV::href", XMLWriter.OPENING);
String href = req.getContextPath();
if ((href.endsWith("/")) && (path.startsWith("/")))
href += path.substring(1);
else
href += path;
if ((so.isFolder()) && (!href.endsWith("/")))
href += "/";
generatedXML.writeText(rewriteUrl(href));
generatedXML.writeElement("DAV::href", XMLWriter.CLOSING);
for (Iterator<String> iter = tochange.iterator(); iter
.hasNext();) {
String property = (String) iter.next();
generatedXML.writeElement("DAV::propstat",
XMLWriter.OPENING);
generatedXML.writeElement("DAV::prop", XMLWriter.OPENING);
generatedXML.writeElement(property, XMLWriter.NO_CONTENT);
generatedXML.writeElement("DAV::prop", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::status", XMLWriter.OPENING);
generatedXML.writeText(status);
generatedXML.writeElement("DAV::status", XMLWriter.CLOSING);
generatedXML.writeElement("DAV::propstat",
XMLWriter.CLOSING);
}
generatedXML.writeElement("DAV::response", XMLWriter.CLOSING);
generatedXML
.writeElement("DAV::multistatus", XMLWriter.CLOSING);
generatedXML.sendData();
} catch (AccessDeniedException e) {
resp.sendError(WebdavStatus.SC_FORBIDDEN);
} catch (WebdavException e) {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
} catch (ServletException e) {
e.printStackTrace(); // To change body of catch statement use
// File | Settings | File Templates.
} finally {
_resourceLocks.unlockTemporaryLockedObjects(transaction, path,
tempLockOwner);
}
} else {
resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
}
}
|
diff --git a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
index 7eabea2..0ac03ce 100644
--- a/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
+++ b/JsTestDriver/src/com/google/jstestdriver/ConfigurationParser.java
@@ -1,178 +1,178 @@
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.jstestdriver;
import com.google.common.collect.Lists;
import org.apache.oro.io.GlobFilenameFilter;
import org.apache.oro.text.GlobCompiler;
import org.jvyaml.YAML;
import java.io.File;
import java.io.Reader;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* TODO: needs to give more feedback when something goes wrong...
*
* @author jeremiele@google.com (Jeremie Lenfant-Engelmann)
*/
public class ConfigurationParser {
private static final List<String> EMPTY_LIST = Lists.newArrayList();
private final Set<FileInfo> filesList = new LinkedHashSet<FileInfo>();
private final File basePath;
private final Reader configReader;
private final PathRewriter pathRewriter;
private String server = "";
private List<Plugin> plugins = new LinkedList<Plugin>();
private PathResolver pathResolver = new PathResolver();
public ConfigurationParser(File basePath, Reader configReader, PathRewriter pathRewriter) {
this.basePath = basePath;
this.configReader = configReader;
this.pathRewriter = pathRewriter;
}
@SuppressWarnings("unchecked")
public void parse() {
Map<Object, Object> data = (Map<Object, Object>) YAML.load(configReader);
Set<FileInfo> resolvedFilesLoad = new LinkedHashSet<FileInfo>();
Set<FileInfo> resolvedFilesExclude = new LinkedHashSet<FileInfo>();
if (data.containsKey("load")) {
resolvedFilesLoad.addAll(resolveFiles((List<String>) data.get("load"), false));
}
if (data.containsKey("exclude")) {
resolvedFilesExclude.addAll(resolveFiles((List<String>) data.get("exclude"), false));
}
if (data.containsKey("server")) {
this.server = (String) data.get("server");
}
if (data.containsKey("plugin")) {
for (Map<String, String> value: (List<Map<String, String>>) data.get("plugin")) {
plugins.add(new Plugin(value.get("name"), value.get("jar"), value.get("module"),
createArgsList(value.get("args"))));
}
}
if (data.containsKey("serve")) {
Set<FileInfo> resolvedServeFiles = resolveFiles((List<String>) data.get("serve"), true);
resolvedFilesLoad.addAll(resolvedServeFiles);
}
filesList.addAll(consolidatePatches(resolvedFilesLoad));
filesList.removeAll(resolvedFilesExclude);
}
private List<String> createArgsList(String args) {
if (args == null) {
return EMPTY_LIST;
}
List<String> argsList = Lists.newLinkedList();
String[] splittedArgs = args.split(",");
for (String arg : splittedArgs) {
argsList.add(arg.trim());
}
return argsList;
}
private Set<FileInfo> consolidatePatches(Set<FileInfo> resolvedFilesLoad) {
Set<FileInfo> consolidated = new LinkedHashSet<FileInfo>(resolvedFilesLoad.size());
FileInfo currentNonPatch = null;
for (FileInfo fileInfo : resolvedFilesLoad) {
if (fileInfo.isPatch()) {
if (currentNonPatch == null) {
throw new IllegalStateException("Patch " + fileInfo + " without a core file to patch");
}
currentNonPatch.addPatch(fileInfo);
} else {
consolidated.add(fileInfo);
currentNonPatch = fileInfo;
}
}
return consolidated;
}
private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
- File file = basePath != null ? new File(basePath, f) : new File(f);
+ File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
public Set<FileInfo> getFilesList() {
return filesList;
}
public String getServer() {
return server;
}
public List<Plugin> getPlugins() {
return plugins;
}
}
| true | true | private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
File file = basePath != null ? new File(basePath, f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
| private Set<FileInfo> resolveFiles(List<String> files, boolean serveOnly) {
if (files != null) {
Set<FileInfo> resolvedFiles = new LinkedHashSet<FileInfo>();
for (String f : files) {
f = pathRewriter.rewrite(f);
boolean isPatch = f.startsWith("patch");
if (isPatch) {
String[] tokens = f.split(" ", 2);
f = tokens[1].trim();
}
if (f.startsWith("http://") || f.startsWith("https://")) {
resolvedFiles.add(new FileInfo(f, -1, false, false, null));
} else {
File file = basePath != null ? new File(basePath.getAbsoluteFile(), f) : new File(f);
File testFile = file.getAbsoluteFile();
File dir = testFile.getParentFile().getAbsoluteFile();
final String pattern = file.getName();
String[] filteredFiles = dir.list(new GlobFilenameFilter(pattern,
GlobCompiler.DEFAULT_MASK | GlobCompiler.CASE_INSENSITIVE_MASK));
if (filteredFiles == null || filteredFiles.length == 0) {
String error = "The patterns/paths " + f + " used in the configuration"
+ " file didn't match any file, the files patterns/paths need to be relative to"
+ " the configuration file.";
System.err.println(error);
throw new RuntimeException(error);
}
Arrays.sort(filteredFiles, String.CASE_INSENSITIVE_ORDER);
for (String filteredFile : filteredFiles) {
String resolvedFilePath =
pathResolver.resolvePath(dir.getAbsolutePath().replaceAll("\\\\", "/") + "/"
+ filteredFile.replaceAll("\\\\", "/"));
File resolvedFile = new File(resolvedFilePath);
resolvedFiles.add(new FileInfo(resolvedFilePath, resolvedFile.lastModified(), isPatch,
serveOnly, null));
}
}
}
return resolvedFiles;
}
return Collections.emptySet();
}
|
diff --git a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
index 66c591ded9..8030b4601d 100644
--- a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
+++ b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/CopyMojo.java
@@ -1,121 +1,121 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.maven;
import static org.apache.commons.io.FileUtils.copyFile;
import java.io.File;
import java.io.IOException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
/**
* @goal copy
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class CopyMojo extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* @parameter
*/
private Copy[] files;
public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
- if ( !to.getParentFile().mkdirs() ) {
+ if ( !to.getParentFile().isDirectory() && !to.getParentFile().mkdirs() ) {
log.warn( "Could not create parent directories for " + to + "." );
continue;
}
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
/**
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public static class Copy {
/**
* @parameter
*/
String from;
/**
* @parameter
*/
String to;
@Override
public String toString() {
return from + " -> " + to;
}
}
}
| true | true | public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
if ( !to.getParentFile().mkdirs() ) {
log.warn( "Could not create parent directories for " + to + "." );
continue;
}
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
if ( files == null ) {
log.debug( "No files configured." );
return;
}
File basedir = project.getBasedir();
for ( Copy copy : files ) {
log.info( "Copy " + copy.from + " to " + copy.to );
File from = new File( basedir, copy.from );
File to = new File( basedir, copy.to );
if ( !to.getParentFile().isDirectory() && !to.getParentFile().mkdirs() ) {
log.warn( "Could not create parent directories for " + to + "." );
continue;
}
try {
copyFile( from, to );
} catch ( IOException e ) {
log.warn( "Could not copy " + copy.from + " to " + copy.to + ": " + e.getLocalizedMessage() );
log.debug( e );
}
}
}
|
diff --git a/src/main/java/uk/ac/cam/sup/form/SearchForm.java b/src/main/java/uk/ac/cam/sup/form/SearchForm.java
index 56aa820..0cab59c 100644
--- a/src/main/java/uk/ac/cam/sup/form/SearchForm.java
+++ b/src/main/java/uk/ac/cam/sup/form/SearchForm.java
@@ -1,298 +1,298 @@
package uk.ac.cam.sup.form;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.ws.rs.QueryParam;
import uk.ac.cam.sup.exceptions.FormValidationException;
import uk.ac.cam.sup.exceptions.ModelNotFoundException;
import uk.ac.cam.sup.exceptions.QueryAlreadyOrderedException;
import uk.ac.cam.sup.models.Tag;
import uk.ac.cam.sup.models.User;
import uk.ac.cam.sup.queries.Query;
import uk.ac.cam.sup.queries.TagQuery;
import uk.ac.cam.sup.queries.UserQuery;
import uk.ac.cam.sup.util.Mappable;
import uk.ac.cam.sup.util.TripleChoice;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
public abstract class SearchForm<T extends Mappable> {
@QueryParam("tags")
protected String tags;
protected List<Tag> tagList = new ArrayList<Tag>();
@QueryParam("authors")
protected String authors;
protected List<User> authorList = new ArrayList<User>();
@QueryParam("minduration")
protected String minDuration;
protected Integer minDurationInt;
@QueryParam("maxduration")
protected String maxDuration;
protected Integer maxDurationInt;
@QueryParam("after")
protected String after;
protected Date afterDate = new Date();
@QueryParam("before")
protected String before;
protected Date beforeDate = new Date();
@QueryParam("supervisor")
protected String supervisor;
protected TripleChoice supervisorChoice = TripleChoice.DONT_CARE;
@QueryParam("starred")
protected String starred;
protected TripleChoice starredChoice = TripleChoice.DONT_CARE;
@QueryParam("page")
protected String page;
protected Integer pageInt;
@QueryParam("amount")
protected String amount;
protected Integer amountInt;
protected Integer totalAmount = null;
protected boolean emptySearch = true;
protected boolean validated = false;
protected final void checkValidity() throws FormValidationException {
if ( ! this.validated) {
throw new FormValidationException("Form was nod validated");
}
}
public SearchForm<T> validate() throws FormValidationException {
if (tags == null) {
tags = "";
}
if (authors == null) {
authors = "";
}
if (minDuration == null) {
minDuration = "";
}
if (maxDuration == null) {
maxDuration = "";
}
if (after == null) {
after = "";
}
if (before == null) {
before = "";
}
if (supervisor == null || supervisor.equals("")) {
supervisor = "DONT_CARE";
}
try {
TripleChoice.valueOf(supervisor);
} catch (IllegalArgumentException | NullPointerException e) {
throw new FormValidationException
("Illegal value for supervisor filter: "+supervisor);
}
if (starred == null || starred.equals("")) {
starred = "DONT_CARE";
}
try {
TripleChoice.valueOf(starred);
} catch (IllegalArgumentException | NullPointerException e) {
throw new FormValidationException
("Illegal value for starred filter: "+starred);
}
if(page == null || page == ""){
page = "1";
pageInt = 1;
}
if(amount == null || amount == ""){
amount = "25";
amountInt = 25;
}
this.validated = true;
return this;
}
public SearchForm<T> parse() throws FormValidationException {
checkValidity();
try{
pageInt = Integer.parseInt(page);
} catch (NumberFormatException e) {
page = "1";
pageInt = 1;
}
try{
amountInt = Integer.parseInt(amount);
} catch (NumberFormatException e) {
amount = "25";
amountInt = 25;
}
String[] split = tags.split(",");
if(tags.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
tagList.add(TagQuery.get(s.trim()));
}
}
split = authors.split(",");
if(authors.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
try {
authorList.add(UserQuery.get(s.trim()));
} catch (ModelNotFoundException e) {
continue;
}
}
}
try {
minDurationInt = Integer.parseInt(minDuration);
emptySearch = false;
} catch (Exception e) {
minDurationInt = null;
}
try {
maxDurationInt = Integer.parseInt(maxDuration);
emptySearch = false;
} catch (Exception e) {
maxDurationInt = null;
}
Calendar c = Calendar.getInstance();
try {
split = before.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
- c.set(year, month, day);
+ c.set(year, month-1, day, 0, 0, 0);
beforeDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
beforeDate = null;
}
try {
split = after.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
- c.set(year, month, day);
+ c.set(year, month-1, day, 0, 0, 0);
afterDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
afterDate = null;
}
supervisorChoice = TripleChoice.valueOf(supervisor);
starredChoice = TripleChoice.valueOf(starred);
if(supervisorChoice != TripleChoice.DONT_CARE || starredChoice != TripleChoice.DONT_CARE){
emptySearch = false;
}
return this;
}
public final List<T> getSearchResults() {
Query<T> query = getQueryObject();
if (query == null) {
totalAmount = 0;
return new ArrayList<T>();
}
if (tagList.size() > 0) {
query.withTags(tagList);
}
if (authorList.size() > 0) {
query.withOwners(authorList);
}
if (supervisorChoice == TripleChoice.YES) {
query.bySupervisor();
} else if (supervisorChoice == TripleChoice.NO) {
query.byStudent();
}
if (starredChoice == TripleChoice.YES){
query.withStar();
} else if (starredChoice == TripleChoice.NO) {
query.withoutStar();
}
if(maxDurationInt != null) query.maxDuration(maxDurationInt);
if(minDurationInt != null) query.minDuration(minDurationInt);
if(afterDate != null) query.after(afterDate);
if(beforeDate != null) query.before(beforeDate);
if(emptySearch || !query.isModified()){
totalAmount = 0;
} else{
try {
totalAmount = query.size();
} catch (QueryAlreadyOrderedException e) {
totalAmount = -1;
e.printStackTrace();
}
}
if(query.isModified()){
return query
.maxResults(amountInt)
.offset(amountInt * (pageInt - 1))
.list();
} else {
return new ArrayList<T>();
}
}
public final Map<String, ?> toMap() {
Builder<String,Object> b = new ImmutableMap.Builder<String,Object>();
b.put("tags", tags);
b.put("authors", authors);
b.put("minDuration", minDuration);
b.put("maxDuration", maxDuration);
b.put("after", after);
b.put("before", before);
b.put("supervisor", supervisor);
b.put("starred", starred);
if(totalAmount == null) getSearchResults();
b.put("page", pageInt);
b.put("amount", amountInt);
b.put("totalAmount", totalAmount);
b.put("emptySearch", emptySearch);
return b.build();
}
protected abstract Query<T> getQueryObject();
}
| false | true | public SearchForm<T> parse() throws FormValidationException {
checkValidity();
try{
pageInt = Integer.parseInt(page);
} catch (NumberFormatException e) {
page = "1";
pageInt = 1;
}
try{
amountInt = Integer.parseInt(amount);
} catch (NumberFormatException e) {
amount = "25";
amountInt = 25;
}
String[] split = tags.split(",");
if(tags.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
tagList.add(TagQuery.get(s.trim()));
}
}
split = authors.split(",");
if(authors.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
try {
authorList.add(UserQuery.get(s.trim()));
} catch (ModelNotFoundException e) {
continue;
}
}
}
try {
minDurationInt = Integer.parseInt(minDuration);
emptySearch = false;
} catch (Exception e) {
minDurationInt = null;
}
try {
maxDurationInt = Integer.parseInt(maxDuration);
emptySearch = false;
} catch (Exception e) {
maxDurationInt = null;
}
Calendar c = Calendar.getInstance();
try {
split = before.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
c.set(year, month, day);
beforeDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
beforeDate = null;
}
try {
split = after.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
c.set(year, month, day);
afterDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
afterDate = null;
}
supervisorChoice = TripleChoice.valueOf(supervisor);
starredChoice = TripleChoice.valueOf(starred);
if(supervisorChoice != TripleChoice.DONT_CARE || starredChoice != TripleChoice.DONT_CARE){
emptySearch = false;
}
return this;
}
| public SearchForm<T> parse() throws FormValidationException {
checkValidity();
try{
pageInt = Integer.parseInt(page);
} catch (NumberFormatException e) {
page = "1";
pageInt = 1;
}
try{
amountInt = Integer.parseInt(amount);
} catch (NumberFormatException e) {
amount = "25";
amountInt = 25;
}
String[] split = tags.split(",");
if(tags.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
tagList.add(TagQuery.get(s.trim()));
}
}
split = authors.split(",");
if(authors.trim().length() > 0) emptySearch = false;
for (String s: split) {
if ( ! s.equals("")) {
try {
authorList.add(UserQuery.get(s.trim()));
} catch (ModelNotFoundException e) {
continue;
}
}
}
try {
minDurationInt = Integer.parseInt(minDuration);
emptySearch = false;
} catch (Exception e) {
minDurationInt = null;
}
try {
maxDurationInt = Integer.parseInt(maxDuration);
emptySearch = false;
} catch (Exception e) {
maxDurationInt = null;
}
Calendar c = Calendar.getInstance();
try {
split = before.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
c.set(year, month-1, day, 0, 0, 0);
beforeDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
beforeDate = null;
}
try {
split = after.split("/");
int day = Integer.parseInt(split[0]);
int month = Integer.parseInt(split[1]);
int year = Integer.parseInt(split[2]);
c.set(year, month-1, day, 0, 0, 0);
afterDate = c.getTime();
emptySearch = false;
} catch(Exception e) {
afterDate = null;
}
supervisorChoice = TripleChoice.valueOf(supervisor);
starredChoice = TripleChoice.valueOf(starred);
if(supervisorChoice != TripleChoice.DONT_CARE || starredChoice != TripleChoice.DONT_CARE){
emptySearch = false;
}
return this;
}
|
diff --git a/bigbluebutton-apps/test/org/bigbluebutton/conference/voice/asterisk/MeetMeRoomAdapterTest.java b/bigbluebutton-apps/test/org/bigbluebutton/conference/voice/asterisk/MeetMeRoomAdapterTest.java
index 5ae2b2d670..7516e005fe 100644
--- a/bigbluebutton-apps/test/org/bigbluebutton/conference/voice/asterisk/MeetMeRoomAdapterTest.java
+++ b/bigbluebutton-apps/test/org/bigbluebutton/conference/voice/asterisk/MeetMeRoomAdapterTest.java
@@ -1,21 +1,21 @@
package org.bigbluebutton.conference.voice.asterisk;
import org.bigbluebutton.conference.voice.IParticipant;
import junit.framework.TestCase;
public class MeetMeRoomAdapterTest extends TestCase {
public void testAddingAndGettingAndRemovingParticipant() {
MeetMeRoomAdapter r = new MeetMeRoomAdapter();
String id = "testParticipant";
IParticipant p = new MeetMeUserAdapter();
p.setId(id);
r.addParticipant(p);
assertEquals("Room should have participant", true, r.hasParticipant(id));
- Participant p1 = r.getParticipant(id);
- assertEquals("Room should get participant", p1.getId(), id);
+// Participant p1 = r.getParticipant(id);
+// assertEquals("Room should get participant", p1.getId(), id);
r.removeParticipant(id);
assertEquals("There should be no more participant", false, r.hasParticipant(id));
}
}
| true | true | public void testAddingAndGettingAndRemovingParticipant() {
MeetMeRoomAdapter r = new MeetMeRoomAdapter();
String id = "testParticipant";
IParticipant p = new MeetMeUserAdapter();
p.setId(id);
r.addParticipant(p);
assertEquals("Room should have participant", true, r.hasParticipant(id));
Participant p1 = r.getParticipant(id);
assertEquals("Room should get participant", p1.getId(), id);
r.removeParticipant(id);
assertEquals("There should be no more participant", false, r.hasParticipant(id));
}
| public void testAddingAndGettingAndRemovingParticipant() {
MeetMeRoomAdapter r = new MeetMeRoomAdapter();
String id = "testParticipant";
IParticipant p = new MeetMeUserAdapter();
p.setId(id);
r.addParticipant(p);
assertEquals("Room should have participant", true, r.hasParticipant(id));
// Participant p1 = r.getParticipant(id);
// assertEquals("Room should get participant", p1.getId(), id);
r.removeParticipant(id);
assertEquals("There should be no more participant", false, r.hasParticipant(id));
}
|
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractBlockAnalyzer.java b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractBlockAnalyzer.java
index 8e4ad81..7e16d39 100644
--- a/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractBlockAnalyzer.java
+++ b/src/jp/ac/osaka_u/ist/sdl/ectec/analyzer/sourceanalyzer/crd/AbstractBlockAnalyzer.java
@@ -1,128 +1,128 @@
package jp.ac.osaka_u.ist.sdl.ectec.analyzer.sourceanalyzer.crd;
import java.util.ArrayList;
import java.util.List;
import jp.ac.osaka_u.ist.sdl.ectec.analyzer.sourceanalyzer.normalizer.StringCreateVisitor;
import jp.ac.osaka_u.ist.sdl.ectec.data.BlockType;
import jp.ac.osaka_u.ist.sdl.ectec.data.CRD;
import org.eclipse.jdt.core.dom.ASTNode;
/**
* A class to create a crd for a given node
*
* @author k-hotta
*
*/
public abstract class AbstractBlockAnalyzer<T extends ASTNode> {
/**
* the node to be analyzed
*/
protected final T node;
/**
* the crd for the parent of this node
*/
protected final CRD parent;
/**
* the type of the block
*/
protected final BlockType bType;
/**
* the visitor to create string for clone detection
*/
protected final StringCreateVisitor visitor;
/**
* the crd created as a result of analysis
*/
private CRD createdCrd;
/**
* the normalized string created as a result of analysis
*/
private String stringForCloneDetection;
public AbstractBlockAnalyzer(final T node, final CRD parent,
final BlockType bType, final StringCreateVisitor visitor) {
this.node = node;
this.parent = parent;
this.bType = bType;
this.visitor = visitor;
}
public CRD getCreatedCrd() {
return createdCrd;
}
public String getStringForCloneDetection() {
return stringForCloneDetection;
}
/**
* create a new instance of CRD for this block
*
* @return
*/
public void analyze() {
final String head = bType.getHead();
final String anchor = getAnchor();
final String normalizedAnchor = getNormalizedAnchor();
final List<Long> ancestorIds = new ArrayList<Long>();
if (parent != null) {
for (final long ancestorId : parent.getAncestors()) {
ancestorIds.add(ancestorId);
}
ancestorIds.add(parent.getId());
}
final MetricsCalculator cmCalculator = new MetricsCalculator();
node.accept(cmCalculator);
final int cm = cmCalculator.getCC() + cmCalculator.getFO();
final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm);
final String fullText = (parent == null) ? thisCrdStr : parent
.getFullText() + "\n" + thisCrdStr;
node.accept(visitor);
createdCrd = new CRD(bType, head, anchor, normalizedAnchor, cm,
ancestorIds, fullText);
- stringForCloneDetection = visitor.toString();
+ stringForCloneDetection = visitor.getString();
}
/**
* get the string representation of THIS block
*
* @param head
* @param anchor
* @param cm
* @return
*/
private String getStringCrdForThisBlock(final String head,
final String anchor, final int cm) {
final StringBuilder builder = new StringBuilder();
builder.append(head + ",");
builder.append(anchor + ",");
builder.append(cm + "\n");
return builder.toString();
}
/**
* get the anchor of the block
*
* @return
*/
protected abstract String getAnchor();
protected abstract String getNormalizedAnchor();
}
| true | true | public void analyze() {
final String head = bType.getHead();
final String anchor = getAnchor();
final String normalizedAnchor = getNormalizedAnchor();
final List<Long> ancestorIds = new ArrayList<Long>();
if (parent != null) {
for (final long ancestorId : parent.getAncestors()) {
ancestorIds.add(ancestorId);
}
ancestorIds.add(parent.getId());
}
final MetricsCalculator cmCalculator = new MetricsCalculator();
node.accept(cmCalculator);
final int cm = cmCalculator.getCC() + cmCalculator.getFO();
final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm);
final String fullText = (parent == null) ? thisCrdStr : parent
.getFullText() + "\n" + thisCrdStr;
node.accept(visitor);
createdCrd = new CRD(bType, head, anchor, normalizedAnchor, cm,
ancestorIds, fullText);
stringForCloneDetection = visitor.toString();
}
| public void analyze() {
final String head = bType.getHead();
final String anchor = getAnchor();
final String normalizedAnchor = getNormalizedAnchor();
final List<Long> ancestorIds = new ArrayList<Long>();
if (parent != null) {
for (final long ancestorId : parent.getAncestors()) {
ancestorIds.add(ancestorId);
}
ancestorIds.add(parent.getId());
}
final MetricsCalculator cmCalculator = new MetricsCalculator();
node.accept(cmCalculator);
final int cm = cmCalculator.getCC() + cmCalculator.getFO();
final String thisCrdStr = getStringCrdForThisBlock(head, anchor, cm);
final String fullText = (parent == null) ? thisCrdStr : parent
.getFullText() + "\n" + thisCrdStr;
node.accept(visitor);
createdCrd = new CRD(bType, head, anchor, normalizedAnchor, cm,
ancestorIds, fullText);
stringForCloneDetection = visitor.getString();
}
|
diff --git a/src/com/dmdirc/Server.java b/src/com/dmdirc/Server.java
index 3e7217321..c28c59cf4 100644
--- a/src/com/dmdirc/Server.java
+++ b/src/com/dmdirc/Server.java
@@ -1,1399 +1,1397 @@
/*
* Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.actions.wrappers.AliasWrapper;
import com.dmdirc.commandparser.CommandManager;
import com.dmdirc.commandparser.CommandType;
import com.dmdirc.config.ConfigManager;
import com.dmdirc.config.Identity;
import com.dmdirc.config.IdentityManager;
import com.dmdirc.interfaces.AwayStateListener;
import com.dmdirc.interfaces.InviteListener;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import com.dmdirc.parser.ChannelInfo;
import com.dmdirc.parser.ClientInfo;
import com.dmdirc.parser.IRCParser;
import com.dmdirc.parser.MyInfo;
import com.dmdirc.parser.ParserError;
import com.dmdirc.parser.ServerInfo;
import com.dmdirc.ui.WindowManager;
import com.dmdirc.ui.input.TabCompleter;
import com.dmdirc.ui.interfaces.InputWindow;
import com.dmdirc.ui.interfaces.ServerWindow;
import com.dmdirc.ui.interfaces.Window;
import com.dmdirc.ui.messages.Formatter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
* The Server class represents the client's view of a server. It maintains
* a list of all channels, queries, etc, and handles parser callbacks pertaining
* to the server.
*
* @author chris
*/
public final class Server extends WritableFrameContainer implements Serializable {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/** The name of the general domain. */
private static final String DOMAIN_GENERAL = "general".intern();
/** The name of the profile domain. */
private static final String DOMAIN_PROFILE = "profile".intern();
/** The name of the server domain. */
private static final String DOMAIN_SERVER = "server".intern();
/** Open channels that currently exist on the server. */
private final Map<String, Channel> channels = new Hashtable<String, Channel>();
/** Open query windows on the server. */
private final List<Query> queries = new ArrayList<Query>();
/** The IRC Parser instance handling this server. */
private transient IRCParser parser;
/** The raw frame used for this server instance. */
private Raw raw;
/** The ServerWindow corresponding to this server. */
private ServerWindow window;
/** The details of the server we're connecting to. */
private ServerInfo serverInfo;
/** The profile we're using. */
private transient Identity profile;
/** The current state of this server. */
private ServerState myState = ServerState.DISCONNECTED;
/** The timer we're using to delay reconnects. */
private Timer reconnectTimer;
/** Channels we're meant to auto-join. */
private final List<String> autochannels;
/** The tabcompleter used for this server. */
private final TabCompleter tabCompleter = new TabCompleter();
/** The last activated internal frame for this server. */
private FrameContainer activeFrame = this;
/** The config manager for this server. */
private ConfigManager configManager;
/** Our reason for being away, if any. */
private String awayMessage = null;
/** Our event handler. */
private final ServerEventHandler eventHandler = new ServerEventHandler(this);
/** A list of outstanding invites. */
private final List<Invite> invites = new ArrayList<Invite>();
/** Our ignore list. */
private IgnoreList ignoreList = new IgnoreList();
/**
* Creates a new instance of Server.
*
* @param server The hostname/ip of the server to connect to
* @param port The port to connect to
* @param password The server password
* @param ssl Whether to use SSL or not
* @param profile The profile to use
*/
public Server(final String server, final int port, final String password,
final boolean ssl, final Identity profile) {
this(server, port, password, ssl, profile, new ArrayList<String>());
}
/**
* Creates a new instance of Server.
*
* @param server The hostname/ip of the server to connect to
* @param port The port to connect to
* @param password The server password
* @param ssl Whether to use SSL or not
* @param profile The profile to use
* @param autochannels A list of channels to auto-join when we connect
*/
public Server(final String server, final int port, final String password,
final boolean ssl, final Identity profile, final List<String> autochannels) {
super();
serverInfo = new ServerInfo(server, port, password);
serverInfo.setSSL(ssl);
ServerManager.getServerManager().registerServer(this);
configManager = new ConfigManager("", "", server);
window = Main.getUI().getServer(this);
WindowManager.addWindow(window);
window.setTitle(server + ":" + port);
tabCompleter.addEntries(AliasWrapper.getAliasWrapper().getAliases());
window.getInputHandler().setTabCompleter(tabCompleter);
updateIcon();
window.open();
tabCompleter.addEntries(CommandManager.getCommandNames(CommandType.TYPE_SERVER));
tabCompleter.addEntries(CommandManager.getCommandNames(CommandType.TYPE_GLOBAL));
this.autochannels = autochannels;
new Timer("Server Who Timer").scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
for (Channel channel : channels.values()) {
channel.checkWho();
}
}
}, 0, configManager.getOptionInt(DOMAIN_GENERAL, "whotime", 60000));
if (configManager.getOptionBool(DOMAIN_GENERAL, "showrawwindow", false)) {
addRaw();
}
connect(server, port, password, ssl, profile);
}
// ------------------------ CONNECTION, DISCONNECTION AND RECONNECTION -----
/**
* Connects to a new server with the specified details.
*
* @param server The hostname/ip of the server to connect to
* @param port The port to connect to
* @param password The server password
* @param ssl Whether to use SSL or not
* @param profile The profile to use
*/
@Precondition({
"The IRC Parser is null or not connected",
"The specified profile is not null"
})
public void connect(final String server, final int port, final String password,
final boolean ssl, final Identity profile) {
assert(profile != null);
synchronized(myState) {
switch (myState) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
- Logger.appError(ErrorLevel.MEDIUM,
- "Connect attempt while not expecting one",
- new UnsupportedOperationException("Current state: " + myState));
+ // Ignore the connection attempt
return;
case CONNECTED:
case CONNECTING:
disconnect(configManager.getOption(DOMAIN_GENERAL, "quitmessage"));
break;
default:
// Do nothing
break;
}
myState = ServerState.CONNECTING;
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
assert(parser == null || parser.getSocketState() != IRCParser.STATE_OPEN);
serverInfo = new ServerInfo(server, port, password);
serverInfo.setSSL(ssl);
this.profile = profile;
configManager = new ConfigManager("", "", server);
updateIcon();
addLine("serverConnecting", server, port);
final MyInfo myInfo = getMyInfo();
parser = new IRCParser(myInfo, serverInfo);
parser.setRemoveAfterCallback(true);
parser.setCreateFake(true);
parser.setAddLastLine(true);
parser.setIgnoreList(ignoreList);
if (configManager.hasOption(DOMAIN_GENERAL, "bindip")) {
parser.setBindIP(configManager.getOption(DOMAIN_GENERAL, "bindip"));
}
doCallbacks();
awayMessage = null;
invites.clear();
window.setAwayIndicator(false);
try {
new Thread(parser, "IRC Parser thread").start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
/**
* Reconnects to the IRC server with a specified reason.
*
* @param reason The quit reason to send
*/
public void reconnect(final String reason) {
synchronized(myState) {
if (myState == ServerState.CLOSING) {
return;
}
}
disconnect(reason);
connect(serverInfo.getHost(), serverInfo.getPort(),
serverInfo.getPassword(), serverInfo.getSSL(), profile);
}
/**
* Reconnects to the IRC server.
*/
public void reconnect() {
reconnect(configManager.getOption(DOMAIN_GENERAL, "reconnectmessage"));
}
/**
* Disconnects from the server with the default quit message.
*/
public void disconnect() {
disconnect(configManager.getOption(DOMAIN_GENERAL, "quitmessage"));
}
/**
* Disconnects from the server.
*
* @param reason disconnect reason
*/
public void disconnect(final String reason) {
synchronized(myState) {
switch (myState) {
case CLOSING:
case DISCONNECTED:
case TRANSIENTLY_DISCONNECTED:
return;
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
default:
break;
}
myState = ServerState.DISCONNECTED;
}
removeInvites();
updateIcon();
if (parser != null && parser.getSocketState() == IRCParser.STATE_OPEN) {
parser.disconnect(reason);
if (configManager.getOptionBool(DOMAIN_GENERAL, "closechannelsonquit", false)) {
closeChannels();
} else {
clearChannels();
}
if (configManager.getOptionBool(DOMAIN_GENERAL, "closequeriesonquit", false)) {
closeQueries();
}
}
}
/**
* Schedules a reconnect attempt to be performed after a user-defiend delay.
*/
private void doDelayedReconnect() {
final int delay = Math.max(1,
configManager.getOptionInt(DOMAIN_GENERAL, "reconnectdelay", 5));
handleNotification("connectRetry", getName(), delay);
reconnectTimer = new Timer("Server Reconnect Timer");
reconnectTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized(myState) {
if (myState == ServerState.RECONNECT_WAIT) {
myState = ServerState.TRANSIENTLY_DISCONNECTED;
reconnect();
}
}
}
}, delay * 1000);
myState = ServerState.RECONNECT_WAIT;
updateIcon();
}
// ------------------------------------------------- CHILDREN HANDLING -----
/**
* Determines whether the server knows of the specified channel.
*
* @param channel The channel to be checked
* @return True iff the channel is known, false otherwise
*/
public boolean hasChannel(final String channel) {
return parser != null && channels.containsKey(parser.toLowerCase(channel));
}
/**
* Retrieves the specified channel belonging to this server.
*
* @param channel The channel to be retrieved
* @return The appropriate channel object
*/
public Channel getChannel(final String channel) {
return channels.get(parser.toLowerCase(channel));
}
/**
* Retrieves a list of channel names belonging to this server.
*
* @return list of channel names belonging to this server
*/
public List<String> getChannels() {
final ArrayList<String> res = new ArrayList<String>();
for (String channel : channels.keySet()) {
res.add(channel);
}
return res;
}
/**
* Determines whether the server knows of the specified query.
*
* @param host The host of the query to look for
* @return True iff the query is known, false otherwise
*/
public boolean hasQuery(final String host) {
final String nick = ClientInfo.parseHost(host);
for (Query query : queries) {
if (parser.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) {
return true;
}
}
return false;
}
/**
* Retrieves the specified query belonging to this server.
*
* @param host The host of the query to look for
* @return The appropriate query object
*/
public Query getQuery(final String host) {
final String nick = ClientInfo.parseHost(host);
for (Query query : queries) {
if (parser.equalsIgnoreCase(ClientInfo.parseHost(query.getHost()), nick)) {
return query;
}
}
throw new IllegalArgumentException("No such query: " + host);
}
/**
* Retrieves a list of queries belonging to this server.
*
* @return list of queries belonging to this server
*/
public List<Query> getQueries() {
return new ArrayList<Query>(queries);
}
/**
* Adds a raw window to this server.
*/
public void addRaw() {
if (raw == null) {
raw = new Raw(this);
if (parser != null) {
raw.registerCallbacks();
}
} else {
raw.activateFrame();
}
}
/**
* Retrieves the raw window associated with this server.
*
* @return The raw window associated with this server.
*/
public Raw getRaw() {
return raw;
}
/**
* Removes our reference to the raw object (presumably after it has been
* closed).
*/
public void delRaw() {
raw = null; //NOPMD
}
/**
* Removes a specific channel and window from this server.
*
* @param chan channel to remove
*/
public void delChannel(final String chan) {
tabCompleter.removeEntry(chan);
channels.remove(parser.toLowerCase(chan));
}
/**
* Adds a specific channel and window to this server.
*
* @param chan channel to add
*/
public void addChannel(final ChannelInfo chan) {
if (hasChannel(chan.getName())) {
getChannel(chan.getName()).setChannelInfo(chan);
getChannel(chan.getName()).selfJoin();
} else {
final Channel newChan = new Channel(this, chan);
tabCompleter.addEntry(chan.getName());
channels.put(parser.toLowerCase(chan.getName()), newChan);
newChan.show();
}
}
/**
* Adds a query to this server.
*
* @param host host of the remote client being queried
*/
public void addQuery(final String host) {
if (!hasQuery(host)) {
final Query newQuery = new Query(this, host);
tabCompleter.addEntry(ClientInfo.parseHost(host));
queries.add(newQuery);
}
}
/**
* Deletes a query from this server.
*
* @param query The query that should be removed.
*/
public void delQuery(final Query query) {
tabCompleter.removeEntry(query.getNickname());
queries.remove(query);
}
/** {@inheritDoc} */
@Override
public boolean ownsFrame(final Window target) {
// Check if it's our server frame
if (window != null && window.equals(target)) { return true; }
// Check if it's the raw frame
if (raw != null && raw.ownsFrame(target)) { return true; }
// Check if it's a channel frame
for (Channel channel : channels.values()) {
if (channel.ownsFrame(target)) { return true; }
}
// Check if it's a query frame
for (Query query : queries) {
if (query.ownsFrame(target)) { return true; }
}
return false;
}
/**
* Sets the specified frame as the most-recently activated.
*
* @param source The frame that was activated
*/
public void setActiveFrame(final FrameContainer source) {
activeFrame = source;
}
/**
* Retrieves a list of all children of this server instance.
*
* @return A list of this server's children
*/
public List<WritableFrameContainer> getChildren() {
final List<WritableFrameContainer> res = new ArrayList<WritableFrameContainer>();
if (raw != null) {
res.add(raw);
}
res.addAll(channels.values());
res.addAll(queries);
return res;
}
// --------------------------------------------- MISCELLANEOUS METHODS -----
/**
* Updates this server's icon.
*/
private void updateIcon() {
icon = IconManager.getIconManager().getIcon(
myState == ServerState.CONNECTED ?
serverInfo.getSSL() ? "secure-server" : "server" : "server-disconnected");
if (window != null) {
window.setFrameIcon(icon);
iconUpdated(icon);
}
}
/**
* Retrieves the MyInfo object used for the IRC Parser.
*
* @return The MyInfo object for our profile
*/
@Precondition("The current profile is not null")
private MyInfo getMyInfo() {
assert(profile != null);
final MyInfo myInfo = new MyInfo();
myInfo.setNickname(profile.getOption(DOMAIN_PROFILE, "nickname"));
myInfo.setRealname(profile.getOption(DOMAIN_PROFILE, "realname"));
if (profile.hasOption(DOMAIN_PROFILE, "ident")) {
myInfo.setUsername(profile.getOption(DOMAIN_PROFILE, "ident"));
}
return myInfo;
}
/**
* Registers callbacks.
*/
private void doCallbacks() {
if (raw != null) {
raw.registerCallbacks();
}
eventHandler.registerCallbacks();
for (Query query : queries) {
query.reregister();
}
}
/**
* Joins the specified channel.
*
* @param channel The channel to be joined
*/
@Precondition("This server is connected")
public void join(final String channel) {
assert(myState == ServerState.CONNECTED);
removeInvites(channel);
if (hasChannel(channel)) {
getChannel(channel).join();
getChannel(channel).activateFrame();
} else {
parser.joinChannel(channel);
}
}
/** {@inheritDoc} */
@Override
public void sendLine(final String line) {
synchronized(myState) {
if (parser != null && myState == ServerState.CONNECTED) {
parser.sendLine(window.getTranscoder().encode(line));
}
}
}
/** {@inheritDoc} */
@Override
public int getMaxLineLength() {
return IRCParser.MAX_LINELENGTH;
}
/**
* Retrieves the parser used for this connection.
*
* @return IRCParser this connection's parser
*/
public IRCParser getParser() {
return parser;
}
/**
* Retrieves the profile that's in use for this server.
*
* @return The profile in use by this server
*/
public Identity getProfile() {
return profile;
}
/**
* Retrieves the name of this server.
*
* @return The name of this server
*/
public String getName() {
return serverInfo.getHost();
}
/**
* Retrieves the name of this server's network. The network name is
* determined using the following rules:
*
* 1. If the server includes its network name in the 005 information, we
* use that
* 2. If the server's name ends in biz, com, info, net or org, we use the
* second level domain (e.g., foo.com)
* 3. If the server's name contains more than two dots, we drop everything
* up to and including the first part, and use the remainder
* 4. In all other cases, we use the full server name
*
* @return The name of this server's network
*/
public String getNetwork() {
if (parser == null) {
return "";
} else if (parser.getNetworkName().isEmpty()) {
return getNetworkFromServerName(parser.getServerName());
} else {
return parser.getNetworkName();
}
}
/**
* Caclaultes a network name from the specified server name. This method
* implements parts 2-4 of the procedure documented at getNetwork().
*
* @param serverName The server name to parse
* @return A network name for the specified server
*/
protected static String getNetworkFromServerName(final String serverName) {
final String[] parts = serverName.split("\\.");
final String[] tlds = {"biz", "com", "info", "net", "org"};
boolean isTLD = false;
for (String tld : tlds) {
if (serverName.endsWith("." + tld)) {
isTLD = true;
}
}
if (isTLD && parts.length > 2) {
return parts[parts.length - 2] + "." + parts[parts.length - 1];
} else if (parts.length > 2) {
final StringBuilder network = new StringBuilder();
for (int i = 1; i < parts.length; i++) {
if (network.length() > 0) {
network.append('.');
}
network.append(parts[i]);
}
return network.toString();
} else {
return serverName;
}
}
/**
* Retrieves the name of this server's IRCd.
*
* @return The name of this server's IRCd
*/
public String getIrcd() {
return parser.getIRCD(true);
}
/**
* Returns the current away status.
*
* @return True if the client is marked as away, false otherwise
*/
public boolean isAway() {
return awayMessage != null;
}
/**
* Gets the current away message.
*
* @return Null if the client isn't away, or a textual away message if it is
*/
public String getAwayMessage() {
return awayMessage;
}
/**
* Returns the tab completer for this connection.
*
* @return The tab completer for this server
*/
public TabCompleter getTabCompleter() {
return tabCompleter;
}
/** {@inheritDoc} */
@Override
public InputWindow getFrame() {
return window;
}
/** {@inheritDoc} */
@Override
public ConfigManager getConfigManager() {
return configManager;
}
/**
* Retrieves the current state for this server.
*
* @return This server's state
*/
public ServerState getState() {
return myState;
}
/** {@inheritDoc} */
@Override
public void windowClosing() {
// 1: Make the window non-visible
window.setVisible(false);
// 2: Remove any callbacks or listeners
if (parser != null) {
parser.getCallbackManager().delAllCallback(eventHandler);
}
// 3: Trigger any actions neccessary
if (parser != null && parser.isReady()) {
disconnect();
}
myState = ServerState.CLOSING;
closeChannels();
closeQueries();
removeInvites();
if (raw != null) {
raw.close();
}
// 4: Trigger action for the window closing
// 5: Inform any parents that the window is closing
ServerManager.getServerManager().unregisterServer(this);
// 6: Remove the window from the window manager
WindowManager.removeWindow(window);
// 7: Remove any references to the window and parents
window = null; //NOPMD
parser = null; //NOPMD
}
/**
* Closes all open channel windows associated with this server.
*/
private void closeChannels() {
for (Channel channel : new ArrayList<Channel>(channels.values())) {
channel.close();
}
}
/**
* Clears the nicklist of all open channels.
*/
private void clearChannels() {
for (Channel channel : channels.values()) {
channel.resetWindow();
}
}
/**
* Closes all open query windows associated with this server.
*/
private void closeQueries() {
for (Query query : new ArrayList<Query>(queries)) {
query.close();
}
}
/**
* Passes the arguments to the most recently activated frame for this
* server. If the frame isn't know, or isn't visible, use this frame
* instead.
*
* @param messageType The type of message to send
* @param args The arguments for the message
*/
public void addLineToActive(final String messageType, final Object... args) {
if (activeFrame == null || !activeFrame.getFrame().isVisible()) {
activeFrame = this;
}
activeFrame.getFrame().addLine(messageType, args);
}
/**
* Passes the arguments to all frames for this server.
*
* @param messageType The type of message to send
* @param args The arguments of the message
*/
public void addLineToAll(final String messageType, final Object... args) {
for (Channel channel : channels.values()) {
channel.getFrame().addLine(messageType, args);
}
for (Query query : queries) {
query.getFrame().addLine(messageType, args);
}
addLine(messageType, args);
}
/**
* Replies to an incoming CTCP message.
*
* @param source The source of the message
* @param type The CTCP type
* @param args The CTCP arguments
*/
public void sendCTCPReply(final String source, final String type, final String args) {
if (type.equalsIgnoreCase("VERSION")) {
parser.sendCTCPReply(source, "VERSION", "DMDirc " + Main.VERSION
+ " - http://www.dmdirc.com/");
} else if (type.equalsIgnoreCase("PING")) {
parser.sendCTCPReply(source, "PING", args);
} else if (type.equalsIgnoreCase("CLIENTINFO")) {
parser.sendCTCPReply(source, "CLIENTINFO", "VERSION PING CLIENTINFO");
}
}
/**
* Determines if the specified channel name is valid. A channel name is
* valid if we already have an existing Channel with the same name, or
* we have a valid parser instance and the parser says it's valid.
*
* @param channelName The name of the channel to test
* @return True if the channel name is valid, false otherwise
*/
public boolean isValidChannelName(String channelName) {
return hasChannel(channelName) ||
(parser != null && parser.isValidChannelName(channelName));
}
/**
* Returns this server's name.
*
* @return A string representation of this server (i.e., its name)
*/
@Override
public String toString() {
return getName();
}
/**
* Returns the server instance associated with this frame.
*
* @return the associated server connection
*/
@Override
public Server getServer() {
return this;
}
/** {@inheritDoc} */
@Override
protected boolean processNotificationArg(final Object arg, final List<Object> args) {
if (arg instanceof ClientInfo) {
final ClientInfo clientInfo = (ClientInfo) arg;
args.add(clientInfo.getNickname());
args.add(clientInfo.getIdent());
args.add(clientInfo.getHost());
return true;
} else {
return super.processNotificationArg(arg, args);
}
}
/**
* Retusnt the list of invites for this server.
*
* @return Invite list
*/
public List<Invite> getInvites() {
return invites;
}
// -------------------------------------------------- PARSER CALLBACKS -----
/**
* Called when the server says that the nickname we're trying to use is
* already in use.
*
* @param nickname The nickname that we were trying to use
*/
public void onNickInUse(final String nickname) {
final String lastNick = parser.getMyNickname();
// If our last nick is still valid, ignore the in use message
if (!parser.equalsIgnoreCase(lastNick, nickname)) {
return;
}
String newNick = lastNick + (int) (Math.random() * 10);
if (profile.hasOption(DOMAIN_PROFILE, "altnicks")) {
final String[] alts = profile.getOption(DOMAIN_PROFILE, "altnicks").split("\n");
int offset = 0;
if (!parser.equalsIgnoreCase(lastNick,
profile.getOption(DOMAIN_PROFILE, "nickname"))) {
for (String alt : alts) {
offset++;
if (parser.equalsIgnoreCase(alt, lastNick)) {
break;
}
}
}
if (offset < alts.length && !alts[offset].isEmpty()) {
newNick = alts[offset];
}
}
parser.setNickname(newNick);
}
/**
* Called when the server sends a numeric event.
*
* @param numeric The numeric code for the event
* @param tokens The (tokenised) arguments of the event
*/
public void onNumeric(final int numeric, final String[] tokens) {
String snumeric = String.valueOf(numeric);
if (numeric < 10) {
snumeric = "00" + snumeric;
} else if (numeric < 100) {
snumeric = "0" + snumeric;
}
final String withIrcd = "numeric_" + parser.getIRCD(true) + "_" + snumeric;
final String sansIrcd = "numeric_" + snumeric;
String target = null;
if (Formatter.hasFormat(withIrcd)) {
target = withIrcd;
} else if (Formatter.hasFormat(sansIrcd)) {
target = sansIrcd;
} else if (Formatter.hasFormat("numeric_unknown")) {
target = "numeric_unknown";
}
if (target != null) {
handleNotification(target, (Object[]) tokens);
}
ActionManager.processEvent(CoreActionType.SERVER_NUMERIC, null, this,
Integer.valueOf(numeric), tokens);
}
/**
* Called when the socket has been closed.
*/
public void onSocketClosed() {
handleNotification("socketClosed", getName());
ActionManager.processEvent(CoreActionType.SERVER_DISCONNECTED, null, this);
synchronized(myState) {
if (myState == ServerState.CLOSING || myState == ServerState.DISCONNECTED) {
// This has been triggered via .disconect()
return;
}
myState = ServerState.TRANSIENTLY_DISCONNECTED;
}
updateIcon();
if (configManager.getOptionBool(DOMAIN_GENERAL, "closechannelsondisconnect", false)) {
closeChannels();
} else {
clearChannels();
}
if (configManager.getOptionBool(DOMAIN_GENERAL, "closequeriesondisconnect", false)) {
closeQueries();
}
removeInvites();
if (configManager.getOptionBool(DOMAIN_GENERAL, "reconnectondisconnect", false)) {
doDelayedReconnect();
}
}
/**
* Called when an error was encountered while connecting.
*
* @param errorInfo The parser's error information
*/
@Precondition("The current server state is CONNECTING")
public void onConnectError(final ParserError errorInfo) {
synchronized(myState) {
assert(myState == ServerState.CONNECTING);
myState = ServerState.TRANSIENTLY_DISCONNECTED;
}
updateIcon();
String description;
if (errorInfo.getException() == null) {
description = errorInfo.getData();
} else {
final Exception exception = errorInfo.getException();
if (exception instanceof java.net.UnknownHostException) {
description = "Unknown host (unable to resolve)";
} else if (exception instanceof java.net.NoRouteToHostException) {
description = "No route to host";
} else if (exception instanceof java.net.SocketException) {
description = exception.getMessage();
} else {
Logger.appError(ErrorLevel.LOW, "Unknown socket error", exception);
description = "Unknown error: " + exception.getMessage();
}
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTERROR, null,
this, description);
handleNotification("connectError", getName(), description);
if (configManager.getOptionBool(DOMAIN_GENERAL, "reconnectonconnectfailure", false)) {
doDelayedReconnect();
}
}
/**
* Called when we fail to receive a ping reply within a set period of time.
*/
public void onPingFailed() {
Main.getUI().getStatusBar().setMessage("No ping reply from "
+ getName() + " for over "
+ ((int) (Math.floor(parser.getPingTime(false) / 1000.0)))
+ " seconds.", null, 10);
ActionManager.processEvent(CoreActionType.SERVER_NOPING, null, this,
Long.valueOf(parser.getPingTime(false)));
if (parser.getPingTime(false) >=
configManager.getOptionInt(DOMAIN_SERVER, "pingtimeout", 60000)) {
handleNotification("stonedServer", getName());
reconnect();
}
}
/**
* Called after the parser receives the 005 headers from the server.
*/
public void onPost005() {
synchronized(myState) {
myState = ServerState.CONNECTED;
}
updateIcon();
configManager = new ConfigManager(parser.getIRCD(true), getNetwork(), getName());
updateIgnoreList();
ActionManager.processEvent(CoreActionType.SERVER_CONNECTED, null, this);
if (configManager.hasOption(DOMAIN_GENERAL, "rejoinchannels")) {
for (Channel chan : channels.values()) {
chan.join();
}
}
for (String channel : autochannels) {
parser.joinChannel(channel);
}
checkModeAliases();
}
/**
* Checks that we have the neccessary mode aliases for this server.
*/
private void checkModeAliases() {
// Check we have mode aliases
final String modes = parser.getBoolChanModes() + parser.getListChanModes()
+ parser.getSetOnlyChanModes() + parser.getSetUnsetChanModes();
final String umodes = parser.getUserModeString();
final StringBuffer missingModes = new StringBuffer();
final StringBuffer missingUmodes = new StringBuffer();
for (char mode : modes.toCharArray()) {
if (!configManager.hasOption(DOMAIN_SERVER, "mode" + mode)) {
missingModes.append(mode);
}
}
for (char mode : umodes.toCharArray()) {
if (!configManager.hasOption(DOMAIN_SERVER, "umode" + mode)) {
missingUmodes.append(mode);
}
}
if (missingModes.length() + missingUmodes.length() > 0) {
final StringBuffer missing = new StringBuffer("Missing mode aliases: ");
if (missingModes.length() > 0) {
missing.append("channel: +");
missing.append(missingModes);
}
if (missingUmodes.length() > 0) {
if (missingModes.length() > 0) {
missing.append(' ');
}
missing.append("user: +");
missing.append(missingUmodes);
}
Logger.appError(ErrorLevel.LOW, missing.toString() + " ["
+ getNetwork() + "]",
new Exception(missing.toString() + "\n" // NOPMD
+ "Network: " + getNetwork() + "\n"
+ "IRCd: " + parser.getIRCD(false)
+ " (" + parser.getIRCD(true) + ")\n\n"));
}
}
// ---------------------------------------------- IGNORE LIST HANDLING -----
/**
* Retrieves this server's ignore list.
*
* @return This server's ignore list
*/
public IgnoreList getIgnoreList() {
return ignoreList;
}
/**
* Updates this server's ignore list to use the entries stored in the
* config manager.
*/
public void updateIgnoreList() {
ignoreList.clear();
ignoreList.addAll(configManager.getOptionList("network", "ignorelist"));
}
/**
* Saves the contents of our ignore list to the network identity.
*/
public void saveIgnoreList() {
getNetworkIdentity().setOption("network", "ignorelist", ignoreList.getRegexList());
}
// ------------------------------------------------- IDENTITY WRAPPERS -----
/**
* Retrieves the identity for this server.
*
* @return This server's identity
*/
public Identity getServerIdentity() {
return IdentityManager.getServerConfig(getName());
}
/**
* Retrieves the identity for this server's network.
*
* @return This server's network identity
*/
public Identity getNetworkIdentity() {
return IdentityManager.getNetworkConfig(getNetwork());
}
// --------------------------------------------------- INVITE HANDLING -----
/**
* Adds an invite listener to this server.
*
* @param listener The listener to be added
*/
public void addInviteListener(final InviteListener listener) {
listeners.add(InviteListener.class, listener);
}
/**
* Removes an invite listener from this server.
*
* @param listener The listener to be removed
*/
public void removeInviteListener(final InviteListener listener) {
listeners.remove(InviteListener.class, listener);
}
/**
* Adds an invite to this server, and fires the appropriate listeners.
*
* @param invite The invite to be added
*/
public void addInvite(final Invite invite) {
for (Invite oldInvite : new ArrayList<Invite>(invites)) {
if (oldInvite.getChannel().equals(invite.getChannel())) {
removeInvite(oldInvite);
}
}
invites.add(invite);
for (InviteListener listener : listeners.get(InviteListener.class)) {
listener.inviteReceived(this, invite);
}
}
/**
* Removes all invites for the specified channel.
*
* @param channel The channel to remove invites for
*/
public void removeInvites(final String channel) {
for (Invite invite : new ArrayList<Invite>(invites)) {
if (invite.getChannel().equals(channel)) {
removeInvite(invite);
}
}
}
/**
* Removes all invites for all channels.
*/
private void removeInvites() {
for (Invite invite : new ArrayList<Invite>(invites)) {
removeInvite(invite);
}
}
/**
* Removes an invite from this server, and fires the appropriate listeners.
*
* @param invite The invite to be removed
*/
public void removeInvite(final Invite invite) {
invites.remove(invite);
for (InviteListener listener : listeners.get(InviteListener.class)) {
listener.inviteExpired(this, invite);
}
}
// ----------------------------------------------- AWAY STATE HANDLING -----
/**
* Adds an away state lisener to this server.
*
* @param listener The listener to be added
*/
public void addAwayStateListener(final AwayStateListener listener) {
listeners.add(AwayStateListener.class, listener);
}
/**
* Removes an away state lisener from this server.
*
* @param listener The listener to be removed
*/
public void removeAwayStateListener(final AwayStateListener listener) {
listeners.remove(AwayStateListener.class, listener);
}
/**
* Updates our away state and fires the relevant listeners.
*
* @param message The away message to use, or null if we're not away.
*/
public void updateAwayState(final String message) {
awayMessage = message;
if (message == null) {
for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
listener.onBack();
}
} else {
for (AwayStateListener listener : listeners.get(AwayStateListener.class)) {
listener.onAway(message);
}
}
}
}
| true | true | public void connect(final String server, final int port, final String password,
final boolean ssl, final Identity profile) {
assert(profile != null);
synchronized(myState) {
switch (myState) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
Logger.appError(ErrorLevel.MEDIUM,
"Connect attempt while not expecting one",
new UnsupportedOperationException("Current state: " + myState));
return;
case CONNECTED:
case CONNECTING:
disconnect(configManager.getOption(DOMAIN_GENERAL, "quitmessage"));
break;
default:
// Do nothing
break;
}
myState = ServerState.CONNECTING;
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
assert(parser == null || parser.getSocketState() != IRCParser.STATE_OPEN);
serverInfo = new ServerInfo(server, port, password);
serverInfo.setSSL(ssl);
this.profile = profile;
configManager = new ConfigManager("", "", server);
updateIcon();
addLine("serverConnecting", server, port);
final MyInfo myInfo = getMyInfo();
parser = new IRCParser(myInfo, serverInfo);
parser.setRemoveAfterCallback(true);
parser.setCreateFake(true);
parser.setAddLastLine(true);
parser.setIgnoreList(ignoreList);
if (configManager.hasOption(DOMAIN_GENERAL, "bindip")) {
parser.setBindIP(configManager.getOption(DOMAIN_GENERAL, "bindip"));
}
doCallbacks();
awayMessage = null;
invites.clear();
window.setAwayIndicator(false);
try {
new Thread(parser, "IRC Parser thread").start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
| public void connect(final String server, final int port, final String password,
final boolean ssl, final Identity profile) {
assert(profile != null);
synchronized(myState) {
switch (myState) {
case RECONNECT_WAIT:
reconnectTimer.cancel();
break;
case CLOSING:
// Ignore the connection attempt
return;
case CONNECTED:
case CONNECTING:
disconnect(configManager.getOption(DOMAIN_GENERAL, "quitmessage"));
break;
default:
// Do nothing
break;
}
myState = ServerState.CONNECTING;
}
ActionManager.processEvent(CoreActionType.SERVER_CONNECTING, null, this);
assert(parser == null || parser.getSocketState() != IRCParser.STATE_OPEN);
serverInfo = new ServerInfo(server, port, password);
serverInfo.setSSL(ssl);
this.profile = profile;
configManager = new ConfigManager("", "", server);
updateIcon();
addLine("serverConnecting", server, port);
final MyInfo myInfo = getMyInfo();
parser = new IRCParser(myInfo, serverInfo);
parser.setRemoveAfterCallback(true);
parser.setCreateFake(true);
parser.setAddLastLine(true);
parser.setIgnoreList(ignoreList);
if (configManager.hasOption(DOMAIN_GENERAL, "bindip")) {
parser.setBindIP(configManager.getOption(DOMAIN_GENERAL, "bindip"));
}
doCallbacks();
awayMessage = null;
invites.clear();
window.setAwayIndicator(false);
try {
new Thread(parser, "IRC Parser thread").start();
} catch (IllegalThreadStateException ex) {
Logger.appError(ErrorLevel.FATAL, "Unable to start IRC Parser", ex);
}
}
|
diff --git a/org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/internal/github/core/issue/IssueTaskDataHandler.java b/org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/internal/github/core/issue/IssueTaskDataHandler.java
index 83c883f..5c2f481 100644
--- a/org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/internal/github/core/issue/IssueTaskDataHandler.java
+++ b/org.eclipse.mylyn.github.core/src/org/eclipse/mylyn/internal/github/core/issue/IssueTaskDataHandler.java
@@ -1,375 +1,368 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David Green <david.green@tasktop.com> - initial contribution
* Christian Trutz <christian.trutz@gmail.com> - initial contribution
* Chris Aniszczyk <caniszczyk@gmail.com> - initial contribution
*******************************************************************************/
package org.eclipse.mylyn.internal.github.core.issue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.egit.github.core.Comment;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.Milestone;
import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.IssueService;
import org.eclipse.egit.github.core.service.LabelService;
import org.eclipse.mylyn.internal.github.core.GitHub;
import org.eclipse.mylyn.internal.github.core.GitHubTaskDataHandler;
import org.eclipse.mylyn.tasks.core.ITaskMapping;
import org.eclipse.mylyn.tasks.core.RepositoryResponse;
import org.eclipse.mylyn.tasks.core.RepositoryResponse.ResponseKind;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
/**
* GitHub issue task data handler
*/
public class IssueTaskDataHandler extends GitHubTaskDataHandler {
private static final String DATA_VERSION = "1"; //$NON-NLS-1$
private static final String MILESTONE_NONE_KEY = "0"; //$NON-NLS-1$
private final IssueConnector connector;
/**
* Create GitHub issue task data handler for connector
*
* @param connector
*/
public IssueTaskDataHandler(IssueConnector connector) {
this.connector = connector;
}
/**
* Create task data
*
* @param repository
* @param monitor
* @param user
* @param project
* @param issue
* @return task data
*/
public TaskData createTaskData(TaskRepository repository,
IProgressMonitor monitor, String user, String project, Issue issue) {
String key = Integer.toString(issue.getNumber());
TaskData data = new TaskData(getAttributeMapper(repository),
IssueConnector.KIND, repository.getRepositoryUrl(), key);
data.setVersion(DATA_VERSION);
createOperations(data, issue);
createAttribute(data, IssueAttribute.KEY.getMetadata(), key);
createAttribute(data, IssueAttribute.TITLE.getMetadata(),
issue.getTitle());
createAttribute(data, IssueAttribute.BODY.getMetadata(),
issue.getBody());
createAttribute(data, IssueAttribute.STATUS.getMetadata(),
issue.getState());
createAttribute(data, IssueAttribute.CREATION_DATE.getMetadata(),
issue.getCreatedAt());
createAttribute(data, IssueAttribute.MODIFICATION_DATE.getMetadata(),
issue.getUpdatedAt());
createAttribute(data, IssueAttribute.CLOSED_DATE.getMetadata(),
issue.getClosedAt());
User reporter = issue.getUser();
createAttribute(data, IssueAttribute.REPORTER.getMetadata(), reporter,
repository);
String reporterGravatar = reporter != null ? reporter.getAvatarUrl()
: null;
createAttribute(data, IssueAttribute.REPORTER_GRAVATAR.getMetadata(),
reporterGravatar);
User assignee = issue.getAssignee();
createAttribute(data, IssueAttribute.ASSIGNEE.getMetadata(), assignee,
repository);
String assigneeGravatar = assignee != null ? assignee.getAvatarUrl()
: null;
createAttribute(data, IssueAttribute.ASSIGNEE_GRAVATAR.getMetadata(),
assigneeGravatar);
createAttribute(data, IssueAttribute.COMMENT_NEW.getMetadata());
createLabels(repository, data, issue);
createMilestones(repository, data, issue);
return data;
}
private void createMilestones(TaskRepository repository, TaskData data,
Issue issue) {
Milestone current = issue.getMilestone();
String number = current != null ? Integer.toString(current.getNumber())
: MILESTONE_NONE_KEY;
TaskAttribute milestoneAttribute = createAttribute(data,
IssueAttribute.MILESTONE.getMetadata(), number);
if (!connector.hasCachedMilestones(repository))
try {
connector.refreshMilestones(repository);
} catch (CoreException ignore) {
// Ignored
}
List<Milestone> cachedMilestones = connector.getMilestones(repository);
milestoneAttribute.putOption(MILESTONE_NONE_KEY,
Messages.IssueAttribute_MilestoneNone);
for (Milestone milestone : cachedMilestones)
milestoneAttribute.putOption(
Integer.toString(milestone.getNumber()),
milestone.getTitle());
}
private void createLabels(TaskRepository repository, TaskData data,
Issue issue) {
TaskAttribute labels = createAttribute(data, IssueAttribute.LABELS,
issue.getLabels());
if (!connector.hasCachedLabels(repository))
try {
connector.refreshLabels(repository);
} catch (CoreException ignore) {
// Ignored
}
List<Label> cachedLabels = connector.getLabels(repository);
for (Label label : cachedLabels)
labels.putOption(label.getName(), label.getName());
}
private void createOperations(TaskData data, Issue issue) {
createOperationAttribute(data);
if (!data.isNew()) {
String state = issue.getState();
if (state != null) {
addOperation(data, issue, IssueOperation.LEAVE, true);
if (state.equals(IssueService.STATE_OPEN))
addOperation(data, issue, IssueOperation.CLOSE, false);
else if (state.equals(IssueService.STATE_CLOSED))
addOperation(data, issue, IssueOperation.REOPEN, false);
}
}
}
private void addOperation(TaskData data, Issue issue,
IssueOperation operation, boolean isDefault) {
String id = operation.getId();
String label = createOperationLabel(issue, operation);
addOperation(data, id, label, isDefault);
}
private String createOperationLabel(Issue issue, IssueOperation operation) {
return operation == IssueOperation.LEAVE ? operation.getLabel()
+ issue.getState() : operation.getLabel();
}
/**
* Create task data for issue
*
* @param repository
* @param monitor
* @param user
* @param project
* @param issue
* @param comments
* @return task data
*/
public TaskData createTaskData(TaskRepository repository,
IProgressMonitor monitor, String user, String project, Issue issue,
List<Comment> comments) {
TaskData taskData = createTaskData(repository, monitor, user, project,
issue);
taskData.setPartial(false);
addComments(taskData.getRoot(), comments, repository);
return taskData;
}
private Issue createIssue(TaskData taskData) {
Issue issue = new Issue();
if (!taskData.isNew())
issue.setNumber(Integer.parseInt(taskData.getTaskId()));
issue.setBody(getAttributeValue(taskData,
IssueAttribute.BODY.getMetadata()));
issue.setTitle(getAttributeValue(taskData,
IssueAttribute.TITLE.getMetadata()));
String assigneeValue = getAttributeValue(taskData,
IssueAttribute.ASSIGNEE.getMetadata());
if (assigneeValue != null) {
if (assigneeValue.trim().length() == 0)
assigneeValue = null;
User assignee = new User().setName(assigneeValue);
issue.setAssignee(assignee);
}
String milestoneValue = getAttributeValue(taskData,
IssueAttribute.MILESTONE.getMetadata());
if (milestoneValue != null) {
Milestone milestone = new Milestone();
if (milestoneValue.length() > 0)
milestone.setNumber(Integer.parseInt(milestoneValue));
issue.setMilestone(milestone);
}
return issue;
}
private TaskAttribute createAttribute(TaskData data,
IssueAttribute attribute, List<Label> values) {
TaskAttribute attr = createAttribute(data, attribute.getMetadata());
if (values != null) {
List<String> labels = new ArrayList<String>(values.size());
for (Label label : values)
labels.add(label.getName());
data.getAttributeMapper().setValues(attr, labels);
}
return attr;
}
@Override
public boolean initializeTaskData(TaskRepository repository, TaskData data,
ITaskMapping initializationData, IProgressMonitor monitor)
throws CoreException {
data.setVersion(DATA_VERSION);
for (IssueAttribute attr : IssueAttribute.values())
if (attr.getMetadata().isInitTask())
createAttribute(data, attr.getMetadata(), (String) null);
Issue dummy = new Issue();
createLabels(repository, data, dummy);
createMilestones(repository, data, dummy);
return true;
}
/**
* Create any new labels that have been added to the issue and set the
* issues labels to the current value of labels attribute.
*
* @param user
* @param repo
* @param client
* @param repository
* @param data
* @param oldAttributes
* @param issue
*/
protected void updateLabels(String user, String repo, GitHubClient client,
TaskRepository repository, TaskData data,
Set<TaskAttribute> oldAttributes, Issue issue) {
TaskAttribute labelsAttribute = data.getRoot().getAttribute(
IssueAttribute.LABELS.getMetadata().getId());
if (oldAttributes.contains(labelsAttribute) || data.isNew()) {
LabelService labelService = new LabelService(client);
if (!connector.hasCachedLabels(repository))
try {
connector.refreshLabels(repository);
} catch (CoreException ignore) {
// Ignore
}
List<Label> currentLabels = connector.getLabels(repository);
List<Label> newLabels = new LinkedList<Label>();
List<Label> labels = new LinkedList<Label>();
for (String value : labelsAttribute.getValues()) {
Label label = new Label().setName(value);
if (!currentLabels.contains(label))
newLabels.add(label);
labels.add(label);
}
issue.setLabels(labels);
for (Label label : newLabels)
try {
labelService.createLabel(user, repo, label);
} catch (IOException e) {
// TODO detect failure and handle label already created
}
if (!newLabels.isEmpty())
try {
connector.refreshLabels(repository);
} catch (CoreException ignore) {
// Ignore
}
}
}
@Override
public RepositoryResponse postTaskData(TaskRepository repository,
TaskData taskData, Set<TaskAttribute> oldAttributes,
IProgressMonitor monitor) throws CoreException {
String taskId = taskData.getTaskId();
Issue issue = createIssue(taskData);
RepositoryId repo = GitHub.getRepository(repository.getRepositoryUrl());
try {
GitHubClient client = IssueConnector.createClient(repository);
boolean collaborator = isCollaborator(client, repo);
if (collaborator)
updateLabels(repo.getOwner(), repo.getName(), client,
repository, taskData, oldAttributes, issue);
IssueService service = new IssueService(client);
if (taskData.isNew()) {
issue.setState(IssueService.STATE_OPEN);
issue = service.createIssue(repo.getOwner(), repo.getName(),
issue);
taskId = Integer.toString(issue.getNumber());
} else {
// Handle new comment
String comment = getAttributeValue(taskData,
IssueAttribute.COMMENT_NEW.getMetadata());
if (comment != null && comment.length() > 0)
service.createComment(repo.getOwner(), repo.getName(),
taskId, comment);
boolean reporter = attributeMatchesUser(client,
IssueAttribute.REPORTER.getMetadata(), taskData);
if (collaborator || reporter) {
// Handle state change
TaskAttribute operationAttribute = taskData.getRoot()
.getAttribute(TaskAttribute.OPERATION);
if (operationAttribute != null) {
IssueOperation operation = IssueOperation
.fromId(operationAttribute.getValue());
- if (operation != IssueOperation.LEAVE)
- switch (operation) {
- case REOPEN:
- issue.setState(IssueService.STATE_OPEN);
- break;
- case CLOSE:
- issue.setState(IssueService.STATE_CLOSED);
- break;
- default:
- break;
- }
+ if (operation == IssueOperation.REOPEN)
+ issue.setState(IssueService.STATE_OPEN);
+ else if (operation == IssueOperation.CLOSE)
+ issue.setState(IssueService.STATE_CLOSED);
}
service.editIssue(repo.getOwner(), repo.getName(), issue);
}
}
return new RepositoryResponse(
taskData.isNew() ? ResponseKind.TASK_CREATED
: ResponseKind.TASK_UPDATED, taskId);
} catch (IOException e) {
throw new CoreException(GitHub.createWrappedStatus(e));
}
}
}
| true | true | public RepositoryResponse postTaskData(TaskRepository repository,
TaskData taskData, Set<TaskAttribute> oldAttributes,
IProgressMonitor monitor) throws CoreException {
String taskId = taskData.getTaskId();
Issue issue = createIssue(taskData);
RepositoryId repo = GitHub.getRepository(repository.getRepositoryUrl());
try {
GitHubClient client = IssueConnector.createClient(repository);
boolean collaborator = isCollaborator(client, repo);
if (collaborator)
updateLabels(repo.getOwner(), repo.getName(), client,
repository, taskData, oldAttributes, issue);
IssueService service = new IssueService(client);
if (taskData.isNew()) {
issue.setState(IssueService.STATE_OPEN);
issue = service.createIssue(repo.getOwner(), repo.getName(),
issue);
taskId = Integer.toString(issue.getNumber());
} else {
// Handle new comment
String comment = getAttributeValue(taskData,
IssueAttribute.COMMENT_NEW.getMetadata());
if (comment != null && comment.length() > 0)
service.createComment(repo.getOwner(), repo.getName(),
taskId, comment);
boolean reporter = attributeMatchesUser(client,
IssueAttribute.REPORTER.getMetadata(), taskData);
if (collaborator || reporter) {
// Handle state change
TaskAttribute operationAttribute = taskData.getRoot()
.getAttribute(TaskAttribute.OPERATION);
if (operationAttribute != null) {
IssueOperation operation = IssueOperation
.fromId(operationAttribute.getValue());
if (operation != IssueOperation.LEAVE)
switch (operation) {
case REOPEN:
issue.setState(IssueService.STATE_OPEN);
break;
case CLOSE:
issue.setState(IssueService.STATE_CLOSED);
break;
default:
break;
}
}
service.editIssue(repo.getOwner(), repo.getName(), issue);
}
}
return new RepositoryResponse(
taskData.isNew() ? ResponseKind.TASK_CREATED
: ResponseKind.TASK_UPDATED, taskId);
} catch (IOException e) {
throw new CoreException(GitHub.createWrappedStatus(e));
}
}
| public RepositoryResponse postTaskData(TaskRepository repository,
TaskData taskData, Set<TaskAttribute> oldAttributes,
IProgressMonitor monitor) throws CoreException {
String taskId = taskData.getTaskId();
Issue issue = createIssue(taskData);
RepositoryId repo = GitHub.getRepository(repository.getRepositoryUrl());
try {
GitHubClient client = IssueConnector.createClient(repository);
boolean collaborator = isCollaborator(client, repo);
if (collaborator)
updateLabels(repo.getOwner(), repo.getName(), client,
repository, taskData, oldAttributes, issue);
IssueService service = new IssueService(client);
if (taskData.isNew()) {
issue.setState(IssueService.STATE_OPEN);
issue = service.createIssue(repo.getOwner(), repo.getName(),
issue);
taskId = Integer.toString(issue.getNumber());
} else {
// Handle new comment
String comment = getAttributeValue(taskData,
IssueAttribute.COMMENT_NEW.getMetadata());
if (comment != null && comment.length() > 0)
service.createComment(repo.getOwner(), repo.getName(),
taskId, comment);
boolean reporter = attributeMatchesUser(client,
IssueAttribute.REPORTER.getMetadata(), taskData);
if (collaborator || reporter) {
// Handle state change
TaskAttribute operationAttribute = taskData.getRoot()
.getAttribute(TaskAttribute.OPERATION);
if (operationAttribute != null) {
IssueOperation operation = IssueOperation
.fromId(operationAttribute.getValue());
if (operation == IssueOperation.REOPEN)
issue.setState(IssueService.STATE_OPEN);
else if (operation == IssueOperation.CLOSE)
issue.setState(IssueService.STATE_CLOSED);
}
service.editIssue(repo.getOwner(), repo.getName(), issue);
}
}
return new RepositoryResponse(
taskData.isNew() ? ResponseKind.TASK_CREATED
: ResponseKind.TASK_UPDATED, taskId);
} catch (IOException e) {
throw new CoreException(GitHub.createWrappedStatus(e));
}
}
|
diff --git a/ini/trakem2/tree/LayerTree.java b/ini/trakem2/tree/LayerTree.java
index 7a0dba23..bd42f47f 100644
--- a/ini/trakem2/tree/LayerTree.java
+++ b/ini/trakem2/tree/LayerTree.java
@@ -1,717 +1,717 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-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.tree;
import ij.gui.GenericDialog;
import ini.trakem2.ControlWindow;
import ini.trakem2.Project;
import ini.trakem2.display.Display;
import ini.trakem2.display.Displayable;
import ini.trakem2.display.DLabel;
import ini.trakem2.display.DoStep;
import ini.trakem2.display.Layer;
import ini.trakem2.display.LayerSet;
import ini.trakem2.persistence.DBObject;
import ini.trakem2.persistence.FSLoader;
import ini.trakem2.utils.IJError;
import ini.trakem2.utils.Utils;
import ini.trakem2.utils.Search;
import java.awt.Component;
import java.awt.Point;
import java.awt.Color;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Hashtable;
import java.util.Iterator;
//import java.util.Enumeration;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.JLabel;
import javax.swing.JTree;
public final class LayerTree extends DNDTree implements MouseListener, ActionListener {
private DefaultMutableTreeNode selected_node = null;
public LayerTree(Project project, LayerThing root) {
super(project, DNDTree.makeNode(root), new Color(230, 235, 255)); // Color(200, 200, 255));
setEditable(false);
addMouseListener(this);
// enable multiple discontiguous selection
this.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
/** Get a custom, context-sensitive popup menu for the selected node. */
private JPopupMenu getPopupMenu(DefaultMutableTreeNode node) {
Object ob = node.getUserObject();
LayerThing thing = null;
if (ob instanceof LayerThing) {
thing = (LayerThing)ob;
} else {
return null;
}
// context-sensitive popup
JMenuItem[] item = thing.getPopupItems(this);
if (0 == item.length) return null;
JPopupMenu popup = new JPopupMenu();
for (int i=0; i<item.length; i++) {
if (null == item[i] || "" == item[i].getText()) popup.addSeparator();
else popup.add(item[i]);
}
return popup;
}
public void mousePressed(MouseEvent me) {
Object source = me.getSource();
if (!source.equals(this) || !Project.getInstance(this).isInputEnabled()) {
return;
}
// ignore if doing multiple selection
if (!Utils.isPopupTrigger(me) && (me.isShiftDown() || (!ij.IJ.isMacOSX() && me.isControlDown()))) {
return;
}
int x = me.getX();
int y = me.getY();
// check if there is a multiple selection
TreePath[] paths = this.getSelectionPaths();
if (null != paths && paths.length > 1) {
if (Utils.isPopupTrigger(me)) {
// check that all items are of the same type
String type_first = ((LayerThing)((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject()).getType();
for (int i=1; i<paths.length; i++) {
String type = ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getType();
if (!type.equals(type_first)) {
Utils.showMessage("All selected items must be of the same type for operations on multiple items.");
return;
}
}
// prepare popup menu
JPopupMenu popup = new JPopupMenu();
JMenuItem item = null;
if (type_first.equals("layer")) {
item = new JMenuItem("Reverse layer Z coords"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Translate layers in Z..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Scale Z and thickness..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Delete..."); item.addActionListener(this); popup.add(item);
}
if (popup.getSubElements().length > 0) {
popup.show(this, x, y);
}
}
// disable commands depending upon a single node being selected
selected_node = null;
return;
}
// find the node and set it selected
TreePath path = getPathForLocation(x, y);
if (null == path) {
return;
}
setSelectionPath(path);
selected_node = (DefaultMutableTreeNode)path.getLastPathComponent();
if (2 == me.getClickCount() && !Utils.isPopupTrigger(me) && MouseEvent.BUTTON1 == me.getButton()) {
// create a new Display
LayerThing thing = (LayerThing)selected_node.getUserObject();
DBObject ob = (DBObject)thing.getObject();
if (thing.getType().toLowerCase().replace('_', ' ').equals("layer set") && null == ((LayerSet)ob).getParent()) { // the top level LayerSet
return;
}
//new Display(ob.getProject(), thing.getType().toLowerCase().equals("layer") ? (Layer)ob : ((LayerSet)ob).getParent());
Display.createDisplay(ob.getProject(), thing.getType().toLowerCase().equals("layer") ? (Layer)ob : ((LayerSet)ob).getParent());
return;
} else if (Utils.isPopupTrigger(me)) {
JPopupMenu popup = getPopupMenu(selected_node);
if (null == popup) return;
popup.show(this, x, y);
return;
}
}
public void mouseDragged(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseClicked(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) {
try {
String command = ae.getActionCommand();
// commands for multiple selections:
TreePath[] paths = this.getSelectionPaths();
if (null != paths && paths.length > 1) {
if (command.equals("Reverse layer Z coords")) {
// check that all layers belong to the same layer set
// just do it
Layer[] layer = new Layer[paths.length];
LayerSet ls = null;
for (int i=0; i<paths.length; i++) {
layer[i] = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
if (null == ls) ls = layer[i].getParent();
else if (!ls.equals(layer[i].getParent())) {
Utils.showMessage("To reverse, all layers must belong to the same layer set");
return;
}
}
final ArrayList<Layer> al = new ArrayList<Layer>();
for (int i=0; i<layer.length; i++) al.add(layer[i]);
ls.addLayerEditedStep(al);
// ASSSUMING layers are already Z ordered! CHECK
for (int i=0, j=layer.length-1; i<layer.length/2; i++, j--) {
double z = layer[i].getZ();
layer[i].setZ(layer[j].getZ());
layer[j].setZ(z);
}
updateList(ls);
ls.addLayerEditedStep(al);
Display.updateLayerScroller(ls);
} else if (command.equals("Translate layers in Z...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
HashSet hs_parents = new HashSet();
for (int i=0; i<paths.length; i++) {
Layer layer = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
layer.setZ(layer.getZ() + dz);
hs_parents.add(layer.getParent());
}
for (Iterator it = hs_parents.iterator(); it.hasNext(); ) {
updateList((LayerSet)it.next());
}
// now update all profile's Z ordering in the ProjectTree
final Project project = Project.getInstance(this);
ProjectThing root_pt = project.getRootProjectThing();
ArrayList al_pl = root_pt.findChildrenOfType("profile_list");
for (Iterator it = al_pl.iterator(); it.hasNext(); ) {
ProjectThing pt = (ProjectThing)it.next();
pt.fixZOrdering();
project.getProjectTree().updateList(pt);
}
project.getProjectTree().updateUILater();
//Display.updateLayerScroller((LayerSet)((DefaultMutableTreeNode)getModel().getRoot()).getUserObject());
} else if (command.equals("Delete...")) {
if (!Utils.check("Really remove all selected layers?")) return;
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
if (!layer.remove(false)) {
Utils.showMessage("Could not delete layer " + layer);
this.updateUILater();
return;
}
if (lt.remove(false)) {
((DefaultTreeModel)this.getModel()).removeNodeFromParent(lnode);
}
}
this.updateUILater();
} else if (command.equals("Scale Z and thickness...")) {
GenericDialog gd = new GenericDialog("Scale Z");
gd.addNumericField("scale: ", 1.0, 2);
gd.showDialog();
double scale = gd.getNextNumber();
if (Double.isNaN(scale) || 0 == scale) {
Utils.showMessage("Imvalid scaling factor: " + scale);
return;
}
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
layer.setZ(layer.getZ() * scale);
layer.setThickness(layer.getThickness() * scale);
}
this.updateUILater();
} else {
Utils.showMessage("Don't know what to do with command " + command + " for multiple selected nodes");
}
return;
}
// commands for single selection:
if (null == selected_node) return;
LayerThing thing = (LayerThing)selected_node.getUserObject();
LayerThing new_thing = null;
TemplateThing tt = null;
Object ob = null;
int i_position = -1;
if (command.startsWith("new ")) {
String name = command.substring(4).toLowerCase();
if (name.equals("layer")) {
// Create new Layer and add it to the selected node
LayerSet set = (LayerSet)thing.getObject();
Layer new_layer = Layer.create(thing.getProject(), set);
if (null == new_layer) return;
tt = thing.getChildTemplate("layer");
ob = new_layer;
Display.updateTitle(set);
} else if (name.equals("layer set")) { // with space in the middle
// Create a new LayerSet and add it in the middle
Layer layer = (Layer)thing.getObject();
LayerSet new_set = layer.getParent().create(layer);
if (null == new_set) return;
layer.add(new_set);
// add it at the end of the list
- tt = thing.getChildTemplate("layer_set");
+ tt = thing.getChildTemplate("layer set"); // with space, not underscore
ob = new_set;
i_position = selected_node.getChildCount();
Display.update(layer);
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
} else if (command.equals("many new layers...")) {
LayerSet set = (LayerSet)thing.getObject();
Layer[] layer = Layer.createMany(set.getProject(), set);
// add them to the tree as LayerThing
if (null == layer) return;
for (int i=0; i<layer.length; i++) {
addLayer(set, layer[i]); // null layers will be skipped
}
Display.updateTitle(set);
return;
} else if (command.equals("Show")) {
// create a new Display
DBObject dbo = (DBObject)thing.getObject();
if (thing.getType().equals("layer_set") && null == ((LayerSet)dbo).getParent()) return; // the top level LayerSet
new Display(dbo.getProject(), thing.getType().equals("layer") ? (Layer)dbo : ((LayerSet)dbo).getParent());
return;
} else if (command.equals("Show centered in Display")) {
LayerSet ls = (LayerSet)thing.getObject();
Display.showCentered(ls.getParent(), ls, false, false);
} else if (command.equals("Delete...")) {
remove(true, thing, selected_node);
return;
} else if (command.equals("Import stack...")) {
DBObject dbo = (DBObject)thing.getObject();
if (thing.getObject() instanceof LayerSet) {
LayerSet set = (LayerSet)thing.getObject();
Layer layer = null;
if (0 == set.getLayers().size()) {
layer = Layer.create(set.getProject(), set);
if (null == layer) return;
tt = thing.getChildTemplate("Layer");
ob = layer;
} else return; // click on a desired, existing layer.
if (null == layer) return;
layer.getProject().getLoader().importStack(layer, null, true);
} else if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importStack(layer, null, true);
return;
}
} else if (command.equals("Import grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importGrid(layer);
}
} else if (command.equals("Import sequence as grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importSequenceAsGrid(layer);
}
} else if (command.equals("Import from text file...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importImages(layer);
}
} else if (command.equals("Resize LayerSet...")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Resize LayerSet");
gd.addNumericField("new width: ", ls.getLayerWidth(), 3);
gd.addNumericField("new height: ",ls.getLayerHeight(),3);
gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_width = gd.getNextNumber();
double new_height =gd.getNextNumber();
ls.setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects
}
} else if (command.equals("Autoresize LayerSet")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ls.setMinimumDimensions();
}
} else if (command.equals("Adjust...")) {
if (thing.getObject() instanceof Layer) {
Layer layer= (Layer)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Adjust Layer");
gd.addNumericField("new z: ", layer.getZ(), 4);
gd.addNumericField("new thickness: ",layer.getThickness(),4);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_z = gd.getNextNumber();
layer.setThickness(gd.getNextNumber());
if (new_z != layer.getZ()) {
layer.setZ(new_z);
// move in the tree
/*
DefaultMutableTreeNode child = findNode(thing, this);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)child.getParent();
parent.remove(child);
// reinsert
int n = parent.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("Layer")) continue;
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < new_z) continue;
// else, add the layer here, after this one
break;
}
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
*/
// fix tree crappiness (empty slot ?!?)
/* // the fix doesn't work. ARGH TODO
Enumeration e = parent.children();
parent.removeAllChildren();
i = 0;
while (e.hasMoreElements()) {
//parent.add((DefaultMutableTreeNode)e.nextElement());
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
i++;
}*/
// easier and correct: overkill
updateList(layer.getParent());
// set selected
DefaultMutableTreeNode child = findNode(thing, this);
TreePath treePath = new TreePath(child.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
}
}
return;
} else if (command.equals("Rename...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Rename");
gd.addStringField("new name: ", thing.getTitle());
gd.showDialog();
if (gd.wasCanceled()) return;
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
thing.setTitle(gd.getNextString());
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
} else if (command.equals("Translate layers in Z...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start; i<=i_end; i++) {
Layer layer = (Layer)al_layers.get(i);
layer.setZ(layer.getZ() + dz);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Reverse layer Z coords...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Reverse Z coordinates of selected range:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.showDialog();
if (gd.wasCanceled()) return;
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start, j=i_end; i<i_end/2; i++, j--) {
Layer layer1 = (Layer)al_layers.get(i);
double z1 = layer1.getZ();
Layer layer2 = (Layer)al_layers.get(j);
layer1.setZ(layer2.getZ());
layer2.setZ(z1);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Search...")) {
new Search();
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
if (null == tt) return;
new_thing = new LayerThing(tt, thing.getProject(), ob);
if (-1 == i_position && new_thing.getType().equals("layer")) {
// find the node whose 'z' is larger than z, and add the Layer before that.
// (just because there could be objects other than LayerThing with a Layer in it in the future, so set.getLayers().indexOf(layer) may not be useful)
double z = ((Layer)ob).getZ();
int n = selected_node.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)selected_node.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("layer")) {
continue;
}
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < z) {
continue;
}
// else, add the layer here, after this one
break;
}
i_position = i;
}
thing.addChild(new_thing);
DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
((DefaultTreeModel)this.getModel()).insertNodeInto(new_node, selected_node, i_position);
TreePath treePath = new TreePath(new_node.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
} catch (Exception e) {
IJError.print(e);
}
}
public boolean remove(Layer layer, boolean check) {
DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.getModel().getRoot();
LayerThing thing = (LayerThing)(((LayerThing)root.getUserObject()).findChild(layer));
if (null == thing) { Utils.log2("LayerTree.remove(Layer): thing not found"); return false; }
DefaultMutableTreeNode node = DNDTree.findNode(thing, this);
if (null == node) { Utils.log2("LayerTree.remove(Layer): node not found"); return false; }
if (thing.remove(check)) {
((DefaultTreeModel)this.getModel()).removeNodeFromParent(node);
this.updateUILater();
}
return true;
}
/** Used by the Loader.importStack and the "many new layers" command. */
public void addLayer(LayerSet layer_set, Layer layer) {
if (null == layer_set || null == layer) return;
try {
// find the node that contains the LayerSet
DefaultMutableTreeNode root_node = (DefaultMutableTreeNode)this.getModel().getRoot();
LayerThing root_lt = (LayerThing)root_node.getUserObject();
Thing thing = null;
if (root_lt.getObject().equals(layer_set)) thing = root_lt;
else thing = root_lt.findChild(layer_set);
DefaultMutableTreeNode parent_node = DNDTree.findNode(thing, this);
if (null == parent_node) { Utils.log("LayerTree: LayerSet not found."); return; }
LayerThing parent_thing = (LayerThing)parent_node.getUserObject();
double z = layer.getZ();
// find the node whose 'z' is larger than z, and add the Layer before that.
int n = parent_node.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent_node.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("layer")) {
continue;
}
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < z) {
continue;
}
// else, add the layer here, after the 'i' layer which has a larger z
break;
}
TemplateThing tt = parent_thing.getChildTemplate("layer");
if (null == tt) {
Utils.log("LayerTree: Null template Thing!");
return;
}
LayerThing new_thing = new LayerThing(tt, layer.getProject(), layer);
// Add the new_thing to the tree
if (null != new_thing) {
parent_thing.addChild(new_thing);
DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
//TODO when changing the Z of a layer, the insertion is proper but an empty space is left //Utils.log("LayerTree: inserting at: " + i);
((DefaultTreeModel)this.getModel()).insertNodeInto(new_node, parent_node, i);
TreePath treePath = new TreePath(new_node.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
}
} catch (Exception e) { IJError.print(e); }
}
public void destroy() {
super.destroy();
this.selected_node = null;
}
/** Remove all layer nodes from the given layer_set, and add them again according to the layer's Z value. */
public void updateList(LayerSet layer_set) {
// store scrolling position for restoring purposes
/*
Component c = this.getParent();
Point point = null;
if (c instanceof JScrollPane) {
point = ((JScrollPane)c).getViewport().getViewPosition();
}
*/
LayerThing lt = layer_set.getProject().findLayerThing(layer_set);
if (null == lt) {
Utils.log2("LayerTree.updateList: could not find LayerSet " + layer_set);
return;
}
// call super
updateList(lt);
/*
DefaultMutableTreeNode ls_node = DNDTree.findNode(lt, this);
if (null == ls_node) {
Utils.log2("LayerTree.updateList: could not find a node for LayerThing " + lt);
return;
}
Hashtable ht = new Hashtable();
for (Enumeration e = ls_node.children(); e.hasMoreElements(); ) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.nextElement();
ht.put(node.getUserObject(), node);
}
ls_node.removeAllChildren();
for (Iterator it = lt.getChildren().iterator(); it.hasNext(); ) {
Object ob = ht.remove(it.next());
ls_node.add((DefaultMutableTreeNode)ob);
}
if (0 != ht.size()) {
Utils.log2("WARNING LayerTree.updateList: did not end up adding this nodes:");
for (Iterator it = ht.keySet().iterator(); it.hasNext(); ) {
Utils.log2(it.next().toString());
}
}
this.updateUILater();
// restore viewport position
if (null != point) {
((JScrollPane)c).getViewport().setViewPosition(point);
}
*/
// what the hell:
this.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
}
/** If the given node is null, it will be searched for. */
public boolean remove(boolean check, LayerThing thing, DefaultMutableTreeNode node) {
if (null == thing || null == thing.getParent()) return false; // can't remove the root LayerSet
return thing.remove(check) && removeNode(null != node ? node : findNode(thing, this));
}
protected DNDTree.NodeRenderer createNodeRenderer() {
return new LayerThingNodeRender();
}
static private final Color FRONT_LAYER_COLOR = new Color(1.0f, 1.0f, 0.4f, 0.5f);
protected final class LayerThingNodeRender extends DNDTree.NodeRenderer {
public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) {
final JLabel label = (JLabel)super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
label.setText(label.getText().replace('_', ' ')); // just for display
try {
if (value.getClass() == DefaultMutableTreeNode.class) {
final Object obb = ((DefaultMutableTreeNode)value).getUserObject();
if (!(obb instanceof LayerThing)) {
Utils.log2("WARNING: not a LayerThing: obb is " + obb.getClass() + " and contains " + obb + " " + ((Thing)obb).getObject());
}
final Object ob = ((Thing)obb).getObject();
final Layer layer = Display.getFrontLayer();
if (ob == layer) {
label.setOpaque(true); //this label
label.setBackground(FRONT_LAYER_COLOR); // this label
} else if (ob.getClass() == LayerSet.class && null != layer && layer.contains((Displayable)ob)) {
label.setOpaque(true); //this label
label.setBackground(ProjectTree.ACTIVE_DISPL_COLOR); // this label
} else {
label.setOpaque(false); //this label
label.setBackground(background);
}
}
} catch (Throwable t) {
t.printStackTrace();
}
return label;
}
}
}
| true | true | public void actionPerformed(ActionEvent ae) {
try {
String command = ae.getActionCommand();
// commands for multiple selections:
TreePath[] paths = this.getSelectionPaths();
if (null != paths && paths.length > 1) {
if (command.equals("Reverse layer Z coords")) {
// check that all layers belong to the same layer set
// just do it
Layer[] layer = new Layer[paths.length];
LayerSet ls = null;
for (int i=0; i<paths.length; i++) {
layer[i] = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
if (null == ls) ls = layer[i].getParent();
else if (!ls.equals(layer[i].getParent())) {
Utils.showMessage("To reverse, all layers must belong to the same layer set");
return;
}
}
final ArrayList<Layer> al = new ArrayList<Layer>();
for (int i=0; i<layer.length; i++) al.add(layer[i]);
ls.addLayerEditedStep(al);
// ASSSUMING layers are already Z ordered! CHECK
for (int i=0, j=layer.length-1; i<layer.length/2; i++, j--) {
double z = layer[i].getZ();
layer[i].setZ(layer[j].getZ());
layer[j].setZ(z);
}
updateList(ls);
ls.addLayerEditedStep(al);
Display.updateLayerScroller(ls);
} else if (command.equals("Translate layers in Z...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
HashSet hs_parents = new HashSet();
for (int i=0; i<paths.length; i++) {
Layer layer = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
layer.setZ(layer.getZ() + dz);
hs_parents.add(layer.getParent());
}
for (Iterator it = hs_parents.iterator(); it.hasNext(); ) {
updateList((LayerSet)it.next());
}
// now update all profile's Z ordering in the ProjectTree
final Project project = Project.getInstance(this);
ProjectThing root_pt = project.getRootProjectThing();
ArrayList al_pl = root_pt.findChildrenOfType("profile_list");
for (Iterator it = al_pl.iterator(); it.hasNext(); ) {
ProjectThing pt = (ProjectThing)it.next();
pt.fixZOrdering();
project.getProjectTree().updateList(pt);
}
project.getProjectTree().updateUILater();
//Display.updateLayerScroller((LayerSet)((DefaultMutableTreeNode)getModel().getRoot()).getUserObject());
} else if (command.equals("Delete...")) {
if (!Utils.check("Really remove all selected layers?")) return;
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
if (!layer.remove(false)) {
Utils.showMessage("Could not delete layer " + layer);
this.updateUILater();
return;
}
if (lt.remove(false)) {
((DefaultTreeModel)this.getModel()).removeNodeFromParent(lnode);
}
}
this.updateUILater();
} else if (command.equals("Scale Z and thickness...")) {
GenericDialog gd = new GenericDialog("Scale Z");
gd.addNumericField("scale: ", 1.0, 2);
gd.showDialog();
double scale = gd.getNextNumber();
if (Double.isNaN(scale) || 0 == scale) {
Utils.showMessage("Imvalid scaling factor: " + scale);
return;
}
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
layer.setZ(layer.getZ() * scale);
layer.setThickness(layer.getThickness() * scale);
}
this.updateUILater();
} else {
Utils.showMessage("Don't know what to do with command " + command + " for multiple selected nodes");
}
return;
}
// commands for single selection:
if (null == selected_node) return;
LayerThing thing = (LayerThing)selected_node.getUserObject();
LayerThing new_thing = null;
TemplateThing tt = null;
Object ob = null;
int i_position = -1;
if (command.startsWith("new ")) {
String name = command.substring(4).toLowerCase();
if (name.equals("layer")) {
// Create new Layer and add it to the selected node
LayerSet set = (LayerSet)thing.getObject();
Layer new_layer = Layer.create(thing.getProject(), set);
if (null == new_layer) return;
tt = thing.getChildTemplate("layer");
ob = new_layer;
Display.updateTitle(set);
} else if (name.equals("layer set")) { // with space in the middle
// Create a new LayerSet and add it in the middle
Layer layer = (Layer)thing.getObject();
LayerSet new_set = layer.getParent().create(layer);
if (null == new_set) return;
layer.add(new_set);
// add it at the end of the list
tt = thing.getChildTemplate("layer_set");
ob = new_set;
i_position = selected_node.getChildCount();
Display.update(layer);
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
} else if (command.equals("many new layers...")) {
LayerSet set = (LayerSet)thing.getObject();
Layer[] layer = Layer.createMany(set.getProject(), set);
// add them to the tree as LayerThing
if (null == layer) return;
for (int i=0; i<layer.length; i++) {
addLayer(set, layer[i]); // null layers will be skipped
}
Display.updateTitle(set);
return;
} else if (command.equals("Show")) {
// create a new Display
DBObject dbo = (DBObject)thing.getObject();
if (thing.getType().equals("layer_set") && null == ((LayerSet)dbo).getParent()) return; // the top level LayerSet
new Display(dbo.getProject(), thing.getType().equals("layer") ? (Layer)dbo : ((LayerSet)dbo).getParent());
return;
} else if (command.equals("Show centered in Display")) {
LayerSet ls = (LayerSet)thing.getObject();
Display.showCentered(ls.getParent(), ls, false, false);
} else if (command.equals("Delete...")) {
remove(true, thing, selected_node);
return;
} else if (command.equals("Import stack...")) {
DBObject dbo = (DBObject)thing.getObject();
if (thing.getObject() instanceof LayerSet) {
LayerSet set = (LayerSet)thing.getObject();
Layer layer = null;
if (0 == set.getLayers().size()) {
layer = Layer.create(set.getProject(), set);
if (null == layer) return;
tt = thing.getChildTemplate("Layer");
ob = layer;
} else return; // click on a desired, existing layer.
if (null == layer) return;
layer.getProject().getLoader().importStack(layer, null, true);
} else if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importStack(layer, null, true);
return;
}
} else if (command.equals("Import grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importGrid(layer);
}
} else if (command.equals("Import sequence as grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importSequenceAsGrid(layer);
}
} else if (command.equals("Import from text file...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importImages(layer);
}
} else if (command.equals("Resize LayerSet...")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Resize LayerSet");
gd.addNumericField("new width: ", ls.getLayerWidth(), 3);
gd.addNumericField("new height: ",ls.getLayerHeight(),3);
gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_width = gd.getNextNumber();
double new_height =gd.getNextNumber();
ls.setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects
}
} else if (command.equals("Autoresize LayerSet")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ls.setMinimumDimensions();
}
} else if (command.equals("Adjust...")) {
if (thing.getObject() instanceof Layer) {
Layer layer= (Layer)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Adjust Layer");
gd.addNumericField("new z: ", layer.getZ(), 4);
gd.addNumericField("new thickness: ",layer.getThickness(),4);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_z = gd.getNextNumber();
layer.setThickness(gd.getNextNumber());
if (new_z != layer.getZ()) {
layer.setZ(new_z);
// move in the tree
/*
DefaultMutableTreeNode child = findNode(thing, this);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)child.getParent();
parent.remove(child);
// reinsert
int n = parent.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("Layer")) continue;
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < new_z) continue;
// else, add the layer here, after this one
break;
}
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
*/
// fix tree crappiness (empty slot ?!?)
/* // the fix doesn't work. ARGH TODO
Enumeration e = parent.children();
parent.removeAllChildren();
i = 0;
while (e.hasMoreElements()) {
//parent.add((DefaultMutableTreeNode)e.nextElement());
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
i++;
}*/
// easier and correct: overkill
updateList(layer.getParent());
// set selected
DefaultMutableTreeNode child = findNode(thing, this);
TreePath treePath = new TreePath(child.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
}
}
return;
} else if (command.equals("Rename...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Rename");
gd.addStringField("new name: ", thing.getTitle());
gd.showDialog();
if (gd.wasCanceled()) return;
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
thing.setTitle(gd.getNextString());
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
} else if (command.equals("Translate layers in Z...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start; i<=i_end; i++) {
Layer layer = (Layer)al_layers.get(i);
layer.setZ(layer.getZ() + dz);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Reverse layer Z coords...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Reverse Z coordinates of selected range:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.showDialog();
if (gd.wasCanceled()) return;
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start, j=i_end; i<i_end/2; i++, j--) {
Layer layer1 = (Layer)al_layers.get(i);
double z1 = layer1.getZ();
Layer layer2 = (Layer)al_layers.get(j);
layer1.setZ(layer2.getZ());
layer2.setZ(z1);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Search...")) {
new Search();
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
if (null == tt) return;
new_thing = new LayerThing(tt, thing.getProject(), ob);
if (-1 == i_position && new_thing.getType().equals("layer")) {
// find the node whose 'z' is larger than z, and add the Layer before that.
// (just because there could be objects other than LayerThing with a Layer in it in the future, so set.getLayers().indexOf(layer) may not be useful)
double z = ((Layer)ob).getZ();
int n = selected_node.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)selected_node.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("layer")) {
continue;
}
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < z) {
continue;
}
// else, add the layer here, after this one
break;
}
i_position = i;
}
thing.addChild(new_thing);
DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
((DefaultTreeModel)this.getModel()).insertNodeInto(new_node, selected_node, i_position);
TreePath treePath = new TreePath(new_node.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
} catch (Exception e) {
IJError.print(e);
}
}
| public void actionPerformed(ActionEvent ae) {
try {
String command = ae.getActionCommand();
// commands for multiple selections:
TreePath[] paths = this.getSelectionPaths();
if (null != paths && paths.length > 1) {
if (command.equals("Reverse layer Z coords")) {
// check that all layers belong to the same layer set
// just do it
Layer[] layer = new Layer[paths.length];
LayerSet ls = null;
for (int i=0; i<paths.length; i++) {
layer[i] = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
if (null == ls) ls = layer[i].getParent();
else if (!ls.equals(layer[i].getParent())) {
Utils.showMessage("To reverse, all layers must belong to the same layer set");
return;
}
}
final ArrayList<Layer> al = new ArrayList<Layer>();
for (int i=0; i<layer.length; i++) al.add(layer[i]);
ls.addLayerEditedStep(al);
// ASSSUMING layers are already Z ordered! CHECK
for (int i=0, j=layer.length-1; i<layer.length/2; i++, j--) {
double z = layer[i].getZ();
layer[i].setZ(layer[j].getZ());
layer[j].setZ(z);
}
updateList(ls);
ls.addLayerEditedStep(al);
Display.updateLayerScroller(ls);
} else if (command.equals("Translate layers in Z...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
HashSet hs_parents = new HashSet();
for (int i=0; i<paths.length; i++) {
Layer layer = (Layer) ((LayerThing)((DefaultMutableTreeNode)paths[i].getLastPathComponent()).getUserObject()).getObject();
layer.setZ(layer.getZ() + dz);
hs_parents.add(layer.getParent());
}
for (Iterator it = hs_parents.iterator(); it.hasNext(); ) {
updateList((LayerSet)it.next());
}
// now update all profile's Z ordering in the ProjectTree
final Project project = Project.getInstance(this);
ProjectThing root_pt = project.getRootProjectThing();
ArrayList al_pl = root_pt.findChildrenOfType("profile_list");
for (Iterator it = al_pl.iterator(); it.hasNext(); ) {
ProjectThing pt = (ProjectThing)it.next();
pt.fixZOrdering();
project.getProjectTree().updateList(pt);
}
project.getProjectTree().updateUILater();
//Display.updateLayerScroller((LayerSet)((DefaultMutableTreeNode)getModel().getRoot()).getUserObject());
} else if (command.equals("Delete...")) {
if (!Utils.check("Really remove all selected layers?")) return;
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
if (!layer.remove(false)) {
Utils.showMessage("Could not delete layer " + layer);
this.updateUILater();
return;
}
if (lt.remove(false)) {
((DefaultTreeModel)this.getModel()).removeNodeFromParent(lnode);
}
}
this.updateUILater();
} else if (command.equals("Scale Z and thickness...")) {
GenericDialog gd = new GenericDialog("Scale Z");
gd.addNumericField("scale: ", 1.0, 2);
gd.showDialog();
double scale = gd.getNextNumber();
if (Double.isNaN(scale) || 0 == scale) {
Utils.showMessage("Imvalid scaling factor: " + scale);
return;
}
for (int i=0; i<paths.length; i++) {
DefaultMutableTreeNode lnode = (DefaultMutableTreeNode)paths[i].getLastPathComponent();
LayerThing lt = (LayerThing)lnode.getUserObject();
Layer layer = (Layer)lt.getObject();
layer.setZ(layer.getZ() * scale);
layer.setThickness(layer.getThickness() * scale);
}
this.updateUILater();
} else {
Utils.showMessage("Don't know what to do with command " + command + " for multiple selected nodes");
}
return;
}
// commands for single selection:
if (null == selected_node) return;
LayerThing thing = (LayerThing)selected_node.getUserObject();
LayerThing new_thing = null;
TemplateThing tt = null;
Object ob = null;
int i_position = -1;
if (command.startsWith("new ")) {
String name = command.substring(4).toLowerCase();
if (name.equals("layer")) {
// Create new Layer and add it to the selected node
LayerSet set = (LayerSet)thing.getObject();
Layer new_layer = Layer.create(thing.getProject(), set);
if (null == new_layer) return;
tt = thing.getChildTemplate("layer");
ob = new_layer;
Display.updateTitle(set);
} else if (name.equals("layer set")) { // with space in the middle
// Create a new LayerSet and add it in the middle
Layer layer = (Layer)thing.getObject();
LayerSet new_set = layer.getParent().create(layer);
if (null == new_set) return;
layer.add(new_set);
// add it at the end of the list
tt = thing.getChildTemplate("layer set"); // with space, not underscore
ob = new_set;
i_position = selected_node.getChildCount();
Display.update(layer);
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
} else if (command.equals("many new layers...")) {
LayerSet set = (LayerSet)thing.getObject();
Layer[] layer = Layer.createMany(set.getProject(), set);
// add them to the tree as LayerThing
if (null == layer) return;
for (int i=0; i<layer.length; i++) {
addLayer(set, layer[i]); // null layers will be skipped
}
Display.updateTitle(set);
return;
} else if (command.equals("Show")) {
// create a new Display
DBObject dbo = (DBObject)thing.getObject();
if (thing.getType().equals("layer_set") && null == ((LayerSet)dbo).getParent()) return; // the top level LayerSet
new Display(dbo.getProject(), thing.getType().equals("layer") ? (Layer)dbo : ((LayerSet)dbo).getParent());
return;
} else if (command.equals("Show centered in Display")) {
LayerSet ls = (LayerSet)thing.getObject();
Display.showCentered(ls.getParent(), ls, false, false);
} else if (command.equals("Delete...")) {
remove(true, thing, selected_node);
return;
} else if (command.equals("Import stack...")) {
DBObject dbo = (DBObject)thing.getObject();
if (thing.getObject() instanceof LayerSet) {
LayerSet set = (LayerSet)thing.getObject();
Layer layer = null;
if (0 == set.getLayers().size()) {
layer = Layer.create(set.getProject(), set);
if (null == layer) return;
tt = thing.getChildTemplate("Layer");
ob = layer;
} else return; // click on a desired, existing layer.
if (null == layer) return;
layer.getProject().getLoader().importStack(layer, null, true);
} else if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importStack(layer, null, true);
return;
}
} else if (command.equals("Import grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importGrid(layer);
}
} else if (command.equals("Import sequence as grid...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importSequenceAsGrid(layer);
}
} else if (command.equals("Import from text file...")) {
if (thing.getObject() instanceof Layer) {
Layer layer = (Layer)thing.getObject();
layer.getProject().getLoader().importImages(layer);
}
} else if (command.equals("Resize LayerSet...")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Resize LayerSet");
gd.addNumericField("new width: ", ls.getLayerWidth(), 3);
gd.addNumericField("new height: ",ls.getLayerHeight(),3);
gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_width = gd.getNextNumber();
double new_height =gd.getNextNumber();
ls.setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects
}
} else if (command.equals("Autoresize LayerSet")) {
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ls.setMinimumDimensions();
}
} else if (command.equals("Adjust...")) {
if (thing.getObject() instanceof Layer) {
Layer layer= (Layer)thing.getObject();
ij.gui.GenericDialog gd = ControlWindow.makeGenericDialog("Adjust Layer");
gd.addNumericField("new z: ", layer.getZ(), 4);
gd.addNumericField("new thickness: ",layer.getThickness(),4);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_z = gd.getNextNumber();
layer.setThickness(gd.getNextNumber());
if (new_z != layer.getZ()) {
layer.setZ(new_z);
// move in the tree
/*
DefaultMutableTreeNode child = findNode(thing, this);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode)child.getParent();
parent.remove(child);
// reinsert
int n = parent.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)parent.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("Layer")) continue;
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < new_z) continue;
// else, add the layer here, after this one
break;
}
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
*/
// fix tree crappiness (empty slot ?!?)
/* // the fix doesn't work. ARGH TODO
Enumeration e = parent.children();
parent.removeAllChildren();
i = 0;
while (e.hasMoreElements()) {
//parent.add((DefaultMutableTreeNode)e.nextElement());
((DefaultTreeModel)this.getModel()).insertNodeInto(child, parent, i);
i++;
}*/
// easier and correct: overkill
updateList(layer.getParent());
// set selected
DefaultMutableTreeNode child = findNode(thing, this);
TreePath treePath = new TreePath(child.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
}
}
return;
} else if (command.equals("Rename...")) {
GenericDialog gd = ControlWindow.makeGenericDialog("Rename");
gd.addStringField("new name: ", thing.getTitle());
gd.showDialog();
if (gd.wasCanceled()) return;
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
thing.setTitle(gd.getNextString());
project.getRootLayerSet().addUndoStep(new RenameThingStep(thing));
} else if (command.equals("Translate layers in Z...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Translate selected range in the Z axis:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.addNumericField("by: ", 0, 4);
gd.showDialog();
if (gd.wasCanceled()) return;
// else, displace
double dz = gd.getNextNumber();
if (Double.isNaN(dz)) {
Utils.showMessage("Invalid number");
return;
}
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start; i<=i_end; i++) {
Layer layer = (Layer)al_layers.get(i);
layer.setZ(layer.getZ() + dz);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Reverse layer Z coords...")) {
/// TODO: this method should use multiple selections directly on the tree
if (thing.getObject() instanceof LayerSet) {
LayerSet ls = (LayerSet)thing.getObject();
ArrayList al_layers = ls.getLayers();
String[] layer_names = new String[al_layers.size()];
for (int i=0; i<layer_names.length; i++) {
layer_names[i] = ls.getProject().findLayerThing(al_layers.get(i)).toString();
}
GenericDialog gd = ControlWindow.makeGenericDialog("Range");
gd.addMessage("Reverse Z coordinates of selected range:");
gd.addChoice("from: ", layer_names, layer_names[0]);
gd.addChoice("to: ", layer_names, layer_names[layer_names.length-1]);
gd.showDialog();
if (gd.wasCanceled()) return;
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
for (int i = i_start, j=i_end; i<i_end/2; i++, j--) {
Layer layer1 = (Layer)al_layers.get(i);
double z1 = layer1.getZ();
Layer layer2 = (Layer)al_layers.get(j);
layer1.setZ(layer2.getZ());
layer2.setZ(z1);
}
// update node labels and position
updateList(ls);
}
} else if (command.equals("Search...")) {
new Search();
} else {
Utils.log("LayerTree.actionPerformed: don't know what to do with the command: " + command);
return;
}
if (null == tt) return;
new_thing = new LayerThing(tt, thing.getProject(), ob);
if (-1 == i_position && new_thing.getType().equals("layer")) {
// find the node whose 'z' is larger than z, and add the Layer before that.
// (just because there could be objects other than LayerThing with a Layer in it in the future, so set.getLayers().indexOf(layer) may not be useful)
double z = ((Layer)ob).getZ();
int n = selected_node.getChildCount();
int i = 0;
for (; i < n; i++) {
DefaultMutableTreeNode child_node = (DefaultMutableTreeNode)selected_node.getChildAt(i);
LayerThing child_thing = (LayerThing)child_node.getUserObject();
if (!child_thing.getType().equals("layer")) {
continue;
}
double iz = ((Layer)child_thing.getObject()).getZ();
if (iz < z) {
continue;
}
// else, add the layer here, after this one
break;
}
i_position = i;
}
thing.addChild(new_thing);
DefaultMutableTreeNode new_node = new DefaultMutableTreeNode(new_thing);
((DefaultTreeModel)this.getModel()).insertNodeInto(new_node, selected_node, i_position);
TreePath treePath = new TreePath(new_node.getPath());
this.scrollPathToVisible(treePath);
this.setSelectionPath(treePath);
} catch (Exception e) {
IJError.print(e);
}
}
|
diff --git a/src/gov/nist/javax/sip/stack/SIPDialog.java b/src/gov/nist/javax/sip/stack/SIPDialog.java
index 34790693..67f2daed 100755
--- a/src/gov/nist/javax/sip/stack/SIPDialog.java
+++ b/src/gov/nist/javax/sip/stack/SIPDialog.java
@@ -1,4228 +1,4228 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/**************************************************************************/
/* Product of NIST Advanced Networking Technologies Division */
/**************************************************************************/
package gov.nist.javax.sip.stack;
import gov.nist.core.CommonLogger;
import gov.nist.core.InternalErrorHandler;
import gov.nist.core.LogLevels;
import gov.nist.core.LogWriter;
import gov.nist.core.NameValueList;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.DialogExt;
import gov.nist.javax.sip.ListeningPointImpl;
import gov.nist.javax.sip.SipListenerExt;
import gov.nist.javax.sip.SipProviderImpl;
import gov.nist.javax.sip.SipStackImpl;
import gov.nist.javax.sip.Utils;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.header.Authorization;
import gov.nist.javax.sip.header.CSeq;
import gov.nist.javax.sip.header.Contact;
import gov.nist.javax.sip.header.ContactList;
import gov.nist.javax.sip.header.From;
import gov.nist.javax.sip.header.MaxForwards;
import gov.nist.javax.sip.header.RAck;
import gov.nist.javax.sip.header.RSeq;
import gov.nist.javax.sip.header.Reason;
import gov.nist.javax.sip.header.RecordRoute;
import gov.nist.javax.sip.header.RecordRouteList;
import gov.nist.javax.sip.header.Require;
import gov.nist.javax.sip.header.Route;
import gov.nist.javax.sip.header.RouteList;
import gov.nist.javax.sip.header.SIPHeader;
import gov.nist.javax.sip.header.TimeStamp;
import gov.nist.javax.sip.header.To;
import gov.nist.javax.sip.header.Via;
import gov.nist.javax.sip.message.MessageFactoryImpl;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.parser.AddressParser;
import gov.nist.javax.sip.parser.CallIDParser;
import gov.nist.javax.sip.parser.ContactParser;
import gov.nist.javax.sip.parser.RecordRouteParser;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.InetAddress;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.sip.ClientTransaction;
import javax.sip.DialogDoesNotExistException;
import javax.sip.DialogState;
import javax.sip.IOExceptionEvent;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint;
import javax.sip.ObjectInUseException;
import javax.sip.SipException;
import javax.sip.Transaction;
import javax.sip.TransactionDoesNotExistException;
import javax.sip.TransactionState;
import javax.sip.address.Address;
import javax.sip.address.Hop;
import javax.sip.address.SipURI;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.EventHeader;
import javax.sip.header.OptionTag;
import javax.sip.header.ProxyAuthorizationHeader;
import javax.sip.header.RAckHeader;
import javax.sip.header.RSeqHeader;
import javax.sip.header.ReasonHeader;
import javax.sip.header.RequireHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.SupportedHeader;
import javax.sip.header.TimeStampHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
/*
* Acknowledgements:
*
* Bugs in this class were reported by Antonis Karydas, Brad Templeton, Jeff Adams, Alex Rootham ,
* Martin Le Clerk, Christophe Anzille, Andreas Bystrom, Lebing Xie, Jeroen van Bemmel. Hagai Sela
* reported a bug in updating the route set (on RE-INVITE). Jens Tinfors submitted a bug fix and
* the .equals method. Jan Schaumloeffel contributed a buf fix ( memory leak was happening when
* 180 contained a To tag. Bug fixes by Vladimir Ralev (Redhat).
* Performance enhancements and memory reduction enhancements by Jean Deruelle.
*
*/
/**
* Tracks dialogs. A dialog is a peer to peer association of communicating SIP
* entities. For INVITE transactions, a Dialog is created when a success message
* is received (i.e. a response that has a To tag). The SIP Protocol stores
* enough state in the message structure to extract a dialog identifier that can
* be used to retrieve this structure from the SipStack.
*
* @version 1.2 $Revision: 1.207 $ $Date: 2010-12-02 22:04:14 $
*
* @author M. Ranganathan
*
*
*/
public class SIPDialog implements javax.sip.Dialog, DialogExt {
private static StackLogger logger = CommonLogger.getLogger(SIPDialog.class);
private static final long serialVersionUID = -1429794423085204069L;
private transient boolean dialogTerminatedEventDelivered; // prevent
// duplicate
private transient String stackTrace; // for semaphore debugging.
protected String method;
// delivery of the event
protected transient boolean isAssigned;
protected boolean reInviteFlag;
private transient Object applicationData; // Opaque pointer to application
// data.
private transient SIPRequest originalRequest;
// jeand : avoid keeping the original request ref above for too long (mem
// saving)
protected transient String originalRequestRecordRouteHeadersString;
protected transient RecordRouteList originalRequestRecordRouteHeaders;
// Last response (JvB: either sent or received).
// jeand replaced the last response with only the data from it needed to
// save on mem
protected String lastResponseDialogId;
private Via lastResponseTopMostVia;
protected Integer lastResponseStatusCode;
protected long lastResponseCSeqNumber;
protected String lastResponseMethod;
protected String lastResponseFromTag;
protected String lastResponseToTag;
// jeand: needed for reliable response sending but nullifyed right after the
// ACK has been received or sent to let go of the ref ASAP
protected SIPTransaction firstTransaction;
// jeand needed for checking 491 but nullifyed right after the ACK has been
// received or sent to let go of the ref ASAP
protected SIPTransaction lastTransaction;
protected String dialogId;
protected transient String earlyDialogId;
protected long localSequenceNumber;
protected long remoteSequenceNumber;
protected String myTag;
protected String hisTag;
protected RouteList routeList;
private transient SIPTransactionStack sipStack;
private int dialogState;
protected transient SIPRequest lastAckSent;
// jeand : replaced the lastAckReceived message with only the data needed to
// save on mem
protected Long lastAckReceivedCSeqNumber;
// could be set on recovery by examining the method looks like a duplicate
// of ackSeen
protected transient boolean ackProcessed;
protected transient DialogTimerTask timerTask;
protected transient long nextSeqno;
private transient int retransmissionTicksLeft;
private transient int prevRetransmissionTicks;
protected long originalLocalSequenceNumber;
// This is for debugging only.
private transient int ackLine;
// Audit tag used by the SIP Stack audit
public transient long auditTag = 0;
// The following fields are extracted from the request that created the
// Dialog.
protected javax.sip.address.Address localParty;
protected String localPartyStringified;
protected javax.sip.address.Address remoteParty;
protected String remotePartyStringified;
protected CallIdHeader callIdHeader;
protected String callIdHeaderString;
public final static int NULL_STATE = -1;
public final static int EARLY_STATE = DialogState._EARLY;
public final static int CONFIRMED_STATE = DialogState._CONFIRMED;
public final static int TERMINATED_STATE = DialogState._TERMINATED;
// the amount of time to keep this dialog around before the stack GC's it
private static final int DIALOG_LINGER_TIME = 8;
protected boolean serverTransactionFlag;
private transient SipProviderImpl sipProvider;
protected boolean terminateOnBye;
protected transient boolean byeSent; // Flag set when BYE is sent, to
// disallow new
// requests
protected Address remoteTarget;
protected String remoteTargetStringified;
protected EventHeader eventHeader; // for Subscribe notify
// Stores the last OK for the INVITE
// Used in createAck.
protected transient long lastInviteOkReceived;
private transient Semaphore ackSem = new Semaphore(1);
protected transient int reInviteWaitTime = 100;
private transient DialogDeleteTask dialogDeleteTask;
private transient DialogDeleteIfNoAckSentTask dialogDeleteIfNoAckSentTask;
protected transient boolean isAcknowledged;
private transient long highestSequenceNumberAcknowledged = -1;
protected boolean isBackToBackUserAgent;
protected boolean sequenceNumberValidation = true;
// List of event listeners for this dialog
private transient Set<SIPDialogEventListener> eventListeners;
// added for Issue 248 :
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=248
private Semaphore timerTaskLock = new Semaphore(1);
// We store here the useful data from the first transaction without having
// to
// keep the whole transaction object for the duration of the dialog. It also
// contains the non-transient information used in the replication of
// dialogs.
protected boolean firstTransactionSecure;
protected boolean firstTransactionSeen;
protected String firstTransactionMethod;
protected String firstTransactionId;
protected boolean firstTransactionIsServerTransaction;
protected String firstTransactionMergeId;
protected int firstTransactionPort = 5060;
protected Contact contactHeader;
protected String contactHeaderStringified;
private boolean pendingRouteUpdateOn202Response;
protected ProxyAuthorizationHeader proxyAuthorizationHeader; // For
// subequent
// requests.
// aggressive flag to optimize eagerly
private boolean releaseReferences;
private EarlyStateTimerTask earlyStateTimerTask;
private int earlyDialogTimeout = 180;
private int ackSemTakenFor;
private Set<String> responsesReceivedInForkingCase = new HashSet<String>(0);
// //////////////////////////////////////////////////////
// Inner classes
// //////////////////////////////////////////////////////
class EarlyStateTimerTask extends SIPStackTimerTask implements Serializable {
public EarlyStateTimerTask() {
}
@Override
public void runTask() {
try {
if (SIPDialog.this.getState().equals(DialogState.EARLY)) {
SIPDialog.this
.raiseErrorEvent(SIPDialogErrorEvent.EARLY_STATE_TIMEOUT);
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("EarlyStateTimerTask : Dialog state is " + SIPDialog.this.getState());
}
}
} catch (Exception ex) {
logger.logError(
"Unexpected exception delivering event", ex);
}
}
}
/**
* This task waits till a pending ACK has been recorded and then sends out a
* re-INVITE. This is to prevent interleaving INVITEs ( which will result in
* a 493 from the UA that receives the out of order INVITE). This is
* primarily for B2BUA support. A B2BUA may send a delayed ACK while it does
* mid call codec renegotiation. In the meanwhile, it cannot send an
* intervening re-INVITE otherwise the othr end will respond with a
* REQUEST_PENDING. We want to avoid this condition. Hence we wait till the
* ACK for the previous re-INVITE has been sent before sending the next
* re-INVITE.
*/
public class ReInviteSender implements Runnable, Serializable {
private static final long serialVersionUID = 1019346148741070635L;
ClientTransaction ctx;
public void terminate() {
try {
ctx.terminate();
Thread.currentThread().interrupt();
} catch (ObjectInUseException e) {
logger.logError("unexpected error", e);
}
}
public ReInviteSender(ClientTransaction ctx) {
this.ctx = ctx;
}
public void run() {
try {
long timeToWait = 0;
long startTime = System.currentTimeMillis();
boolean dialogTimedOut = false;
if (!SIPDialog.this.takeAckSem()) {
/*
* Could not send re-INVITE fire a timeout on the INVITE.
*/
if (logger.isLoggingEnabled())
logger
.logError(
"Could not send re-INVITE time out ClientTransaction");
((SIPClientTransaction) ctx).fireTimeoutTimer();
/*
* Send BYE to the Dialog.
*/
if (sipProvider.getSipListener() != null
&& sipProvider.getSipListener() instanceof SipListenerExt) {
dialogTimedOut = true;
raiseErrorEvent(SIPDialogErrorEvent.DIALOG_REINVITE_TIMEOUT);
} else {
Request byeRequest = SIPDialog.this
.createRequest(Request.BYE);
if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) {
byeRequest.addHeader(MessageFactoryImpl
.getDefaultUserAgentHeader());
}
ReasonHeader reasonHeader = new Reason();
reasonHeader.setCause(1024);
reasonHeader.setText("Timed out waiting to re-INVITE");
byeRequest.addHeader(reasonHeader);
ClientTransaction byeCtx = SIPDialog.this
.getSipProvider().getNewClientTransaction(
byeRequest);
SIPDialog.this.sendRequest(byeCtx);
return;
}
}
if (getState() != DialogState.TERMINATED) {
timeToWait = System.currentTimeMillis() - startTime;
}
/*
* If we had to wait for ACK then wait for the ACK to actually
* get to the other side. Wait for any ACK retransmissions to
* finish. Then send out the request. This is a hack in support
* of some UA that want re-INVITEs to be spaced out in time (
* else they return a 400 error code ).
*/
try {
if (timeToWait != 0) {
Thread.sleep(SIPDialog.this.reInviteWaitTime);
}
} catch (InterruptedException ex) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Interrupted sleep");
return;
}
if (SIPDialog.this.getState() != DialogState.TERMINATED && !dialogTimedOut ) {
SIPDialog.this.sendRequest(ctx, true);
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"re-INVITE successfully sent");
} catch (Exception ex) {
logger.logError("Error sending re-INVITE",
ex);
} finally {
this.ctx = null;
}
}
}
class LingerTimer extends SIPStackTimerTask implements Serializable {
public void runTask() {
SIPDialog dialog = SIPDialog.this;
sipStack.removeDialog(dialog);
// Issue 279 :
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=279
// if non reentrant listener is used the event delivery of
// DialogTerminated
// can happen after the clean
if (((SipStackImpl) getStack()).isReEntrantListener()) {
cleanUp();
}
}
}
class DialogTimerTask extends SIPStackTimerTask implements Serializable {
int nRetransmissions;
SIPServerTransaction transaction;
// long cseqNumber;
public DialogTimerTask(SIPServerTransaction transaction) {
this.transaction = transaction;
this.nRetransmissions = 0;
}
public void runTask() {
// If I ACK has not been seen on Dialog,
// resend last response.
SIPDialog dialog = SIPDialog.this;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Running dialog timer");
nRetransmissions++;
SIPServerTransaction transaction = this.transaction;
/*
* Issue 106. Section 13.3.1.4 RFC 3261 The 2xx response is passed
* to the transport with an interval that starts at T1 seconds and
* doubles for each retransmission until it reaches T2 seconds If
* the server retransmits the 2xx response for 64T1 seconds without
* receiving an ACK, the dialog is confirmed, but the session SHOULD
* be terminated.
*/
if (nRetransmissions > sipStack.getAckTimeoutFactor()
* SIPTransaction.T1) {
if (SIPDialog.this.getSipProvider().getSipListener() != null
&& SIPDialog.this.getSipProvider().getSipListener() instanceof SipListenerExt) {
raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ACK_NOT_RECEIVED_TIMEOUT);
} else {
SIPDialog.this.delete();
}
if (transaction != null
&& transaction.getState() != javax.sip.TransactionState.TERMINATED) {
transaction
.raiseErrorEvent(SIPTransactionErrorEvent.TIMEOUT_ERROR);
}
} else if ((transaction != null) && (!dialog.isAckSeen())) {
// Retransmit to 2xx until ack receivedialog.
if (lastResponseStatusCode.intValue() / 100 == 2) {
try {
// resend the last response.
if (dialog.toRetransmitFinalResponse(transaction.T2)) {
transaction.resendLastResponseAsBytes();
}
} catch (IOException ex) {
raiseIOException(transaction.getPeerAddress(),
transaction.getPeerPort(), transaction
.getPeerProtocol());
} finally {
// Need to fire the timer so
// transaction will eventually
// time out whether or not
// the IOException occurs
// Note that this firing also
// drives Listener timeout.
SIPTransactionStack stack = dialog.sipStack;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"resend 200 response from " + dialog);
}
transaction.fireTimer();
}
}
}
// Stop running this timer if the dialog is in the
// confirmed state or ack seen if retransmit filter on.
if (dialog.isAckSeen() || dialog.dialogState == TERMINATED_STATE) {
this.transaction = null;
getStack().getTimer().cancel(this);
}
}
@Override
public void cleanUpBeforeCancel() {
transaction = null;
lastAckSent = null;
cleanUpOnAck();
super.cleanUpBeforeCancel();
}
}
/**
* This timer task is used to garbage collect the dialog after some time.
*
*/
class DialogDeleteTask extends SIPStackTimerTask implements Serializable {
public void runTask() {
delete();
}
}
/**
* This timer task is used to garbage collect the dialog after some time.
*
*/
class DialogDeleteIfNoAckSentTask extends SIPStackTimerTask implements
Serializable {
private long seqno;
public DialogDeleteIfNoAckSentTask(long seqno) {
this.seqno = seqno;
}
public void runTask() {
if (SIPDialog.this.highestSequenceNumberAcknowledged < seqno) {
/*
* Did not send ACK so we need to delete the dialog. B2BUA NOTE:
* we may want to send BYE to the Dialog at this point. Do we
* want to make this behavior tailorable?
*/
dialogDeleteIfNoAckSentTask = null;
if (!SIPDialog.this.isBackToBackUserAgent) {
if (logger.isLoggingEnabled())
logger.logError(
"ACK Was not sent. killing dialog");
if (((SipProviderImpl) sipProvider).getSipListener() instanceof SipListenerExt) {
raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ACK_NOT_SENT_TIMEOUT);
} else {
delete();
}
} else {
if (logger.isLoggingEnabled())
logger.logError(
"ACK Was not sent. Sending BYE");
if (((SipProviderImpl) sipProvider).getSipListener() instanceof SipListenerExt) {
raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ACK_NOT_SENT_TIMEOUT);
} else {
/*
* Send BYE to the Dialog. This will be removed for the
* next spec revision.
*/
try {
Request byeRequest = SIPDialog.this
.createRequest(Request.BYE);
if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) {
byeRequest.addHeader(MessageFactoryImpl
.getDefaultUserAgentHeader());
}
ReasonHeader reasonHeader = new Reason();
reasonHeader.setProtocol("SIP");
reasonHeader.setCause(1025);
reasonHeader
.setText("Timed out waiting to send ACK");
byeRequest.addHeader(reasonHeader);
ClientTransaction byeCtx = SIPDialog.this
.getSipProvider().getNewClientTransaction(
byeRequest);
SIPDialog.this.sendRequest(byeCtx);
return;
} catch (Exception ex) {
SIPDialog.this.delete();
}
}
}
}
}
}
// ///////////////////////////////////////////////////////////
// Constructors.
// ///////////////////////////////////////////////////////////
/**
* Protected Dialog constructor.
*/
private SIPDialog(SipProviderImpl provider) {
this.terminateOnBye = true;
this.routeList = new RouteList();
this.dialogState = NULL_STATE; // not yet initialized.
localSequenceNumber = 0;
remoteSequenceNumber = -1;
this.sipProvider = provider;
eventListeners = new CopyOnWriteArraySet<SIPDialogEventListener>();
this.earlyDialogTimeout = ((SIPTransactionStack) provider.getSipStack())
.getEarlyDialogTimeout();
}
private void recordStackTrace() {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
new Exception().printStackTrace(writer);
String stackTraceSignature = Integer.toString(Math.abs(new Random().nextInt()));
logger.logDebug("TraceRecord = " + stackTraceSignature);
this.stackTrace = "TraceRecord = " + stackTraceSignature + ":" + stringWriter.getBuffer().toString();
}
/**
* Constructor given the first transaction.
*
* @param transaction
* is the first transaction.
*/
public SIPDialog(SIPTransaction transaction) {
this(transaction.getSipProvider());
SIPRequest sipRequest = (SIPRequest) transaction.getRequest();
this.callIdHeader = sipRequest.getCallId();
this.earlyDialogId = sipRequest.getDialogId(false);
if (transaction == null)
throw new NullPointerException("Null tx");
this.sipStack = transaction.sipStack;
// this.defaultRouter = new DefaultRouter((SipStack) sipStack,
// sipStack.outboundProxy);
this.sipProvider = (SipProviderImpl) transaction.getSipProvider();
if (sipProvider == null)
throw new NullPointerException("Null Provider!");
this.isBackToBackUserAgent = sipStack.isBackToBackUserAgent;
this.addTransaction(transaction);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Creating a dialog : " + this);
logger.logDebug(
"provider port = "
+ this.sipProvider.getListeningPoint().getPort());
logger.logStackTrace();
}
addEventListener(sipStack);
releaseReferences = sipStack.isAggressiveCleanup();
}
/**
* Constructor given a transaction and a response.
*
* @param transaction
* -- the transaction ( client/server)
* @param sipResponse
* -- response with the appropriate tags.
*/
public SIPDialog(SIPClientTransaction transaction, SIPResponse sipResponse) {
this(transaction);
if (sipResponse == null)
throw new NullPointerException("Null SipResponse");
this.setLastResponse(transaction, sipResponse);
this.isBackToBackUserAgent = sipStack.isBackToBackUserAgent;
}
/**
* create a sip dialog with a response ( no tx)
*/
public SIPDialog(SipProviderImpl sipProvider, SIPResponse sipResponse) {
this(sipProvider);
this.sipStack = (SIPTransactionStack) sipProvider.getSipStack();
this.setLastResponse(null, sipResponse);
this.localSequenceNumber = sipResponse.getCSeq().getSeqNumber();
this.originalLocalSequenceNumber = localSequenceNumber;
this.setLocalTag(sipResponse.getFrom().getTag());
this.setRemoteTag(sipResponse.getTo().getTag());
this.localParty = sipResponse.getFrom().getAddress();
this.remoteParty = sipResponse.getTo().getAddress();
this.method = sipResponse.getCSeq().getMethod();
this.callIdHeader = sipResponse.getCallId();
this.serverTransactionFlag = false;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Creating a dialog : " + this);
logger.logStackTrace();
}
this.isBackToBackUserAgent = sipStack.isBackToBackUserAgent;
addEventListener(sipStack);
releaseReferences = sipStack.isAggressiveCleanup();
}
// ///////////////////////////////////////////////////////////
// Private methods
// ///////////////////////////////////////////////////////////
/**
* A debugging print routine.
*/
private void printRouteList() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("this : " + this);
logger.logDebug(
"printRouteList : " + this.routeList.encode());
}
}
/**
* Raise an io exception for asyncrhonous retransmission of responses
*
* @param host
* -- host to where the io was headed
* @param port
* -- remote port
* @param protocol
* -- protocol (udp/tcp/tls)
*/
private void raiseIOException(String host, int port, String protocol) {
// Error occured in retransmitting response.
// Deliver the error event to the listener
// Kill the dialog.
IOExceptionEvent ioError = new IOExceptionEvent(this, host, port,
protocol);
sipProvider.handleEvent(ioError, null);
setState(SIPDialog.TERMINATED_STATE);
}
/**
* Raise a dialog timeout if an ACK has not been sent or received
*
* @param dialogTimeoutError
*/
private void raiseErrorEvent(int dialogTimeoutError) {
// Error event to send to all listeners
SIPDialogErrorEvent newErrorEvent;
// Iterator through the list of listeners
Iterator<SIPDialogEventListener> listenerIterator;
// Next listener in the list
SIPDialogEventListener nextListener;
// Create the error event
newErrorEvent = new SIPDialogErrorEvent(this, dialogTimeoutError);
// Loop through all listeners of this transaction
synchronized (eventListeners) {
listenerIterator = eventListeners.iterator();
while (listenerIterator.hasNext()) {
// Send the event to the next listener
nextListener = (SIPDialogEventListener) listenerIterator.next();
nextListener.dialogErrorEvent(newErrorEvent);
}
}
// Clear the event listeners after propagating the error.
eventListeners.clear();
// Errors always terminate a dialog except if a timeout has occured
// because an ACK was not sent or received, then it is the
// responsibility of the app to terminate
// the dialog, either by sending a BYE or by calling delete() on the
// dialog
if (dialogTimeoutError != SIPDialogErrorEvent.DIALOG_ACK_NOT_SENT_TIMEOUT
&& dialogTimeoutError != SIPDialogErrorEvent.DIALOG_ACK_NOT_RECEIVED_TIMEOUT
&& dialogTimeoutError != SIPDialogErrorEvent.EARLY_STATE_TIMEOUT
&& dialogTimeoutError != SIPDialogErrorEvent.DIALOG_REINVITE_TIMEOUT) {
delete();
}
// we stop the timer in any case
stopTimer();
}
/**
* Set the remote party for this Dialog.
*
* @param sipMessage
* -- SIP Message to extract the relevant information from.
*/
protected void setRemoteParty(SIPMessage sipMessage) {
if (!isServer()) {
this.remoteParty = sipMessage.getTo().getAddress();
} else {
this.remoteParty = sipMessage.getFrom().getAddress();
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"settingRemoteParty " + this.remoteParty);
}
}
/**
* Add a route list extracted from a record route list. If this is a server
* dialog then we assume that the record are added to the route list IN
* order. If this is a client dialog then we assume that the record route
* headers give us the route list to add in reverse order.
*
* @param recordRouteList
* -- the record route list from the incoming message.
*/
private void addRoute(RecordRouteList recordRouteList) {
try {
if (!this.isServer()) {
// This is a client dialog so we extract the record
// route from the response and reverse its order to
// careate a route list.
this.routeList = new RouteList();
// start at the end of the list and walk backwards
ListIterator li = recordRouteList.listIterator(recordRouteList
.size());
boolean addRoute = true;
while (li.hasPrevious()) {
RecordRoute rr = (RecordRoute) li.previous();
if (addRoute) {
Route route = new Route();
AddressImpl address = ((AddressImpl) ((AddressImpl) rr
.getAddress()).clone());
route.setAddress(address);
route.setParameters((NameValueList) rr.getParameters()
.clone());
this.routeList.add(route);
}
}
} else {
// This is a server dialog. The top most record route
// header is the one that is closest to us. We extract the
// route list in the same order as the addresses in the
// incoming request.
this.routeList = new RouteList();
ListIterator li = recordRouteList.listIterator();
boolean addRoute = true;
while (li.hasNext()) {
RecordRoute rr = (RecordRoute) li.next();
if (addRoute) {
Route route = new Route();
AddressImpl address = ((AddressImpl) ((AddressImpl) rr
.getAddress()).clone());
route.setAddress(address);
route.setParameters((NameValueList) rr.getParameters()
.clone());
routeList.add(route);
}
}
}
} finally {
if (logger.isLoggingEnabled()) {
Iterator it = routeList.iterator();
while (it.hasNext()) {
SipURI sipUri = (SipURI) (((Route) it.next()).getAddress()
.getURI());
if (!sipUri.hasLrParam()) {
if (logger.isLoggingEnabled()) {
logger.logWarning(
"NON LR route in Route set detected for dialog : "
+ this);
logger.logStackTrace();
}
} else {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG))
logger.logDebug(
"route = " + sipUri);
}
}
}
}
}
/**
* Add a route list extacted from the contact list of the incoming message.
*
* @param contactList
* -- contact list extracted from the incoming message.
*
*/
protected void setRemoteTarget(ContactHeader contact) {
this.remoteTarget = contact.getAddress();
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Dialog.setRemoteTarget: " + this.remoteTarget);
logger.logStackTrace();
}
}
/**
* Extract the route information from this SIP Message and add the relevant
* information to the route set.
*
* @param sipMessage
* is the SIP message for which we want to add the route.
*/
private synchronized void addRoute(SIPResponse sipResponse) {
try {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"setContact: dialogState: " + this + "state = "
+ this.getState());
}
if (sipResponse.getStatusCode() == 100) {
// Do nothing for trying messages.
return;
} else if (this.dialogState == TERMINATED_STATE) {
// Do nothing if the dialog state is terminated.
return;
} else if (this.dialogState == CONFIRMED_STATE) {
// cannot add route list after the dialog is initialized.
// Remote target is updated on RE-INVITE but not
// the route list.
if (sipResponse.getStatusCode() / 100 == 2 && !this.isServer()) {
ContactList contactList = sipResponse.getContactHeaders();
if (contactList != null
&& SIPRequest.isTargetRefresh(sipResponse.getCSeq()
.getMethod())) {
this.setRemoteTarget((ContactHeader) contactList
.getFirst());
}
}
if (!this.pendingRouteUpdateOn202Response)
return;
}
// Update route list on response if I am a client dialog.
if (!isServer() || this.pendingRouteUpdateOn202Response) {
// only update the route set if the dialog is not in the
// confirmed state.
if ((this.getState() != DialogState.CONFIRMED && this
.getState() != DialogState.TERMINATED)
|| this.pendingRouteUpdateOn202Response) {
RecordRouteList rrlist = sipResponse
.getRecordRouteHeaders();
// Add the route set from the incoming response in reverse
// order for record route headers.
if (rrlist != null) {
this.addRoute(rrlist);
} else {
// Set the rotue list to the last seen route list.
this.routeList = new RouteList();
}
}
ContactList contactList = sipResponse.getContactHeaders();
if (contactList != null) {
this
.setRemoteTarget((ContactHeader) contactList
.getFirst());
}
}
} finally {
if (logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
logger.logStackTrace();
}
}
}
/**
* Get a cloned copy of route list for the Dialog.
*
* @return -- a cloned copy of the dialog route list.
*/
private synchronized RouteList getRouteList() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("getRouteList " + this);
// Find the top via in the route list.
ListIterator li;
RouteList retval = new RouteList();
retval = new RouteList();
if (this.routeList != null) {
li = routeList.listIterator();
while (li.hasNext()) {
Route route = (Route) li.next();
retval.add((Route) route.clone());
}
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("----- ");
logger.logDebug("getRouteList for " + this);
if (retval != null)
logger.logDebug(
"RouteList = " + retval.encode());
if (routeList != null)
logger.logDebug(
"myRouteList = " + routeList.encode());
logger.logDebug("----- ");
}
return retval;
}
void setRouteList(RouteList routeList) {
this.routeList = routeList;
}
/**
* Sends ACK Request to the remote party of this Dialogue.
*
*
* @param request
* the new ACK Request message to send.
* @param throwIOExceptionAsSipException
* - throws SipException if IOEx encountered. Otherwise, no
* exception is propagated.
* @param releaseAckSem
* - release ack semaphore.
* @throws SipException
* if implementation cannot send the ACK Request for any other
* reason
*
*/
private void sendAck(Request request, boolean throwIOExceptionAsSipException)
throws SipException {
SIPRequest ackRequest = (SIPRequest) request;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("sendAck" + this);
if (!ackRequest.getMethod().equals(Request.ACK))
throw new SipException("Bad request method -- should be ACK");
if (this.getState() == null
|| this.getState().getValue() == EARLY_STATE) {
if (logger.isLoggingEnabled(LogWriter.TRACE_ERROR)) {
logger.logError(
"Bad Dialog State for " + this + " dialogID = "
+ this.getDialogId());
}
throw new SipException("Bad dialog state " + this.getState());
}
if (!this.getCallId().getCallId().equals(
((SIPRequest) request).getCallId().getCallId())) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logError("CallID " + this.getCallId());
logger
.logError(
"RequestCallID = "
+ ackRequest.getCallId().getCallId());
logger.logError("dialog = " + this);
}
throw new SipException("Bad call ID in request");
}
try {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"setting from tag For outgoing ACK= "
+ this.getLocalTag());
logger.logDebug(
"setting To tag for outgoing ACK = "
+ this.getRemoteTag());
logger.logDebug("ack = " + ackRequest);
}
if (this.getLocalTag() != null)
ackRequest.getFrom().setTag(this.getLocalTag());
if (this.getRemoteTag() != null)
ackRequest.getTo().setTag(this.getRemoteTag());
} catch (ParseException ex) {
throw new SipException(ex.getMessage());
}
Hop hop = sipStack.getNextHop(ackRequest);
// Hop hop = defaultRouter.getNextHop(ackRequest);
if (hop == null)
throw new SipException("No route!");
try {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("hop = " + hop);
ListeningPointImpl lp = (ListeningPointImpl) this.sipProvider
.getListeningPoint(hop.getTransport());
if (lp == null)
throw new SipException(
"No listening point for this provider registered at "
+ hop);
InetAddress inetAddress = InetAddress.getByName(hop.getHost());
MessageChannel messageChannel = lp.getMessageProcessor()
.createMessageChannel(inetAddress, hop.getPort());
boolean releaseAckSem = false;
long cseqNo = ((SIPRequest) request).getCSeq().getSeqNumber();
if (!this.isAckSent(cseqNo)) {
releaseAckSem = true;
}
this.setLastAckSent(ackRequest);
messageChannel.sendMessage(ackRequest);
// Sent atleast one ACK.
this.isAcknowledged = true;
this.highestSequenceNumberAcknowledged = Math.max(
this.highestSequenceNumberAcknowledged,
((SIPRequest) ackRequest).getCSeq().getSeqNumber());
if (releaseAckSem && this.isBackToBackUserAgent) {
this.releaseAckSem();
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Not releasing ack sem for " + this + " isAckSent "
+ releaseAckSem);
}
}
} catch (IOException ex) {
if (throwIOExceptionAsSipException)
throw new SipException("Could not send ack", ex);
this.raiseIOException(hop.getHost(), hop.getPort(), hop
.getTransport());
} catch (SipException ex) {
if (logger.isLoggingEnabled())
logger.logException(ex);
throw ex;
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger.logException(ex);
throw new SipException("Could not create message channel", ex);
}
if (this.dialogDeleteTask != null) {
this.getStack().getTimer().cancel(dialogDeleteTask);
this.dialogDeleteTask = null;
}
}
// /////////////////////////////////////////////////////////////
// Package local methods
// /////////////////////////////////////////////////////////////
/**
* Set the stack address. Prevent us from routing messages to ourselves.
*
* @param sipStack
* the address of the SIP stack.
*
*/
void setStack(SIPTransactionStack sipStack) {
this.sipStack = sipStack;
}
/**
* Get the stack .
*
* @return sipStack the SIP stack of the dialog.
*
*/
SIPTransactionStack getStack() {
return sipStack;
}
/**
* Return True if this dialog is terminated on BYE.
*
*/
boolean isTerminatedOnBye() {
return this.terminateOnBye;
}
/**
* Mark that the dialog has seen an ACK.
*/
void ackReceived(long cseqNumber) {
// Suppress retransmission of the final response
if (this.isAckSeen()) {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG))
logger.logDebug(
"Ack already seen for response -- dropping");
return;
}
SIPServerTransaction tr = this.getInviteTransaction();
if (tr != null) {
if (tr.getCSeq() == cseqNumber) {
acquireTimerTaskSem();
try {
if (this.timerTask != null) {
this.getStack().getTimer().cancel(timerTask);
this.timerTask = null;
}
} finally {
releaseTimerTaskSem();
}
if (this.dialogDeleteTask != null) {
this.getStack().getTimer().cancel(dialogDeleteTask);
this.dialogDeleteTask = null;
}
lastAckReceivedCSeqNumber = Long.valueOf(cseqNumber);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"ackReceived for "
+ ((SIPTransaction) tr).getMethod());
this.ackLine = logger.getLineCount();
this.printDebugInfo();
}
if (this.isBackToBackUserAgent) {
this.releaseAckSem();
}
this.setState(CONFIRMED_STATE);
}
} else {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG))
logger.logDebug(
"tr is null -- not updating the ack state");
}
}
/**
* Return true if a terminated event was delivered to the application as a
* result of the dialog termination.
*
*/
synchronized boolean testAndSetIsDialogTerminatedEventDelivered() {
boolean retval = this.dialogTerminatedEventDelivered;
this.dialogTerminatedEventDelivered = true;
return retval;
}
// /////////////////////////////////////////////////////////
// Public methods
// /////////////////////////////////////////////////////////
/**
* Adds a new event listener to this dialog.
*
* @param newListener
* Listener to add.
*/
public void addEventListener(SIPDialogEventListener newListener) {
eventListeners.add(newListener);
}
/**
* Removed an event listener from this dialog.
*
* @param oldListener
* Listener to remove.
*/
public void removeEventListener(SIPDialogEventListener oldListener) {
eventListeners.remove(oldListener);
}
/*
* @see javax.sip.Dialog#setApplicationData()
*/
public void setApplicationData(Object applicationData) {
this.applicationData = applicationData;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getApplicationData()
*/
public Object getApplicationData() {
return this.applicationData;
}
/**
* Updates the next consumable seqno.
*
*/
public synchronized void requestConsumed() {
this.nextSeqno = this.getRemoteSeqNumber() + 1;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
this.logger.logDebug(
"Request Consumed -- next consumable Request Seqno = "
+ this.nextSeqno);
}
}
/**
* Return true if this request can be consumed by the dialog.
*
* @param dialogRequest
* is the request to check with the dialog.
* @return true if the dialogRequest sequence number matches the next
* consumable seqno.
*/
public synchronized boolean isRequestConsumable(SIPRequest dialogRequest) {
// have not yet set remote seqno - this is a fresh
if (dialogRequest.getMethod().equals(Request.ACK))
throw new RuntimeException("Illegal method");
// For loose validation this function is delegated to the application
if (!this.isSequnceNumberValidation()) {
return true;
}
// JvB: Acceptable iff remoteCSeq < cseq. remoteCSeq==-1
// when not defined yet, so that works too
return remoteSequenceNumber < dialogRequest.getCSeq().getSeqNumber();
}
/**
* This method is called when a forked dialog is created from the client
* side. It starts a timer task. If the timer task expires before an ACK is
* sent then the dialog is cancelled (i.e. garbage collected ).
*
*/
public void doDeferredDelete() {
if (sipStack.getTimer() == null)
this.setState(TERMINATED_STATE);
else {
this.dialogDeleteTask = new DialogDeleteTask();
// Delete the transaction after the max ack timeout.
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted()) {
sipStack.getTimer().schedule(
this.dialogDeleteTask,
SIPTransaction.TIMER_H
* SIPTransactionStack.BASE_TIMER_INTERVAL);
} else {
this.delete();
}
}
}
/**
* Set the state for this dialog.
*
* @param state
* is the state to set for the dialog.
*/
public void setState(int state) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Setting dialog state for " + this + "newState = " + state);
logger.logStackTrace();
if (state != NULL_STATE && state != this.dialogState)
if (logger.isLoggingEnabled()) {
logger.logDebug(
this + " old dialog state is " + this.getState());
logger.logDebug(
this + " New dialog state is "
+ DialogState.getObject(state));
}
}
if ( state == EARLY_STATE ) {
this.addEventListener(this.getSipProvider());
}
this.dialogState = state;
// Dialog is in terminated state set it up for GC.
if (state == TERMINATED_STATE) {
this.removeEventListener(this.getSipProvider());
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted() ) { // may be null after shutdown
sipStack.getTimer().schedule(new LingerTimer(),
DIALOG_LINGER_TIME * 1000);
}
this.stopTimer();
}
}
/**
* Debugging print for the dialog.
*/
public void printDebugInfo() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("isServer = " + isServer());
logger.logDebug("localTag = " + getLocalTag());
logger.logDebug("remoteTag = " + getRemoteTag());
logger.logDebug(
"localSequenceNumer = " + getLocalSeqNumber());
logger.logDebug(
"remoteSequenceNumer = " + getRemoteSeqNumber());
logger.logDebug(
"ackLine:" + this.getRemoteTag() + " " + ackLine);
}
}
/**
* Return true if the dialog has already seen the ack.
*
* @return flag that records if the ack has been seen.
*/
public boolean isAckSeen() {
if (lastAckReceivedCSeqNumber == null
&& lastResponseStatusCode == Response.OK) {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger.logDebug(
this + "lastAckReceived is null -- returning false");
}
return false;
} else if (lastResponseMethod == null) {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger.logDebug(
this + "lastResponse is null -- returning false");
}
return false;
} else if (lastAckReceivedCSeqNumber == null
&& lastResponseStatusCode / 100 > 2) {
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger.logDebug(
this + "lastResponse statusCode "
+ lastResponseStatusCode);
}
return true;
} else {
return this.lastAckReceivedCSeqNumber != null
&& this.lastAckReceivedCSeqNumber >= this
.getRemoteSeqNumber();
}
}
/**
* Get the last ACK for this transaction.
*/
public SIPRequest getLastAckSent() {
return this.lastAckSent;
}
/**
* Return true if ACK was sent ( for client tx ). For server tx, this is a
* NO-OP ( we dont send ACK).
*/
public boolean isAckSent(long cseqNo) {
if (this.getLastTransaction() == null)
return true;
if (this.getLastTransaction() instanceof ClientTransaction) {
if (this.getLastAckSent() == null) {
return false;
} else {
return cseqNo <= ((SIPRequest) this.getLastAckSent()).getCSeq()
.getSeqNumber();
}
} else {
return true;
}
}
@Deprecated
public Transaction getFirstTransaction() {
throw new UnsupportedOperationException(
"This method has been deprecated and is no longer supported");
}
/**
* This is for internal use only.
*
*/
public Transaction getFirstTransactionInt() {
// jeand : we try to avoid keeping the ref around for too long to help
// the GC
if (firstTransaction != null) {
return firstTransaction;
}
return this.sipStack.findTransaction(firstTransactionId,
firstTransactionIsServerTransaction);
}
/**
* Gets the route set for the dialog. When acting as an User Agent Server
* the route set MUST be set to the list of URIs in the Record-Route header
* field from the request, taken in order and preserving all URI parameters.
* When acting as an User Agent Client the route set MUST be set to the list
* of URIs in the Record-Route header field from the response, taken in
* reverse order and preserving all URI parameters. If no Record-Route
* header field is present in the request or response, the route set MUST be
* set to the empty set. This route set, even if empty, overrides any
* pre-existing route set for future requests in this dialog.
* <p>
* Requests within a dialog MAY contain Record-Route and Contact header
* fields. However, these requests do not cause the dialog's route set to be
* modified.
* <p>
* The User Agent Client uses the remote target and route set to build the
* Request-URI and Route header field of the request.
*
* @return an Iterator containing a list of route headers to be used for
* forwarding. Empty iterator is returned if route has not been
* established.
*/
public Iterator getRouteSet() {
if (this.routeList == null) {
return new LinkedList().listIterator();
} else {
return this.getRouteList().listIterator();
}
}
/**
* Add a Route list extracted from a SIPRequest to this Dialog.
*
* @param sipRequest
*/
public synchronized void addRoute(SIPRequest sipRequest) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"setContact: dialogState: " + this + "state = "
+ this.getState());
}
if (this.dialogState == CONFIRMED_STATE
&& SIPRequest.isTargetRefresh(sipRequest.getMethod())) {
this.doTargetRefresh(sipRequest);
}
if (this.dialogState == CONFIRMED_STATE
|| this.dialogState == TERMINATED_STATE) {
return;
}
// Fix for issue #225: mustn't learn Route set from mid-dialog requests
if (sipRequest.getToTag() != null)
return;
// Incoming Request has the route list
RecordRouteList rrlist = sipRequest.getRecordRouteHeaders();
// Add the route set from the incoming response in reverse
// order
if (rrlist != null) {
this.addRoute(rrlist);
} else {
// Set the rotue list to the last seen route list.
this.routeList = new RouteList();
}
// put the contact header from the incoming request into
// the route set. JvB: some duplication here, ref. doTargetRefresh
ContactList contactList = sipRequest.getContactHeaders();
if (contactList != null) {
this.setRemoteTarget((ContactHeader) contactList.getFirst());
}
}
/**
* Set the dialog identifier.
*/
public void setDialogId(String dialogId) {
if (firstTransaction != null) {
firstTransaction.setDialog(this, dialogId);
}
this.dialogId = dialogId;
}
/**
* Creates a new dialog based on a received NOTIFY. The dialog state is
* initialized appropriately. The NOTIFY differs in the From tag
*
* Made this a separate method to clearly distinguish what's happening here
* - this is a non-trivial case
*
* @param subscribeTx
* - the transaction started with the SUBSCRIBE that we sent
* @param notifyST
* - the ServerTransaction created for an incoming NOTIFY
* @return -- a new dialog created from the subscribe original SUBSCRIBE
* transaction.
*
*
*/
public static SIPDialog createFromNOTIFY(SIPClientTransaction subscribeTx,
SIPTransaction notifyST) {
SIPDialog d = new SIPDialog(notifyST);
//
// The above sets d.firstTransaction to NOTIFY (ST), correct that
//
d.serverTransactionFlag = false;
// they share this one
d.lastTransaction = subscribeTx;
d.storeFirstTransactionInfo(d, subscribeTx);
d.terminateOnBye = false;
d.localSequenceNumber = subscribeTx.getCSeq();
SIPRequest not = (SIPRequest) notifyST.getRequest();
d.remoteSequenceNumber = not.getCSeq().getSeqNumber();
d.setDialogId(not.getDialogId(true));
d.setLocalTag(not.getToTag());
d.setRemoteTag(not.getFromTag());
// to properly create the Dialog object.
// If not the stack will throw an exception when creating the response.
d.setLastResponse(subscribeTx, subscribeTx.getLastResponse());
// Dont use setLocal / setRemote here, they make other assumptions
d.localParty = not.getTo().getAddress();
d.remoteParty = not.getFrom().getAddress();
// initialize d's route set based on the NOTIFY. Any proxies must have
// Record-Routed
d.addRoute(not);
d.setState(CONFIRMED_STATE); // set state, *after* setting route set!
return d;
}
/**
* Return true if is server.
*
* @return true if is server transaction created this dialog.
*/
public boolean isServer() {
if (this.firstTransactionSeen == false)
return this.serverTransactionFlag;
else
return this.firstTransactionIsServerTransaction;
}
/**
* Return true if this is a re-establishment of the dialog.
*
* @return true if the reInvite flag is set.
*/
protected boolean isReInvite() {
return this.reInviteFlag;
}
/**
* Get the id for this dialog.
*
* @return the string identifier for this dialog.
*
*/
public String getDialogId() {
if (this.dialogId == null && this.lastResponseDialogId != null)
this.dialogId = this.lastResponseDialogId;
return this.dialogId;
}
protected void storeFirstTransactionInfo(SIPDialog dialog,
SIPTransaction transaction) {
dialog.firstTransactionSeen = true;
dialog.firstTransaction = transaction;
dialog.firstTransactionIsServerTransaction = transaction
.isServerTransaction();
if (dialog.firstTransactionIsServerTransaction) {
dialog.firstTransactionSecure = transaction.getRequest()
.getRequestURI().getScheme().equalsIgnoreCase("sips");
} else {
dialog.firstTransactionSecure = ((SIPClientTransaction) transaction)
.getOriginalRequestScheme().equalsIgnoreCase("sips");
}
dialog.firstTransactionPort = transaction.getPort();
dialog.firstTransactionId = transaction.getBranchId();
dialog.firstTransactionMethod = transaction.getMethod();
if (transaction instanceof SIPServerTransaction
&& dialog.firstTransactionMethod.equals(Request.INVITE)) {
dialog.firstTransactionMergeId = ((SIPRequest) transaction
.getRequest()).getMergeId();
}
if (transaction.isServerTransaction()) {
SIPServerTransaction st = (SIPServerTransaction) transaction;
SIPResponse response = st.getLastResponse();
dialog.contactHeader = response != null ? response
.getContactHeader() : null;
} else {
SIPClientTransaction ct = (SIPClientTransaction) transaction;
if (ct != null) {
dialog.contactHeader = ct.getOriginalRequestContact();
}
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("firstTransaction = " + dialog.firstTransaction);
logger.logDebug("firstTransactionIsServerTransaction = " + firstTransactionIsServerTransaction);
logger.logDebug("firstTransactionSecure = " + firstTransactionSecure);
logger.logDebug("firstTransactionPort = " + firstTransactionPort);
logger.logDebug("firstTransactionId = " + firstTransactionId);
logger.logDebug("firstTransactionMethod = " + firstTransactionMethod);
logger.logDebug("firstTransactionMergeId = " + firstTransactionMergeId);
}
}
/**
* Add a transaction record to the dialog.
*
* @param transaction
* is the transaction to add to the dialog.
*/
public boolean addTransaction(SIPTransaction transaction) {
SIPRequest sipRequest = (SIPRequest) transaction.getOriginalRequest();
// Proessing a re-invite.
if (firstTransactionSeen
&& !firstTransactionId.equals(transaction.getBranchId())
&& transaction.getMethod().equals(firstTransactionMethod)) {
setReInviteFlag(true);
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"SipDialog.addTransaction() " + this + " transaction = "
+ transaction);
}
if (firstTransactionSeen == false) {
// Record the local and remote sequenc
// numbers and the from and to tags for future
// use on this dialog.
storeFirstTransactionInfo(this, transaction);
if (sipRequest.getMethod().equals(Request.SUBSCRIBE))
this.eventHeader = (EventHeader) sipRequest
.getHeader(EventHeader.NAME);
this.setLocalParty(sipRequest);
this.setRemoteParty(sipRequest);
this.setCallId(sipRequest);
if (this.originalRequest == null
&& transaction.isInviteTransaction()) {
this.originalRequest = sipRequest;
} else if (originalRequest != null) {
originalRequestRecordRouteHeaders = sipRequest
.getRecordRouteHeaders();
}
if (this.method == null) {
this.method = sipRequest.getMethod();
}
if (transaction instanceof SIPServerTransaction) {
this.hisTag = sipRequest.getFrom().getTag();
// My tag is assigned when sending response
} else {
setLocalSequenceNumber(sipRequest.getCSeq().getSeqNumber());
this.originalLocalSequenceNumber = localSequenceNumber;
this.setLocalTag(sipRequest.getFrom().getTag());
if (myTag == null)
if (logger.isLoggingEnabled())
logger
.logError(
"The request's From header is missing the required Tag parameter.");
}
} else if (transaction.getMethod().equals(firstTransactionMethod)
&& firstTransactionIsServerTransaction != transaction
.isServerTransaction()) {
// This case occurs when you are processing a re-invite.
// Switch from client side to server side for re-invite
// (put the other side on hold).
storeFirstTransactionInfo(this, transaction);
this.setLocalParty(sipRequest);
this.setRemoteParty(sipRequest);
this.setCallId(sipRequest);
if (transaction.isInviteTransaction()) {
this.originalRequest = sipRequest;
} else {
originalRequestRecordRouteHeaders = sipRequest
.getRecordRouteHeaders();
}
this.method = sipRequest.getMethod();
} else if (firstTransaction == null
&& transaction.isInviteTransaction()) {
// jeand needed for reinvite reliable processing
firstTransaction = transaction;
}
if (transaction instanceof SIPServerTransaction) {
setRemoteSequenceNumber(sipRequest.getCSeq().getSeqNumber());
}
// If this is a server transaction record the remote
// sequence number to avoid re-processing of requests
// with the same sequence number directed towards this
// dialog.
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"isBackToBackUserAgent = " + this.isBackToBackUserAgent);
}
if (transaction.isInviteTransaction()) {
this.lastTransaction = transaction;
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Transaction Added " + this + myTag + "/" + hisTag);
logger.logDebug(
"TID = " + transaction.getTransactionId() + "/"
+ transaction.isServerTransaction());
logger.logStackTrace();
}
return true;
}
/**
* Set the remote tag.
*
* @param hisTag
* is the remote tag to set.
*/
protected void setRemoteTag(String hisTag) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"setRemoteTag(): " + this + " remoteTag = " + this.hisTag
+ " new tag = " + hisTag);
}
if (this.hisTag != null && hisTag != null
&& !hisTag.equals(this.hisTag)) {
if (this.getState() != DialogState.EARLY) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug(
"Dialog is already established -- ignoring remote tag re-assignment");
return;
} else if (sipStack.isRemoteTagReassignmentAllowed()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug(
"UNSAFE OPERATION ! tag re-assignment "
+ this.hisTag
+ " trying to set to " + hisTag
+ " can cause unexpected effects ");
boolean removed = false;
if (this.sipStack.getDialog(dialogId) == this) {
this.sipStack.removeDialog(dialogId);
removed = true;
}
// Force recomputation of Dialog ID;
this.dialogId = null;
this.hisTag = hisTag;
if (removed) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug("ReInserting Dialog");
this.sipStack.putDialog(this);
}
}
} else {
if (hisTag != null) {
this.hisTag = hisTag;
} else {
if (logger.isLoggingEnabled())
logger.logWarning(
"setRemoteTag : called with null argument ");
}
}
}
/**
* Get the last transaction from the dialog.
*/
public SIPTransaction getLastTransaction() {
return this.lastTransaction;
}
/**
* Get the INVITE transaction (null if no invite transaction).
*/
public SIPServerTransaction getInviteTransaction() {
DialogTimerTask t = this.timerTask;
if (t != null)
return t.transaction;
else
return null;
}
/**
* Set the local sequece number for the dialog (defaults to 1 when the
* dialog is created).
*
* @param lCseq
* is the local cseq number.
*
*/
private void setLocalSequenceNumber(long lCseq) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"setLocalSequenceNumber: original "
+ this.localSequenceNumber + " new = " + lCseq);
if (lCseq <= this.localSequenceNumber)
throw new RuntimeException("Sequence number should not decrease !");
this.localSequenceNumber = lCseq;
}
/**
* Set the remote sequence number for the dialog.
*
* @param rCseq
* is the remote cseq number.
*
*/
public void setRemoteSequenceNumber(long rCseq) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"setRemoteSeqno " + this + "/" + rCseq);
this.remoteSequenceNumber = rCseq;
}
/**
* Increment the local CSeq # for the dialog. This is useful for if you want
* to create a hole in the sequence number i.e. route a request outside the
* dialog and then resume within the dialog.
*/
public void incrementLocalSequenceNumber() {
++this.localSequenceNumber;
}
/**
* Get the remote sequence number (for cseq assignment of outgoing requests
* within this dialog).
*
* @deprecated
* @return local sequence number.
*/
public int getRemoteSequenceNumber() {
return (int) this.remoteSequenceNumber;
}
/**
* Get the local sequence number (for cseq assignment of outgoing requests
* within this dialog).
*
* @deprecated
* @return local sequence number.
*/
public int getLocalSequenceNumber() {
return (int) this.localSequenceNumber;
}
/**
* Get the sequence number for the request that origianlly created the
* Dialog.
*
* @return -- the original starting sequence number for this dialog.
*/
public long getOriginalLocalSequenceNumber() {
return this.originalLocalSequenceNumber;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getLocalSequenceNumberLong()
*/
public long getLocalSeqNumber() {
return this.localSequenceNumber;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getRemoteSequenceNumberLong()
*/
public long getRemoteSeqNumber() {
return this.remoteSequenceNumber;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getLocalTag()
*/
public String getLocalTag() {
return this.myTag;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getRemoteTag()
*/
public String getRemoteTag() {
return hisTag;
}
/**
* Set local tag for the transaction.
*
* @param mytag
* is the tag to use in From headers client transactions that
* belong to this dialog and for generating To tags for Server
* transaction requests that belong to this dialog.
*/
protected void setLocalTag(String mytag) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"set Local tag " + mytag + " dialog = " + this);
logger.logStackTrace();
}
this.myTag = mytag;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#delete()
*/
public void delete() {
// the reaper will get him later.
this.setState(TERMINATED_STATE);
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getCallId()
*/
public CallIdHeader getCallId() {
// jeand : we save the header in a string form and reparse it, help GC
// for dialogs updated not too often
if (callIdHeader == null && callIdHeaderString != null) {
try {
this.callIdHeader = (CallIdHeader) new CallIDParser(
callIdHeaderString).parse();
} catch (ParseException e) {
logger.logError(
"error reparsing the call id header", e);
}
}
return this.callIdHeader;
}
/**
* set the call id header for this dialog.
*/
private void setCallId(SIPRequest sipRequest) {
this.callIdHeader = sipRequest.getCallId();
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getLocalParty()
*/
public javax.sip.address.Address getLocalParty() {
// jeand : we save the address in a string form and reparse it, help GC
// for dialogs updated not too often
if (localParty == null && localPartyStringified != null) {
try {
this.localParty = (Address) new AddressParser(
localPartyStringified).address(true);
} catch (ParseException e) {
logger.logError(
"error reparsing the localParty", e);
}
}
return this.localParty;
}
protected void setLocalParty(SIPMessage sipMessage) {
if (!isServer()) {
this.localParty = sipMessage.getFrom().getAddress();
} else {
this.localParty = sipMessage.getTo().getAddress();
}
}
/**
* Returns the Address identifying the remote party. This is the value of
* the To header of locally initiated requests in this dialogue when acting
* as an User Agent Client.
* <p>
* This is the value of the From header of recieved responses in this
* dialogue when acting as an User Agent Server.
*
* @return the address object of the remote party.
*/
public javax.sip.address.Address getRemoteParty() {
// jeand : we save the address in a string form and reparse it, help GC
// for dialogs updated not too often
if (remoteParty == null && remotePartyStringified != null) {
try {
this.remoteParty = (Address) new AddressParser(
remotePartyStringified).address(true);
} catch (ParseException e) {
logger.logError(
"error reparsing the remoteParty", e);
}
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"gettingRemoteParty " + this.remoteParty);
}
return this.remoteParty;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getRemoteTarget()
*/
public javax.sip.address.Address getRemoteTarget() {
// jeand : we save the address in a string form and reparse it, help GC
// for dialogs updated not too often
if (remoteTarget == null && remoteTargetStringified != null) {
try {
this.remoteTarget = (Address) new AddressParser(
remoteTargetStringified).address(true);
} catch (ParseException e) {
logger.logError(
"error reparsing the remoteTarget", e);
}
}
return this.remoteTarget;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#getState()
*/
public DialogState getState() {
if (this.dialogState == NULL_STATE)
return null; // not yet initialized
return DialogState.getObject(this.dialogState);
}
/**
* Returns true if this Dialog is secure i.e. if the request arrived over
* TLS, and the Request-URI contained a SIPS URI, the "secure" flag is set
* to TRUE.
*
* @return <code>true</code> if this dialogue was established using a sips
* URI over TLS, and <code>false</code> otherwise.
*/
public boolean isSecure() {
return this.firstTransactionSecure;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#sendAck(javax.sip.message.Request)
*/
public void sendAck(Request request) throws SipException {
this.sendAck(request, true);
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#createRequest(java.lang.String)
*/
public Request createRequest(String method) throws SipException {
if (method.equals(Request.ACK) || method.equals(Request.PRACK)) {
throw new SipException(
"Invalid method specified for createRequest:" + method);
}
if (lastResponseTopMostVia != null)
return this.createRequest(method, this.lastResponseTopMostVia
.getTransport());
else
throw new SipException("Dialog not yet established -- no response!");
}
/**
* The method that actually does the work of creating a request.
*
* @param method
* @param response
* @return
* @throws SipException
*/
private SIPRequest createRequest(String method, String topMostViaTransport)
throws SipException {
/*
* Check if the dialog is in the right state (RFC 3261 section 15). The
* caller's UA MAY send a BYE for either CONFIRMED or EARLY dialogs, and
* the callee's UA MAY send a BYE on CONFIRMED dialogs, but MUST NOT
* send a BYE on EARLY dialogs.
*
* Throw out cancel request.
*/
if (method == null || topMostViaTransport == null)
throw new NullPointerException("null argument");
if (method.equals(Request.CANCEL))
throw new SipException("Dialog.createRequest(): Invalid request");
if (this.getState() == null
|| (this.getState().getValue() == TERMINATED_STATE && !method
.equalsIgnoreCase(Request.BYE))
|| (this.isServer()
&& this.getState().getValue() == EARLY_STATE && method
.equalsIgnoreCase(Request.BYE)))
throw new SipException("Dialog " + getDialogId()
+ " not yet established or terminated " + this.getState());
SipUri sipUri = null;
if (this.getRemoteTarget() != null)
sipUri = (SipUri) this.getRemoteTarget().getURI().clone();
else {
sipUri = (SipUri) this.getRemoteParty().getURI().clone();
sipUri.clearUriParms();
}
CSeq cseq = new CSeq();
try {
cseq.setMethod(method);
cseq.setSeqNumber(this.getLocalSeqNumber());
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger.logError("Unexpected error");
InternalErrorHandler.handleException(ex);
}
/*
* Add a via header for the outbound request based on the transport of
* the message processor.
*/
ListeningPointImpl lp = (ListeningPointImpl) this.sipProvider
.getListeningPoint(topMostViaTransport);
if (lp == null) {
if (logger.isLoggingEnabled())
logger.logError(
"Cannot find listening point for transport "
+ topMostViaTransport);
throw new SipException("Cannot find listening point for transport "
+ topMostViaTransport);
}
Via via = lp.getViaHeader();
From from = new From();
from.setAddress(this.getLocalParty());
To to = new To();
to.setAddress(this.getRemoteParty());
SIPRequest sipRequest = createRequest(sipUri, via, cseq, from, to);
/*
* The default contact header is obtained from the provider. The
* application can override this.
*
* JvB: Should only do this for target refresh requests, ie not for BYE,
* PRACK, etc
*/
if (SIPRequest.isTargetRefresh(method)) {
ContactHeader contactHeader = ((ListeningPointImpl) this.sipProvider
.getListeningPoint(lp.getTransport()))
.createContactHeader();
((SipURI) contactHeader.getAddress().getURI()).setSecure(this
.isSecure());
sipRequest.setHeader(contactHeader);
}
try {
/*
* Guess of local sequence number - this is being re-set when the
* request is actually dispatched
*/
cseq = (CSeq) sipRequest.getCSeq();
cseq.setSeqNumber(this.localSequenceNumber + 1);
} catch (InvalidArgumentException ex) {
InternalErrorHandler.handleException(ex);
}
if (method.equals(Request.SUBSCRIBE)) {
if (eventHeader != null)
sipRequest.addHeader(eventHeader);
}
/*
* RFC3261, section 12.2.1.1:
*
* The URI in the To field of the request MUST be set to the remote URI
* from the dialog state. The tag in the To header field of the request
* MUST be set to the remote tag of the dialog ID. The From URI of the
* request MUST be set to the local URI from the dialog state. The tag
* in the From header field of the request MUST be set to the local tag
* of the dialog ID. If the value of the remote or local tags is null,
* the tag parameter MUST be omitted from the To or From header fields,
* respectively.
*/
try {
if (this.getLocalTag() != null) {
from.setTag(this.getLocalTag());
} else {
from.removeTag();
}
if (this.getRemoteTag() != null) {
to.setTag(this.getRemoteTag());
} else {
to.removeTag();
}
} catch (ParseException ex) {
InternalErrorHandler.handleException(ex);
}
// get the route list from the dialog.
this.updateRequest(sipRequest);
return sipRequest;
}
/**
* Generate a request from a response.
*
* @param requestURI
* -- the request URI to assign to the request.
* @param via
* -- the Via header to assign to the request
* @param cseq
* -- the CSeq header to assign to the request
* @param from
* -- the From header to assign to the request
* @param to
* -- the To header to assign to the request
* @return -- the newly generated sip request.
*/
public SIPRequest createRequest(SipUri requestURI, Via via, CSeq cseq,
From from, To to) {
SIPRequest newRequest = new SIPRequest();
String method = cseq.getMethod();
newRequest.setMethod(method);
newRequest.setRequestURI(requestURI);
this.setBranch(via, method);
newRequest.setHeader(via);
newRequest.setHeader(cseq);
newRequest.setHeader(from);
newRequest.setHeader(to);
newRequest.setHeader(getCallId());
try {
// JvB: all requests need a Max-Forwards
newRequest.attachHeader(new MaxForwards(70), false);
} catch (Exception d) {
}
if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) {
newRequest
.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader());
}
return newRequest;
}
/**
* Sets the Via branch for CANCEL or ACK requests
*
* @param via
* @param method
* @throws ParseException
*/
private final void setBranch(Via via, String method) {
String branch;
if (method.equals(Request.ACK)) {
if (getLastResponseStatusCode().intValue() >= 300) {
branch = lastResponseTopMostVia.getBranch(); // non-2xx ACK uses
// same branch
} else {
branch = Utils.getInstance().generateBranchId(); // 2xx ACK gets
// new branch
}
} else if (method.equals(Request.CANCEL)) {
branch = lastResponseTopMostVia.getBranch(); // CANCEL uses same
// branch
} else
return;
try {
via.setBranch(branch);
} catch (ParseException e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#sendRequest(javax.sip.ClientTransaction)
*/
public void sendRequest(ClientTransaction clientTransactionId)
throws TransactionDoesNotExistException, SipException {
this.sendRequest(clientTransactionId, !this.isBackToBackUserAgent);
}
public void sendRequest(ClientTransaction clientTransactionId,
boolean allowInterleaving) throws TransactionDoesNotExistException,
SipException {
if (clientTransactionId == null)
throw new NullPointerException("null parameter");
if ((!allowInterleaving)
&& clientTransactionId.getRequest().getMethod().equals(
Request.INVITE)) {
sipStack.getReinviteExecutor().execute(
(new ReInviteSender(clientTransactionId)));
return;
}
SIPRequest dialogRequest = ((SIPClientTransaction) clientTransactionId)
.getOriginalRequest();
this.proxyAuthorizationHeader = (ProxyAuthorizationHeader) dialogRequest
.getHeader(ProxyAuthorizationHeader.NAME);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"dialog.sendRequest " + " dialog = " + this
+ "\ndialogRequest = \n" + dialogRequest);
if (dialogRequest.getMethod().equals(Request.ACK)
|| dialogRequest.getMethod().equals(Request.CANCEL))
throw new SipException("Bad Request Method. "
+ dialogRequest.getMethod());
// JvB: added, allow re-sending of BYE after challenge
if (byeSent && isTerminatedOnBye()
&& !dialogRequest.getMethod().equals(Request.BYE)) {
if (logger.isLoggingEnabled())
logger.logError(
"BYE already sent for " + this);
throw new SipException("Cannot send request; BYE already sent");
}
if (dialogRequest.getTopmostVia() == null) {
Via via = ((SIPClientTransaction) clientTransactionId)
.getOutgoingViaHeader();
dialogRequest.addHeader(via);
}
if (!this.getCallId().getCallId().equalsIgnoreCase(
dialogRequest.getCallId().getCallId())) {
if (logger.isLoggingEnabled()) {
logger
.logError("CallID " + this.getCallId());
logger.logError(
"RequestCallID = "
+ dialogRequest.getCallId().getCallId());
logger.logError("dialog = " + this);
}
throw new SipException("Bad call ID in request");
}
// Set the dialog back pointer.
((SIPClientTransaction) clientTransactionId).setDialog(this,
this.dialogId);
this.addTransaction((SIPTransaction) clientTransactionId);
// Enable the retransmission filter for the transaction
((SIPClientTransaction) clientTransactionId).isMapped = true;
From from = (From) dialogRequest.getFrom();
To to = (To) dialogRequest.getTo();
// Caller already did the tag assignment -- check to see if the
// tag assignment is OK.
if (this.getLocalTag() != null && from.getTag() != null
&& !from.getTag().equals(this.getLocalTag()))
throw new SipException("From tag mismatch expecting "
+ this.getLocalTag());
if (this.getRemoteTag() != null && to.getTag() != null
&& !to.getTag().equals(this.getRemoteTag())) {
if (logger.isLoggingEnabled())
this.logger.logWarning(
"To header tag mismatch expecting "
+ this.getRemoteTag());
}
/*
* The application is sending a NOTIFY before sending the response of
* the dialog.
*/
if (this.getLocalTag() == null
&& dialogRequest.getMethod().equals(Request.NOTIFY)) {
if (!this.getMethod().equals(Request.SUBSCRIBE))
throw new SipException(
"Trying to send NOTIFY without SUBSCRIBE Dialog!");
this.setLocalTag(from.getTag());
}
try {
if (this.getLocalTag() != null)
from.setTag(this.getLocalTag());
if (this.getRemoteTag() != null)
to.setTag(this.getRemoteTag());
} catch (ParseException ex) {
InternalErrorHandler.handleException(ex);
}
Hop hop = ((SIPClientTransaction) clientTransactionId).getNextHop();
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Using hop = " + hop.getHost() + " : " + hop.getPort());
}
try {
MessageChannel messageChannel = sipStack.createRawMessageChannel(
this.getSipProvider().getListeningPoint(hop.getTransport())
.getIPAddress(), this.firstTransactionPort, hop);
MessageChannel oldChannel = ((SIPClientTransaction) clientTransactionId)
.getMessageChannel();
// Remove this from the connection cache if it is in the
// connection
// cache and is not yet active.
oldChannel.uncache();
// Not configured to cache client connections.
if (!sipStack.cacheClientConnections) {
oldChannel.useCount--;
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"oldChannel: useCount " + oldChannel.useCount);
}
if (messageChannel == null) {
/*
* At this point the procedures of 8.1.2 and 12.2.1.1 of RFC3261
* have been tried but the resulting next hop cannot be resolved
* (recall that the exception thrown is caught and ignored in
* SIPStack.createMessageChannel() so we end up here with a null
* messageChannel instead of the exception handler below). All
* else failing, try the outbound proxy in accordance with
* 8.1.2, in particular: This ensures that outbound proxies that
* do not add Record-Route header field values will drop out of
* the path of subsequent requests. It allows endpoints that
* cannot resolve the first Route URI to delegate that task to
* an outbound proxy.
*
* if one considers the 'first Route URI' of a request
* constructed according to 12.2.1.1 to be the request URI when
* the route set is empty.
*/
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Null message channel using outbound proxy !");
Hop outboundProxy = sipStack.getRouter(dialogRequest)
.getOutboundProxy();
if (outboundProxy == null)
throw new SipException("No route found! hop=" + hop);
messageChannel = sipStack.createRawMessageChannel(this
.getSipProvider().getListeningPoint(
outboundProxy.getTransport()).getIPAddress(),
this.firstTransactionPort, outboundProxy);
if (messageChannel != null)
((SIPClientTransaction) clientTransactionId)
.setEncapsulatedChannel(messageChannel);
} else {
((SIPClientTransaction) clientTransactionId)
.setEncapsulatedChannel(messageChannel);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"using message channel " + messageChannel);
}
}
if (messageChannel != null)
messageChannel.useCount++;
// See if we need to release the previously mapped channel.
if ((!sipStack.cacheClientConnections) && oldChannel != null
&& oldChannel.useCount <= 0)
oldChannel.close();
} catch (Exception ex) {
if (logger.isLoggingEnabled())
logger.logException(ex);
throw new SipException("Could not create message channel", ex);
}
try {
// Increment before setting!!
localSequenceNumber++;
dialogRequest.getCSeq().setSeqNumber(getLocalSeqNumber());
} catch (InvalidArgumentException ex) {
logger.logFatalError(ex.getMessage());
}
try {
((SIPClientTransaction) clientTransactionId)
.sendMessage(dialogRequest);
/*
* Note that if the BYE is rejected then the Dialog should bo back
* to the ESTABLISHED state so we only set state after successful
* send.
*/
if (dialogRequest.getMethod().equals(Request.BYE)) {
this.byeSent = true;
/*
* Dialog goes into TERMINATED state as soon as BYE is sent.
* ISSUE 182.
*/
if (isTerminatedOnBye()) {
this.setState(DialogState._TERMINATED);
}
}
} catch (IOException ex) {
throw new SipException("error sending message", ex);
}
}
/**
* Return yes if the last response is to be retransmitted.
*/
private boolean toRetransmitFinalResponse(int T2) {
if (--retransmissionTicksLeft == 0) {
if (2 * prevRetransmissionTicks <= T2)
this.retransmissionTicksLeft = 2 * prevRetransmissionTicks;
else
this.retransmissionTicksLeft = prevRetransmissionTicks;
this.prevRetransmissionTicks = retransmissionTicksLeft;
return true;
} else
return false;
}
protected void setRetransmissionTicks() {
this.retransmissionTicksLeft = 1;
this.prevRetransmissionTicks = 1;
}
/**
* Resend the last ack.
*/
public void resendAck() throws SipException {
// Check for null.
if (this.getLastAckSent() != null) {
if (getLastAckSent().getHeader(TimeStampHeader.NAME) != null
&& sipStack.generateTimeStampHeader) {
TimeStamp ts = new TimeStamp();
try {
ts.setTimeStamp(System.currentTimeMillis());
getLastAckSent().setHeader(ts);
} catch (InvalidArgumentException e) {
}
}
this.sendAck(getLastAckSent(), false);
}
}
/**
* Get the method of the request/response that resulted in the creation of
* the Dialog.
*
* @return -- the method of the dialog.
*/
public String getMethod() {
// Method of the request or response used to create this dialog
return this.method;
}
/**
* Start the dialog timer.
*
* @param transaction
*/
protected void startTimer(SIPServerTransaction transaction) {
if (this.timerTask != null && timerTask.transaction == transaction) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Timer already running for " + getDialogId());
return;
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Starting dialog timer for " + getDialogId());
acquireTimerTaskSem();
try {
if (this.timerTask != null) {
this.timerTask.transaction = transaction;
} else {
this.timerTask = new DialogTimerTask(transaction);
if ( sipStack.getTimer() != null && sipStack.getTimer().isStarted()) {
sipStack.getTimer().scheduleWithFixedDelay(timerTask,
SIPTransactionStack.BASE_TIMER_INTERVAL,
SIPTransactionStack.BASE_TIMER_INTERVAL);
}
}
} finally {
releaseTimerTaskSem();
}
this.setRetransmissionTicks();
}
/**
* Stop the dialog timer. This is called when the dialog is terminated.
*
*/
protected void stopTimer() {
try {
acquireTimerTaskSem();
try {
if (this.timerTask != null) {
this.getStack().getTimer().cancel(timerTask);
this.timerTask = null;
}
if (this.earlyStateTimerTask != null) {
this.getStack().getTimer().cancel(this.earlyStateTimerTask);
this.earlyStateTimerTask = null;
}
} finally {
releaseTimerTaskSem();
}
} catch (Exception ex) {
}
}
/*
* (non-Javadoc) Retransmissions of the reliable provisional response cease
* when a matching PRACK is received by the UA core. PRACK is like any other
* request within a dialog, and the UAS core processes it according to the
* procedures of Sections 8.2 and 12.2.2 of RFC 3261. A matching PRACK is
* defined as one within the same dialog as the response, and whose method,
* CSeq-num, and response-num in the RAck header field match, respectively,
* the method from the CSeq, the sequence number from the CSeq, and the
* sequence number from the RSeq of the reliable provisional response.
*
* @see javax.sip.Dialog#createPrack(javax.sip.message.Response)
*/
public Request createPrack(Response relResponse)
throws DialogDoesNotExistException, SipException {
if (this.getState() == null
|| this.getState().equals(DialogState.TERMINATED))
throw new DialogDoesNotExistException(
"Dialog not initialized or terminated");
if ((RSeq) relResponse.getHeader(RSeqHeader.NAME) == null) {
throw new SipException("Missing RSeq Header");
}
try {
SIPResponse sipResponse = (SIPResponse) relResponse;
SIPRequest sipRequest = this.createRequest(Request.PRACK,
sipResponse.getTopmostVia().getTransport());
String toHeaderTag = sipResponse.getTo().getTag();
sipRequest.setToTag(toHeaderTag);
RAck rack = new RAck();
RSeq rseq = (RSeq) relResponse.getHeader(RSeqHeader.NAME);
rack.setMethod(sipResponse.getCSeq().getMethod());
rack.setCSequenceNumber((int) sipResponse.getCSeq().getSeqNumber());
rack.setRSequenceNumber(rseq.getSeqNumber());
sipRequest.setHeader(rack);
if (this.proxyAuthorizationHeader != null) {
sipRequest.addHeader(proxyAuthorizationHeader);
}
return (Request) sipRequest;
} catch (Exception ex) {
InternalErrorHandler.handleException(ex);
return null;
}
}
private void updateRequest(SIPRequest sipRequest) {
RouteList rl = this.getRouteList();
if (rl.size() > 0) {
sipRequest.setHeader(rl);
} else {
sipRequest.removeHeader(RouteHeader.NAME);
}
if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) {
sipRequest
.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader());
}
/*
* Update the request with Proxy auth header if one has been cached.
*/
if (this.proxyAuthorizationHeader != null
&& sipRequest.getHeader(ProxyAuthorizationHeader.NAME) == null) {
sipRequest.setHeader(proxyAuthorizationHeader);
}
}
/*
* (non-Javadoc) The UAC core MUST generate an ACK request for each 2xx
* received from the transaction layer. The header fields of the ACK are
* constructed in the same way as for any request sent within a dialog (see
* Section 12) with the exception of the CSeq and the header fields related
* to authentication. The sequence number of the CSeq header field MUST be
* the same as the INVITE being acknowledged, but the CSeq method MUST be
* ACK. The ACK MUST contain the same credentials as the INVITE. If the 2xx
* contains an offer (based on the rules above), the ACK MUST carry an
* answer in its body. If the offer in the 2xx response is not acceptable,
* the UAC core MUST generate a valid answer in the ACK and then send a BYE
* immediately.
*
* Note that for the case of forked requests, you can create multiple
* outgoing invites each with a different cseq and hence you need to supply
* the invite.
*
* @see javax.sip.Dialog#createAck(long)
*/
public Request createAck(long cseqno) throws InvalidArgumentException,
SipException {
// JvB: strictly speaking it is allowed to start a dialog with
// SUBSCRIBE,
// then send INVITE+ACK later on
if (!method.equals(Request.INVITE))
throw new SipException("Dialog was not created with an INVITE"
+ method);
if (cseqno <= 0)
throw new InvalidArgumentException("bad cseq <= 0 ");
else if (cseqno > ((((long) 1) << 32) - 1))
throw new InvalidArgumentException("bad cseq > "
+ ((((long) 1) << 32) - 1));
if (this.getRemoteTarget() == null) {
throw new SipException("Cannot create ACK - no remote Target!");
}
if (this.logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
this.logger.logDebug(
"createAck " + this + " cseqno " + cseqno);
}
// MUST ack in the same order that the OKs were received. This traps
// out of order ACK sending. Old ACKs seqno's can always be ACKed.
if (lastInviteOkReceived < cseqno) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
this.logger.logDebug(
"WARNING : Attempt to crete ACK without OK " + this);
this.logger.logDebug(
"LAST RESPONSE = " + this.getLastResponseStatusCode());
}
throw new SipException(
"Dialog not yet established -- no OK response!");
}
try {
// JvB: Transport from first entry in route set, or remote Contact
// if none
// Only used to find correct LP & create correct Via
SipURI uri4transport = null;
if (this.routeList != null && !this.routeList.isEmpty()) {
Route r = (Route) this.routeList.getFirst();
uri4transport = ((SipURI) r.getAddress().getURI());
} else { // should be !=null, checked above
uri4transport = ((SipURI) this.getRemoteTarget().getURI());
}
String transport = uri4transport.getTransportParam();
ListeningPointImpl lp;
if (transport != null) {
lp = (ListeningPointImpl) sipProvider
.getListeningPoint(transport);
} else {
if (uri4transport.isSecure()) { // JvB fix: also support TLS
lp = (ListeningPointImpl) sipProvider
.getListeningPoint(ListeningPoint.TLS);
} else {
lp = (ListeningPointImpl) sipProvider
.getListeningPoint(ListeningPoint.UDP);
if (lp == null) { // Alex K fix: let's try to find TCP
lp = (ListeningPointImpl) sipProvider
.getListeningPoint(ListeningPoint.TCP);
}
}
}
if (lp == null) {
if (logger.isLoggingEnabled()) {
logger.logError(
"remoteTargetURI "
+ this.getRemoteTarget().getURI());
logger.logError(
"uri4transport = " + uri4transport);
logger.logError(
"No LP found for transport=" + transport);
}
throw new SipException(
"Cannot create ACK - no ListeningPoint for transport towards next hop found:"
+ transport);
}
SIPRequest sipRequest = new SIPRequest();
sipRequest.setMethod(Request.ACK);
sipRequest.setRequestURI((SipUri) getRemoteTarget().getURI()
.clone());
sipRequest.setCallId(this.getCallId());
sipRequest.setCSeq(new CSeq(cseqno, Request.ACK));
List<Via> vias = new ArrayList<Via>();
// Via via = lp.getViaHeader();
// The user may have touched the sentby for the response.
// so use the via header extracted from the response for the ACK =>
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=205
// strip the params from the via of the response and use the params
// from the
// original request
Via via = this.lastResponseTopMostVia;
via.removeParameters();
if (originalRequest != null
&& originalRequest.getTopmostVia() != null) {
NameValueList originalRequestParameters = originalRequest
.getTopmostVia().getParameters();
if (originalRequestParameters != null
&& originalRequestParameters.size() > 0) {
via.setParameters((NameValueList) originalRequestParameters
.clone());
}
}
via.setBranch(Utils.getInstance().generateBranchId()); // new branch
vias.add(via);
sipRequest.setVia(vias);
From from = new From();
from.setAddress(this.getLocalParty());
from.setTag(this.myTag);
sipRequest.setFrom(from);
To to = new To();
to.setAddress(this.getRemoteParty());
if (hisTag != null)
to.setTag(this.hisTag);
sipRequest.setTo(to);
sipRequest.setMaxForwards(new MaxForwards(70));
if (this.originalRequest != null) {
Authorization authorization = this.originalRequest
.getAuthorization();
if (authorization != null)
sipRequest.setHeader(authorization);
// jeand : setting back the original Request to null to avoid
// keeping references around for too long
// since it is used only in the dialog setup
originalRequestRecordRouteHeaders = originalRequest
.getRecordRouteHeaders();
originalRequest = null;
}
// ACKs for 2xx responses
// use the Route values learned from the Record-Route of the 2xx
// responses.
this.updateRequest(sipRequest);
return sipRequest;
} catch (Exception ex) {
InternalErrorHandler.handleException(ex);
throw new SipException("unexpected exception ", ex);
}
}
/**
* Get the provider for this Dialog.
*
* SPEC_REVISION
*
* @return -- the SIP Provider associated with this transaction.
*/
public SipProviderImpl getSipProvider() {
return this.sipProvider;
}
/**
* @param sipProvider
* the sipProvider to set
*/
public void setSipProvider(SipProviderImpl sipProvider) {
this.sipProvider = sipProvider;
}
/**
* Check the tags of the response against the tags of the Dialog. Return
* true if the respnse matches the tags of the dialog. We do this check wehn
* sending out a response.
*
* @param sipResponse
* -- the response to check.
*
*/
public void setResponseTags(SIPResponse sipResponse) {
if (this.getLocalTag() != null || this.getRemoteTag() != null) {
return;
}
String responseFromTag = sipResponse.getFromTag();
if (responseFromTag != null) {
if (responseFromTag.equals(this.getLocalTag())) {
sipResponse.setToTag(this.getRemoteTag());
} else if (responseFromTag.equals(this.getRemoteTag())) {
sipResponse.setToTag(this.getLocalTag());
}
} else {
if (logger.isLoggingEnabled())
logger.logWarning(
"No from tag in response! Not RFC 3261 compatible.");
}
}
/**
* Set the last response for this dialog. This method is called for updating
* the dialog state when a response is either sent or received from within a
* Dialog.
*
* @param transaction
* -- the transaction associated with the response
* @param sipResponse
* -- the last response to set.
*/
public void setLastResponse(SIPTransaction transaction,
SIPResponse sipResponse) {
this.callIdHeader = sipResponse.getCallId();
final int statusCode = sipResponse.getStatusCode();
if (statusCode == 100) {
if (logger.isLoggingEnabled())
logger
.logWarning(
"Invalid status code - 100 in setLastResponse - ignoring");
return;
}
// this.lastResponse = sipResponse;
try {
this.lastResponseStatusCode = Integer.valueOf(statusCode);
this.lastResponseTopMostVia = sipResponse.getTopmostVia();
this.lastResponseMethod = sipResponse.getCSeqHeader().getMethod();
this.lastResponseCSeqNumber = sipResponse.getCSeq().getSeqNumber();
if (sipResponse.getToTag() != null ) {
this.lastResponseToTag = sipResponse.getToTag();
}
if ( sipResponse.getFromTag() != null ) {
this.lastResponseFromTag = sipResponse.getFromTag();
}
if (transaction != null) {
this.lastResponseDialogId = sipResponse.getDialogId(transaction
.isServerTransaction());
}
this.setAssigned();
// Adjust state of the Dialog state machine.
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"sipDialog: setLastResponse:" + this
+ " lastResponse = "
+ this.lastResponseStatusCode);
}
if (this.getState() == DialogState.TERMINATED) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"sipDialog: setLastResponse -- dialog is terminated - ignoring ");
}
// Capture the OK response for later use in createAck
// This is handy for late arriving OK's that we want to ACK.
if (lastResponseMethod.equals(Request.INVITE)
&& statusCode == 200) {
this.lastInviteOkReceived = Math.max(
lastResponseCSeqNumber, this.lastInviteOkReceived);
}
return;
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logStackTrace();
logger.logDebug(
"cseqMethod = " + lastResponseMethod);
logger.logDebug(
"dialogState = " + this.getState());
logger.logDebug(
"method = " + this.getMethod());
logger
.logDebug("statusCode = " + statusCode);
logger.logDebug(
"transaction = " + transaction);
}
// JvB: don't use "!this.isServer" here
// note that the transaction can be null for forked
// responses.
if (transaction == null || transaction instanceof ClientTransaction) {
if (SIPTransactionStack.isDialogCreated(lastResponseMethod)) {
// Make a final tag assignment.
if (getState() == null && (statusCode / 100 == 1)) {
/*
* Guard aginst slipping back into early state from
* confirmed state.
*/
// Was (sipResponse.getToTag() != null ||
// sipStack.rfc2543Supported)
setState(SIPDialog.EARLY_STATE);
if ((sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& this.getRemoteTag() == null) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (getState() != null
&& getState().equals(DialogState.EARLY)
&& statusCode / 100 == 1) {
/*
* This case occurs for forked dialog responses. The To
* tag can change as a result of the forking. The remote
* target can also change as a result of the forking.
*/
if (lastResponseMethod.equals(getMethod())
&& transaction != null
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (statusCode / 100 == 2) {
// This is a dialog creating method (such as INVITE).
// 2xx response -- set the state to the confirmed
// state. To tag is MANDATORY for the response.
// Only do this if method equals initial request!
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"pendingRouteUpdateOn202Response : "
+ this.pendingRouteUpdateOn202Response);
}
if (lastResponseMethod.equals(getMethod())
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& (this.getState() != DialogState.CONFIRMED || (this
.getState() == DialogState.CONFIRMED
&& lastResponseMethod
.equals(Request.SUBSCRIBE)
&& this.pendingRouteUpdateOn202Response && sipResponse
.getStatusCode() == Response.ACCEPTED))) {
if (this.getState() != DialogState.CONFIRMED) {
setRemoteTag(sipResponse.getToTag());
this
.setDialogId(sipResponse
.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
this.setState(CONFIRMED_STATE);
}
/*
* Note: Subscribe NOTIFY processing. The route set
* is computed only after we get the 202 response
* but the NOTIFY may come in before we get the 202
* response. So we need to update the route set
* after we see the 202 despite the fact that the
* dialog is in the CONFIRMED state. We do this only
* on the dialog forming SUBSCRIBE an not a
* resubscribe.
*/
if (lastResponseMethod.equals(Request.SUBSCRIBE)
&& sipResponse.getStatusCode() == Response.ACCEPTED
&& this.pendingRouteUpdateOn202Response) {
setRemoteTag(sipResponse.getToTag());
this.addRoute(sipResponse);
this.pendingRouteUpdateOn202Response = false;
}
}
// Capture the OK response for later use in createAck
if (lastResponseMethod.equals(Request.INVITE)) {
this.lastInviteOkReceived = Math.max(sipResponse
.getCSeq().getSeqNumber(),
this.lastInviteOkReceived);
}
} else if (statusCode >= 300
&& statusCode <= 699
&& (getState() == null || (lastResponseMethod
.equals(getMethod()) && getState()
.getValue() == SIPDialog.EARLY_STATE))) {
/*
* This case handles 3xx, 4xx, 5xx and 6xx responses.
* RFC 3261 Section 12.3 - dialog termination.
* Independent of the method, if a request outside of a
* dialog generates a non-2xx final response, any early
* dialogs created through provisional responses to that
* request are terminated.
*/
setState(SIPDialog.TERMINATED_STATE);
}
/*
* This code is in support of "proxy" servers that are
* constructed as back to back user agents. This could be a
* dialog in the middle of the call setup path somewhere.
* Hence the incoming invite has record route headers in it.
* The response will have additional record route headers.
* However, for this dialog only the downstream record route
* headers matter. Ideally proxy servers should not be
* constructed as Back to Back User Agents. Remove all the
* record routes that are present in the incoming INVITE so
* you only have the downstream Route headers present in the
* dialog. Note that for an endpoint - you will have no
* record route headers present in the original request so
* the loop will not execute.
*/
if (this.getState() != DialogState.CONFIRMED
&& this.getState() != DialogState.TERMINATED) {
if (getOriginalRequestRecordRouteHeaders() != null) {
ListIterator<RecordRoute> it = getOriginalRequestRecordRouteHeaders()
.listIterator(
getOriginalRequestRecordRouteHeaders()
.size());
while (it.hasPrevious()) {
RecordRoute rr = (RecordRoute) it.previous();
Route route = (Route) routeList.getFirst();
if (route != null
&& rr.getAddress().equals(
route.getAddress())) {
routeList.removeFirst();
} else
break;
}
}
}
} else if (lastResponseMethod.equals(Request.NOTIFY)
&& (this.getMethod().equals(Request.SUBSCRIBE) || this
.getMethod().equals(Request.REFER))
&& sipResponse.getStatusCode() / 100 == 2
&& this.getState() == null) {
// This is a notify response.
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
this.setState(SIPDialog.CONFIRMED_STATE);
} else if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && isTerminatedOnBye()) {
// Dialog will be terminated when the transction is
// terminated.
setState(SIPDialog.TERMINATED_STATE);
}
} else {
// Processing Server Dialog.
if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && this.isTerminatedOnBye()) {
/*
* Only transition to terminated state when 200 OK is
* returned for the BYE. Other status codes just result in
* leaving the state in COMPLETED state.
*/
this.setState(SIPDialog.TERMINATED_STATE);
} else {
boolean doPutDialog = false;
if (getLocalTag() == null
&& sipResponse.getTo().getTag() != null
&& SIPTransactionStack.isDialogCreated(lastResponseMethod)
&& lastResponseMethod.equals(getMethod())) {
setLocalTag(sipResponse.getTo().getTag());
doPutDialog = true;
}
if (statusCode / 100 != 2) {
if (statusCode / 100 == 1) {
if (doPutDialog) {
setState(SIPDialog.EARLY_STATE);
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
} else {
/*
* RFC 3265 chapter 3.1.4.1 "Non-200 class final
* responses indicate that no subscription or dialog
* has been created, and no subsequent NOTIFY
* message will be sent. All non-200 class" +
* responses (with the exception of "489", described
* herein) have the same meanings and handling as
* described in SIP"
*/
// Bug Fix by Jens tinfors
// see
// https://jain-sip.dev.java.net/servlets/ReadMsg?list=users&msgNo=797
if (statusCode == 489
&& (lastResponseMethod
.equals(Request.NOTIFY) || lastResponseMethod
.equals(Request.SUBSCRIBE))) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug(
"RFC 3265 : Not setting dialog to TERMINATED for 489");
} else {
// baranowb: simplest fix to
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=175
// application is responsible for terminating in
// this case
// see rfc 5057 for better explanation
if (!this.isReInvite()
&& getState() != DialogState.CONFIRMED) {
this.setState(SIPDialog.TERMINATED_STATE);
}
}
}
} else {
/*
* JvB: RFC4235 says that when sending 2xx on UAS side,
* state should move to CONFIRMED
*/
if (this.dialogState <= SIPDialog.EARLY_STATE
&& (lastResponseMethod.equals(Request.INVITE)
|| lastResponseMethod
.equals(Request.SUBSCRIBE) || lastResponseMethod
.equals(Request.REFER))) {
this.setState(SIPDialog.CONFIRMED_STATE);
}
if (doPutDialog) {
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
/*
* We put the dialog into the table. We must wait for
* ACK before re-INVITE is sent.
*/
if (transaction.getInternalState() != TransactionState._TERMINATED
&& sipResponse.getStatusCode() == Response.OK
&& lastResponseMethod.equals(Request.INVITE)
&& this.isBackToBackUserAgent) {
//
// Acquire the flag for re-INVITE so that we cannot
// re-INVITE before
// ACK is received.
//
if (!this.takeAckSem()) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"Delete dialog -- cannot acquire ackSem");
}
this
.raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ERROR_INTERNAL_COULD_NOT_TAKE_ACK_SEM);
logger
.logError(
"IntenalError : Ack Sem already acquired ");
return;
}
}
}
}
}
} finally {
if (sipResponse.getCSeq().getMethod().equals(Request.INVITE)
- && transaction instanceof ClientTransaction) {
+ && transaction instanceof ClientTransaction && this.getState() != DialogState.TERMINATED) {
this.acquireTimerTaskSem();
try {
if (this.getState() == DialogState.EARLY) {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
}
logger.logDebug(
"EarlyStateTimerTask craeted "
+ this.earlyDialogTimeout * 1000);
this.earlyStateTimerTask = new EarlyStateTimerTask();
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted() ) {
sipStack.getTimer().schedule(this.earlyStateTimerTask,
this.earlyDialogTimeout * 1000);
}
} else {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
this.earlyStateTimerTask = null;
}
}
} finally {
this.releaseTimerTaskSem();
}
}
}
}
/**
* Start the retransmit timer.
*
* @param sipServerTx
* -- server transaction on which the response was sent
* @param response
* - response that was sent.
*/
public void startRetransmitTimer(SIPServerTransaction sipServerTx,
Response response) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"startRetransmitTimer() " + response.getStatusCode()
+ " method " + sipServerTx.getMethod());
}
if (sipServerTx.isInviteTransaction()
&& response.getStatusCode() / 100 == 2) {
this.startTimer(sipServerTx);
}
}
/**
* @return -- the last response associated with the dialog.
*/
// public SIPResponse getLastResponse() {
//
// return lastResponse;
// }
/**
* Do taget refresh dialog state updates.
*
* RFC 3261: Requests within a dialog MAY contain Record-Route and Contact
* header fields. However, these requests do not cause the dialog's route
* set to be modified, although they may modify the remote target URI.
* Specifically, requests that are not target refresh requests do not modify
* the dialog's remote target URI, and requests that are target refresh
* requests do. For dialogs that have been established with an
*
* INVITE, the only target refresh request defined is re-INVITE (see Section
* 14). Other extensions may define different target refresh requests for
* dialogs established in other ways.
*/
private void doTargetRefresh(SIPMessage sipMessage) {
ContactList contactList = sipMessage.getContactHeaders();
/*
* INVITE is the target refresh for INVITE dialogs. SUBSCRIBE is the
* target refresh for subscribe dialogs from the client side. This
* modifies the remote target URI potentially
*/
if (contactList != null) {
Contact contact = (Contact) contactList.getFirst();
this.setRemoteTarget(contact);
}
}
private static final boolean optionPresent(ListIterator l, String option) {
while (l.hasNext()) {
OptionTag opt = (OptionTag) l.next();
if (opt != null && option.equalsIgnoreCase(opt.getOptionTag()))
return true;
}
return false;
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#createReliableProvisionalResponse(int)
*/
public Response createReliableProvisionalResponse(int statusCode)
throws InvalidArgumentException, SipException {
if (!(firstTransactionIsServerTransaction)) {
throw new SipException("Not a Server Dialog!");
}
/*
* A UAS MUST NOT attempt to send a 100 (Trying) response reliably. Only
* provisional responses numbered 101 to 199 may be sent reliably. If
* the request did not include either a Supported or Require header
* field indicating this feature, the UAS MUST NOT send the provisional
* response reliably.
*/
if (statusCode <= 100 || statusCode > 199)
throw new InvalidArgumentException("Bad status code ");
SIPRequest request = this.originalRequest;
if (!request.getMethod().equals(Request.INVITE))
throw new SipException("Bad method");
ListIterator<SIPHeader> list = request.getHeaders(SupportedHeader.NAME);
if (list == null || !optionPresent(list, "100rel")) {
list = request.getHeaders(RequireHeader.NAME);
if (list == null || !optionPresent(list, "100rel")) {
throw new SipException(
"No Supported/Require 100rel header in the request");
}
}
SIPResponse response = request.createResponse(statusCode);
/*
* The provisional response to be sent reliably is constructed by the
* UAS core according to the procedures of Section 8.2.6 of RFC 3261. In
* addition, it MUST contain a Require header field containing the
* option tag 100rel, and MUST include an RSeq header field. The value
* of the header field for the first reliable provisional response in a
* transaction MUST be between 1 and 231 - 1. It is RECOMMENDED that it
* be chosen uniformly in this range. The RSeq numbering space is within
* a single transaction. This means that provisional responses for
* different requests MAY use the same values for the RSeq number.
*/
Require require = new Require();
try {
require.setOptionTag("100rel");
} catch (Exception ex) {
InternalErrorHandler.handleException(ex);
}
response.addHeader(require);
RSeq rseq = new RSeq();
/*
* set an arbitrary sequence number. This is actually set when the
* response is sent out
*/
rseq.setSeqNumber(1L);
/*
* Copy the record route headers from the request to the response (
* Issue 160 ). Note that other 1xx headers do not get their Record
* Route headers copied over but reliable provisional responses do. See
* RFC 3262 Table 2.
*/
RecordRouteList rrl = request.getRecordRouteHeaders();
if (rrl != null) {
RecordRouteList rrlclone = (RecordRouteList) rrl.clone();
response.setHeader(rrlclone);
}
return response;
}
/**
* Do the processing necessary for the PRACK
*
* @param prackRequest
* @return true if this is the first time the tx has seen the prack ( and
* hence needs to be passed up to the TU)
*/
public boolean handlePrack(SIPRequest prackRequest) {
/*
* The RAck header is sent in a PRACK request to support reliability of
* provisional responses. It contains two numbers and a method tag. The
* first number is the value from the RSeq header in the provisional
* response that is being acknowledged. The next number, and the method,
* are copied from the CSeq in the response that is being acknowledged.
* The method name in the RAck header is case sensitive.
*/
if (!this.isServer()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- not a server Dialog");
return false;
}
SIPServerTransaction sipServerTransaction = (SIPServerTransaction) this
.getFirstTransactionInt();
byte[] sipResponse = sipServerTransaction
.getReliableProvisionalResponse();
if (sipResponse == null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- ReliableResponse not found");
return false;
}
RAck rack = (RAck) prackRequest.getHeader(RAckHeader.NAME);
if (rack == null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- rack header not found");
return false;
}
if (!rack.getMethod().equals(
sipServerTransaction.getPendingReliableResponseMethod())) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- CSeq Header does not match PRACK");
return false;
}
if (rack.getCSeqNumberLong() != sipServerTransaction
.getPendingReliableCSeqNumber()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- CSeq Header does not match PRACK");
return false;
}
if (rack.getRSequenceNumber() != sipServerTransaction
.getPendingReliableRSeqNumber()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dropping Prack -- RSeq Header does not match PRACK");
return false;
}
return sipServerTransaction.prackRecieved();
}
/*
* (non-Javadoc)
*
* @see
* javax.sip.Dialog#sendReliableProvisionalResponse(javax.sip.message.Response
* )
*/
public void sendReliableProvisionalResponse(Response relResponse)
throws SipException {
if (!this.isServer()) {
throw new SipException("Not a Server Dialog");
}
SIPResponse sipResponse = (SIPResponse) relResponse;
if (relResponse.getStatusCode() == 100)
throw new SipException(
"Cannot send 100 as a reliable provisional response");
if (relResponse.getStatusCode() / 100 > 2)
throw new SipException(
"Response code is not a 1xx response - should be in the range 101 to 199 ");
/*
* Do a little checking on the outgoing response.
*/
if (sipResponse.getToTag() == null) {
throw new SipException(
"Badly formatted response -- To tag mandatory for Reliable Provisional Response");
}
ListIterator requireList = (ListIterator) relResponse
.getHeaders(RequireHeader.NAME);
boolean found = false;
if (requireList != null) {
while (requireList.hasNext() && !found) {
RequireHeader rh = (RequireHeader) requireList.next();
if (rh.getOptionTag().equalsIgnoreCase("100rel")) {
found = true;
}
}
}
if (!found) {
Require require = new Require("100rel");
relResponse.addHeader(require);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"Require header with optionTag 100rel is needed -- adding one");
}
}
SIPServerTransaction serverTransaction = (SIPServerTransaction) this
.getFirstTransactionInt();
/*
* put into the dialog table before sending the response so as to avoid
* race condition with PRACK
*/
this.setLastResponse(serverTransaction, sipResponse);
this.setDialogId(sipResponse.getDialogId(true));
serverTransaction.sendReliableProvisionalResponse(relResponse);
this.startRetransmitTimer(serverTransaction, relResponse);
}
/*
* (non-Javadoc)
*
* @see javax.sip.Dialog#terminateOnBye(boolean)
*/
public void terminateOnBye(boolean terminateFlag) throws SipException {
this.terminateOnBye = terminateFlag;
}
/**
* Set the "assigned" flag to true. We do this when inserting the dialog
* into the dialog table of the stack.
*
*/
public void setAssigned() {
this.isAssigned = true;
}
/**
* Return true if the dialog has already been mapped to a transaction.
*
*/
public boolean isAssigned() {
return this.isAssigned;
}
/**
* Get the contact header that the owner of this dialog assigned. Subsequent
* Requests are considered to belong to the dialog if the dialog identifier
* matches and the contact header matches the ip address and port on which
* the request is received.
*
* @return contact header belonging to the dialog.
*/
public Contact getMyContactHeader() {
if (contactHeader == null && contactHeaderStringified != null) {
try {
this.contactHeader = (Contact) new ContactParser(
contactHeaderStringified).parse();
} catch (ParseException e) {
logger.logError(
"error reparsing the contact header", e);
}
}
return contactHeader;
}
/**
* Do the necessary processing to handle an ACK directed at this Dialog.
*
* @param ackTransaction
* -- the ACK transaction that was directed at this dialog.
* @return -- true if the ACK was successfully consumed by the Dialog and
* resulted in the dialog state being changed.
*/
public boolean handleAck(SIPServerTransaction ackTransaction) {
// SIPRequest sipRequest = ackTransaction.getOriginalRequest();
if (isAckSeen() && getRemoteSeqNumber() == ackTransaction.getCSeq()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"ACK already seen by dialog -- dropping Ack"
+ " retransmission");
}
acquireTimerTaskSem();
try {
if (this.timerTask != null) {
this.getStack().getTimer().cancel(timerTask);
this.timerTask = null;
}
} finally {
releaseTimerTaskSem();
}
return false;
} else if (this.getState() == DialogState.TERMINATED) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"Dialog is terminated -- dropping ACK");
return false;
} else {
if (lastResponseStatusCode != null
&& lastResponseStatusCode.intValue() / 100 == 2
&& lastResponseMethod.equals(Request.INVITE)
&& lastResponseCSeqNumber == ackTransaction.getCSeq()) {
ackTransaction.setDialog(this, lastResponseDialogId);
/*
* record that we already saw an ACK for this dialog.
*/
ackReceived(ackTransaction.getCSeq());
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
"ACK for 2XX response --- sending to TU ");
return true;
} else {
/*
* This happens when the ACK is re-transmitted and arrives too
* late to be processed.
*/
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug(
" INVITE transaction not found -- Discarding ACK");
if ( this.isBackToBackUserAgent() ) {
this.releaseAckSem();
}
return false;
}
}
}
String getEarlyDialogId() {
return earlyDialogId;
}
/**
* Release the semaphore for ACK processing so the next re-INVITE may
* proceed.
*/
void releaseAckSem() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug("releaseAckSem-enter]]" + this + " sem=" + this.ackSem + " b2bua=" + this.isBackToBackUserAgent);
logger.logStackTrace();
}
if (this.isBackToBackUserAgent) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug("releaseAckSem]]" + this + " sem=" + this.ackSem);
logger.logStackTrace();
}
if (this.ackSem.availablePermits() == 0 ) {
this.ackSem.release();
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug("releaseAckSem]]" + this + " sem=" + this.ackSem);
}
}
}
}
boolean takeAckSem() {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("[takeAckSem " + this + " sem=" + this.ackSem);
}
try {
if (!this.ackSem.tryAcquire(2, TimeUnit.SECONDS)) {
if (logger.isLoggingEnabled()) {
logger.logError(
"Cannot aquire ACK semaphore ");
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"Semaphore previously acquired at "
+ this.stackTrace + " sem=" + this.ackSem);
logger.logStackTrace();
}
return false;
}
if (logger.isLoggingEnabled(
StackLogger.TRACE_DEBUG)) {
this.recordStackTrace();
}
} catch (InterruptedException ex) {
logger.logError("Cannot aquire ACK semaphore");
return false;
}
return true;
}
/**
* @param lastAckSent
* the lastAckSent to set
*/
private void setLastAckSent(SIPRequest lastAckSent) {
this.lastAckSent = lastAckSent;
}
/**
* @return true if an ack was ever sent for this Dialog
*/
public boolean isAtleastOneAckSent() {
return this.isAcknowledged;
}
public boolean isBackToBackUserAgent() {
return this.isBackToBackUserAgent;
}
public synchronized void doDeferredDeleteIfNoAckSent(long seqno) {
if (sipStack.getTimer() == null) {
this.setState(TERMINATED_STATE);
} else if (dialogDeleteIfNoAckSentTask == null) {
// Delete the transaction after the max ack timeout.
dialogDeleteIfNoAckSentTask = new DialogDeleteIfNoAckSentTask(seqno);
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted()) {
sipStack.getTimer().schedule(
dialogDeleteIfNoAckSentTask,
sipStack.getAckTimeoutFactor()
* SIPTransactionStack.BASE_TIMER_INTERVAL);
}
}
}
/*
* (non-Javadoc)
*
* @see gov.nist.javax.sip.DialogExt#setBackToBackUserAgent(boolean)
*/
public void setBackToBackUserAgent() {
this.isBackToBackUserAgent = true;
}
/**
* @return the eventHeader
*/
EventHeader getEventHeader() {
return eventHeader;
}
/**
* @param eventHeader
* the eventHeader to set
*/
void setEventHeader(EventHeader eventHeader) {
this.eventHeader = eventHeader;
}
/**
* @param serverTransactionFlag
* the serverTransactionFlag to set
*/
void setServerTransactionFlag(boolean serverTransactionFlag) {
this.serverTransactionFlag = serverTransactionFlag;
}
/**
* @param reInviteFlag
* the reinviteFlag to set
*/
protected void setReInviteFlag(boolean reInviteFlag) {
this.reInviteFlag = reInviteFlag;
}
public boolean isSequnceNumberValidation() {
return this.sequenceNumberValidation;
}
public void disableSequenceNumberValidation() {
this.sequenceNumberValidation = false;
}
public void acquireTimerTaskSem() {
boolean acquired = false;
try {
acquired = this.timerTaskLock.tryAcquire(10, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
acquired = false;
}
if (!acquired) {
throw new IllegalStateException(
"Impossible to acquire the dialog timer task lock");
}
}
public void releaseTimerTaskSem() {
this.timerTaskLock.release();
}
public String getMergeId() {
return this.firstTransactionMergeId;
}
public void setPendingRouteUpdateOn202Response(SIPRequest sipRequest) {
this.pendingRouteUpdateOn202Response = true;
String toTag = sipRequest.getToHeader().getTag();
if (toTag != null) {
this.setRemoteTag(toTag);
}
}
public String getLastResponseMethod() {
return lastResponseMethod;
}
public Integer getLastResponseStatusCode() {
return lastResponseStatusCode;
}
public long getLastResponseCSeqNumber() {
return lastResponseCSeqNumber;
}
// jeand cleanup the dialog from the data not needed anymore upon receiving
// or sending an ACK
// to save on mem
protected void cleanUpOnAck() {
if (isReleaseReferences()) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"cleanupOnAck : " + getDialogId());
}
if (originalRequest != null) {
if (originalRequestRecordRouteHeaders != null) {
originalRequestRecordRouteHeadersString = originalRequestRecordRouteHeaders
.toString();
}
originalRequestRecordRouteHeaders = null;
originalRequest = null;
}
if (firstTransaction != null) {
if (firstTransaction.getOriginalRequest() != null) {
firstTransaction.getOriginalRequest().cleanUp();
}
firstTransaction = null;
}
if (lastTransaction != null) {
if (lastTransaction.getOriginalRequest() != null) {
lastTransaction.getOriginalRequest().cleanUp();
}
lastTransaction = null;
}
if (callIdHeader != null) {
callIdHeaderString = callIdHeader.toString();
callIdHeader = null;
}
if (contactHeader != null) {
contactHeaderStringified = contactHeader.toString();
contactHeader = null;
}
if (remoteTarget != null) {
remoteTargetStringified = remoteTarget.toString();
remoteTarget = null;
}
if (remoteParty != null) {
remotePartyStringified = remoteParty.toString();
remoteParty = null;
}
if (localParty != null) {
localPartyStringified = localParty.toString();
localParty = null;
}
}
}
/**
* Release references so the GC can clean up dialog state.
*
*/
protected void cleanUp() {
if (isReleaseReferences()) {
cleanUpOnAck();
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug("dialog cleanup : " + getDialogId());
}
if (eventListeners != null) {
eventListeners.clear();
}
timerTaskLock = null;
ackSem = null;
contactHeader = null;
eventHeader = null;
firstTransactionId = null;
firstTransactionMethod = null;
// Cannot clear up the last Ack Sent.
lastAckSent = null;
// lastAckReceivedCSeqNumber = null;
lastResponseDialogId = null;
lastResponseMethod = null;
lastResponseTopMostVia = null;
if (originalRequestRecordRouteHeaders != null) {
originalRequestRecordRouteHeaders.clear();
originalRequestRecordRouteHeaders = null;
originalRequestRecordRouteHeadersString = null;
}
if (routeList != null) {
routeList.clear();
routeList = null;
}
responsesReceivedInForkingCase.clear();
}
}
protected RecordRouteList getOriginalRequestRecordRouteHeaders() {
if (originalRequestRecordRouteHeaders == null
&& originalRequestRecordRouteHeadersString != null) {
try {
originalRequestRecordRouteHeaders = (RecordRouteList) new RecordRouteParser(
originalRequestRecordRouteHeadersString).parse();
} catch (ParseException e) {
logger
.logError(
"error reparsing the originalRequest RecordRoute Headers",
e);
}
originalRequestRecordRouteHeadersString = null;
}
return originalRequestRecordRouteHeaders;
}
/**
* @return the lastResponseTopMostVia
*/
public Via getLastResponseTopMostVia() {
return lastResponseTopMostVia;
}
/*
* (non-Javadoc)
*
* @see gov.nist.javax.sip.DialogExt#isReleaseReferences()
*/
public boolean isReleaseReferences() {
return releaseReferences;
}
/*
* (non-Javadoc)
*
* @see gov.nist.javax.sip.DialogExt#setReleaseReferences(boolean)
*/
public void setReleaseReferences(boolean releaseReferences) {
this.releaseReferences = releaseReferences;
}
public void setEarlyDialogTimeoutSeconds(int seconds) {
if (seconds <= 0) {
throw new IllegalArgumentException("Invalid value " + seconds);
}
this.earlyDialogTimeout = seconds;
}
public void checkRetransmissionForForking(SIPResponse response) {
final int statusCode = response.getStatusCode();
final String responseMethod = response.getCSeqHeader().getMethod();
final long responseCSeqNumber = response.getCSeq().getSeqNumber();
boolean isRetransmission = !responsesReceivedInForkingCase.add(statusCode + "/" + responseCSeqNumber + "/" + responseMethod);
response.setRetransmission(isRetransmission);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"marking response as retransmission " + isRetransmission + " for dialog " + this);
}
}
}
| true | true | public void setLastResponse(SIPTransaction transaction,
SIPResponse sipResponse) {
this.callIdHeader = sipResponse.getCallId();
final int statusCode = sipResponse.getStatusCode();
if (statusCode == 100) {
if (logger.isLoggingEnabled())
logger
.logWarning(
"Invalid status code - 100 in setLastResponse - ignoring");
return;
}
// this.lastResponse = sipResponse;
try {
this.lastResponseStatusCode = Integer.valueOf(statusCode);
this.lastResponseTopMostVia = sipResponse.getTopmostVia();
this.lastResponseMethod = sipResponse.getCSeqHeader().getMethod();
this.lastResponseCSeqNumber = sipResponse.getCSeq().getSeqNumber();
if (sipResponse.getToTag() != null ) {
this.lastResponseToTag = sipResponse.getToTag();
}
if ( sipResponse.getFromTag() != null ) {
this.lastResponseFromTag = sipResponse.getFromTag();
}
if (transaction != null) {
this.lastResponseDialogId = sipResponse.getDialogId(transaction
.isServerTransaction());
}
this.setAssigned();
// Adjust state of the Dialog state machine.
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"sipDialog: setLastResponse:" + this
+ " lastResponse = "
+ this.lastResponseStatusCode);
}
if (this.getState() == DialogState.TERMINATED) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"sipDialog: setLastResponse -- dialog is terminated - ignoring ");
}
// Capture the OK response for later use in createAck
// This is handy for late arriving OK's that we want to ACK.
if (lastResponseMethod.equals(Request.INVITE)
&& statusCode == 200) {
this.lastInviteOkReceived = Math.max(
lastResponseCSeqNumber, this.lastInviteOkReceived);
}
return;
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logStackTrace();
logger.logDebug(
"cseqMethod = " + lastResponseMethod);
logger.logDebug(
"dialogState = " + this.getState());
logger.logDebug(
"method = " + this.getMethod());
logger
.logDebug("statusCode = " + statusCode);
logger.logDebug(
"transaction = " + transaction);
}
// JvB: don't use "!this.isServer" here
// note that the transaction can be null for forked
// responses.
if (transaction == null || transaction instanceof ClientTransaction) {
if (SIPTransactionStack.isDialogCreated(lastResponseMethod)) {
// Make a final tag assignment.
if (getState() == null && (statusCode / 100 == 1)) {
/*
* Guard aginst slipping back into early state from
* confirmed state.
*/
// Was (sipResponse.getToTag() != null ||
// sipStack.rfc2543Supported)
setState(SIPDialog.EARLY_STATE);
if ((sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& this.getRemoteTag() == null) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (getState() != null
&& getState().equals(DialogState.EARLY)
&& statusCode / 100 == 1) {
/*
* This case occurs for forked dialog responses. The To
* tag can change as a result of the forking. The remote
* target can also change as a result of the forking.
*/
if (lastResponseMethod.equals(getMethod())
&& transaction != null
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (statusCode / 100 == 2) {
// This is a dialog creating method (such as INVITE).
// 2xx response -- set the state to the confirmed
// state. To tag is MANDATORY for the response.
// Only do this if method equals initial request!
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"pendingRouteUpdateOn202Response : "
+ this.pendingRouteUpdateOn202Response);
}
if (lastResponseMethod.equals(getMethod())
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& (this.getState() != DialogState.CONFIRMED || (this
.getState() == DialogState.CONFIRMED
&& lastResponseMethod
.equals(Request.SUBSCRIBE)
&& this.pendingRouteUpdateOn202Response && sipResponse
.getStatusCode() == Response.ACCEPTED))) {
if (this.getState() != DialogState.CONFIRMED) {
setRemoteTag(sipResponse.getToTag());
this
.setDialogId(sipResponse
.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
this.setState(CONFIRMED_STATE);
}
/*
* Note: Subscribe NOTIFY processing. The route set
* is computed only after we get the 202 response
* but the NOTIFY may come in before we get the 202
* response. So we need to update the route set
* after we see the 202 despite the fact that the
* dialog is in the CONFIRMED state. We do this only
* on the dialog forming SUBSCRIBE an not a
* resubscribe.
*/
if (lastResponseMethod.equals(Request.SUBSCRIBE)
&& sipResponse.getStatusCode() == Response.ACCEPTED
&& this.pendingRouteUpdateOn202Response) {
setRemoteTag(sipResponse.getToTag());
this.addRoute(sipResponse);
this.pendingRouteUpdateOn202Response = false;
}
}
// Capture the OK response for later use in createAck
if (lastResponseMethod.equals(Request.INVITE)) {
this.lastInviteOkReceived = Math.max(sipResponse
.getCSeq().getSeqNumber(),
this.lastInviteOkReceived);
}
} else if (statusCode >= 300
&& statusCode <= 699
&& (getState() == null || (lastResponseMethod
.equals(getMethod()) && getState()
.getValue() == SIPDialog.EARLY_STATE))) {
/*
* This case handles 3xx, 4xx, 5xx and 6xx responses.
* RFC 3261 Section 12.3 - dialog termination.
* Independent of the method, if a request outside of a
* dialog generates a non-2xx final response, any early
* dialogs created through provisional responses to that
* request are terminated.
*/
setState(SIPDialog.TERMINATED_STATE);
}
/*
* This code is in support of "proxy" servers that are
* constructed as back to back user agents. This could be a
* dialog in the middle of the call setup path somewhere.
* Hence the incoming invite has record route headers in it.
* The response will have additional record route headers.
* However, for this dialog only the downstream record route
* headers matter. Ideally proxy servers should not be
* constructed as Back to Back User Agents. Remove all the
* record routes that are present in the incoming INVITE so
* you only have the downstream Route headers present in the
* dialog. Note that for an endpoint - you will have no
* record route headers present in the original request so
* the loop will not execute.
*/
if (this.getState() != DialogState.CONFIRMED
&& this.getState() != DialogState.TERMINATED) {
if (getOriginalRequestRecordRouteHeaders() != null) {
ListIterator<RecordRoute> it = getOriginalRequestRecordRouteHeaders()
.listIterator(
getOriginalRequestRecordRouteHeaders()
.size());
while (it.hasPrevious()) {
RecordRoute rr = (RecordRoute) it.previous();
Route route = (Route) routeList.getFirst();
if (route != null
&& rr.getAddress().equals(
route.getAddress())) {
routeList.removeFirst();
} else
break;
}
}
}
} else if (lastResponseMethod.equals(Request.NOTIFY)
&& (this.getMethod().equals(Request.SUBSCRIBE) || this
.getMethod().equals(Request.REFER))
&& sipResponse.getStatusCode() / 100 == 2
&& this.getState() == null) {
// This is a notify response.
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
this.setState(SIPDialog.CONFIRMED_STATE);
} else if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && isTerminatedOnBye()) {
// Dialog will be terminated when the transction is
// terminated.
setState(SIPDialog.TERMINATED_STATE);
}
} else {
// Processing Server Dialog.
if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && this.isTerminatedOnBye()) {
/*
* Only transition to terminated state when 200 OK is
* returned for the BYE. Other status codes just result in
* leaving the state in COMPLETED state.
*/
this.setState(SIPDialog.TERMINATED_STATE);
} else {
boolean doPutDialog = false;
if (getLocalTag() == null
&& sipResponse.getTo().getTag() != null
&& SIPTransactionStack.isDialogCreated(lastResponseMethod)
&& lastResponseMethod.equals(getMethod())) {
setLocalTag(sipResponse.getTo().getTag());
doPutDialog = true;
}
if (statusCode / 100 != 2) {
if (statusCode / 100 == 1) {
if (doPutDialog) {
setState(SIPDialog.EARLY_STATE);
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
} else {
/*
* RFC 3265 chapter 3.1.4.1 "Non-200 class final
* responses indicate that no subscription or dialog
* has been created, and no subsequent NOTIFY
* message will be sent. All non-200 class" +
* responses (with the exception of "489", described
* herein) have the same meanings and handling as
* described in SIP"
*/
// Bug Fix by Jens tinfors
// see
// https://jain-sip.dev.java.net/servlets/ReadMsg?list=users&msgNo=797
if (statusCode == 489
&& (lastResponseMethod
.equals(Request.NOTIFY) || lastResponseMethod
.equals(Request.SUBSCRIBE))) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug(
"RFC 3265 : Not setting dialog to TERMINATED for 489");
} else {
// baranowb: simplest fix to
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=175
// application is responsible for terminating in
// this case
// see rfc 5057 for better explanation
if (!this.isReInvite()
&& getState() != DialogState.CONFIRMED) {
this.setState(SIPDialog.TERMINATED_STATE);
}
}
}
} else {
/*
* JvB: RFC4235 says that when sending 2xx on UAS side,
* state should move to CONFIRMED
*/
if (this.dialogState <= SIPDialog.EARLY_STATE
&& (lastResponseMethod.equals(Request.INVITE)
|| lastResponseMethod
.equals(Request.SUBSCRIBE) || lastResponseMethod
.equals(Request.REFER))) {
this.setState(SIPDialog.CONFIRMED_STATE);
}
if (doPutDialog) {
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
/*
* We put the dialog into the table. We must wait for
* ACK before re-INVITE is sent.
*/
if (transaction.getInternalState() != TransactionState._TERMINATED
&& sipResponse.getStatusCode() == Response.OK
&& lastResponseMethod.equals(Request.INVITE)
&& this.isBackToBackUserAgent) {
//
// Acquire the flag for re-INVITE so that we cannot
// re-INVITE before
// ACK is received.
//
if (!this.takeAckSem()) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"Delete dialog -- cannot acquire ackSem");
}
this
.raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ERROR_INTERNAL_COULD_NOT_TAKE_ACK_SEM);
logger
.logError(
"IntenalError : Ack Sem already acquired ");
return;
}
}
}
}
}
} finally {
if (sipResponse.getCSeq().getMethod().equals(Request.INVITE)
&& transaction instanceof ClientTransaction) {
this.acquireTimerTaskSem();
try {
if (this.getState() == DialogState.EARLY) {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
}
logger.logDebug(
"EarlyStateTimerTask craeted "
+ this.earlyDialogTimeout * 1000);
this.earlyStateTimerTask = new EarlyStateTimerTask();
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted() ) {
sipStack.getTimer().schedule(this.earlyStateTimerTask,
this.earlyDialogTimeout * 1000);
}
} else {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
this.earlyStateTimerTask = null;
}
}
} finally {
this.releaseTimerTaskSem();
}
}
}
}
| public void setLastResponse(SIPTransaction transaction,
SIPResponse sipResponse) {
this.callIdHeader = sipResponse.getCallId();
final int statusCode = sipResponse.getStatusCode();
if (statusCode == 100) {
if (logger.isLoggingEnabled())
logger
.logWarning(
"Invalid status code - 100 in setLastResponse - ignoring");
return;
}
// this.lastResponse = sipResponse;
try {
this.lastResponseStatusCode = Integer.valueOf(statusCode);
this.lastResponseTopMostVia = sipResponse.getTopmostVia();
this.lastResponseMethod = sipResponse.getCSeqHeader().getMethod();
this.lastResponseCSeqNumber = sipResponse.getCSeq().getSeqNumber();
if (sipResponse.getToTag() != null ) {
this.lastResponseToTag = sipResponse.getToTag();
}
if ( sipResponse.getFromTag() != null ) {
this.lastResponseFromTag = sipResponse.getFromTag();
}
if (transaction != null) {
this.lastResponseDialogId = sipResponse.getDialogId(transaction
.isServerTransaction());
}
this.setAssigned();
// Adjust state of the Dialog state machine.
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug(
"sipDialog: setLastResponse:" + this
+ " lastResponse = "
+ this.lastResponseStatusCode);
}
if (this.getState() == DialogState.TERMINATED) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"sipDialog: setLastResponse -- dialog is terminated - ignoring ");
}
// Capture the OK response for later use in createAck
// This is handy for late arriving OK's that we want to ACK.
if (lastResponseMethod.equals(Request.INVITE)
&& statusCode == 200) {
this.lastInviteOkReceived = Math.max(
lastResponseCSeqNumber, this.lastInviteOkReceived);
}
return;
}
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logStackTrace();
logger.logDebug(
"cseqMethod = " + lastResponseMethod);
logger.logDebug(
"dialogState = " + this.getState());
logger.logDebug(
"method = " + this.getMethod());
logger
.logDebug("statusCode = " + statusCode);
logger.logDebug(
"transaction = " + transaction);
}
// JvB: don't use "!this.isServer" here
// note that the transaction can be null for forked
// responses.
if (transaction == null || transaction instanceof ClientTransaction) {
if (SIPTransactionStack.isDialogCreated(lastResponseMethod)) {
// Make a final tag assignment.
if (getState() == null && (statusCode / 100 == 1)) {
/*
* Guard aginst slipping back into early state from
* confirmed state.
*/
// Was (sipResponse.getToTag() != null ||
// sipStack.rfc2543Supported)
setState(SIPDialog.EARLY_STATE);
if ((sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& this.getRemoteTag() == null) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (getState() != null
&& getState().equals(DialogState.EARLY)
&& statusCode / 100 == 1) {
/*
* This case occurs for forked dialog responses. The To
* tag can change as a result of the forking. The remote
* target can also change as a result of the forking.
*/
if (lastResponseMethod.equals(getMethod())
&& transaction != null
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)) {
setRemoteTag(sipResponse.getToTag());
this.setDialogId(sipResponse.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
}
} else if (statusCode / 100 == 2) {
// This is a dialog creating method (such as INVITE).
// 2xx response -- set the state to the confirmed
// state. To tag is MANDATORY for the response.
// Only do this if method equals initial request!
if (logger.isLoggingEnabled(
LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"pendingRouteUpdateOn202Response : "
+ this.pendingRouteUpdateOn202Response);
}
if (lastResponseMethod.equals(getMethod())
&& (sipResponse.getToTag() != null || sipStack.rfc2543Supported)
&& (this.getState() != DialogState.CONFIRMED || (this
.getState() == DialogState.CONFIRMED
&& lastResponseMethod
.equals(Request.SUBSCRIBE)
&& this.pendingRouteUpdateOn202Response && sipResponse
.getStatusCode() == Response.ACCEPTED))) {
if (this.getState() != DialogState.CONFIRMED) {
setRemoteTag(sipResponse.getToTag());
this
.setDialogId(sipResponse
.getDialogId(false));
sipStack.putDialog(this);
this.addRoute(sipResponse);
this.setState(CONFIRMED_STATE);
}
/*
* Note: Subscribe NOTIFY processing. The route set
* is computed only after we get the 202 response
* but the NOTIFY may come in before we get the 202
* response. So we need to update the route set
* after we see the 202 despite the fact that the
* dialog is in the CONFIRMED state. We do this only
* on the dialog forming SUBSCRIBE an not a
* resubscribe.
*/
if (lastResponseMethod.equals(Request.SUBSCRIBE)
&& sipResponse.getStatusCode() == Response.ACCEPTED
&& this.pendingRouteUpdateOn202Response) {
setRemoteTag(sipResponse.getToTag());
this.addRoute(sipResponse);
this.pendingRouteUpdateOn202Response = false;
}
}
// Capture the OK response for later use in createAck
if (lastResponseMethod.equals(Request.INVITE)) {
this.lastInviteOkReceived = Math.max(sipResponse
.getCSeq().getSeqNumber(),
this.lastInviteOkReceived);
}
} else if (statusCode >= 300
&& statusCode <= 699
&& (getState() == null || (lastResponseMethod
.equals(getMethod()) && getState()
.getValue() == SIPDialog.EARLY_STATE))) {
/*
* This case handles 3xx, 4xx, 5xx and 6xx responses.
* RFC 3261 Section 12.3 - dialog termination.
* Independent of the method, if a request outside of a
* dialog generates a non-2xx final response, any early
* dialogs created through provisional responses to that
* request are terminated.
*/
setState(SIPDialog.TERMINATED_STATE);
}
/*
* This code is in support of "proxy" servers that are
* constructed as back to back user agents. This could be a
* dialog in the middle of the call setup path somewhere.
* Hence the incoming invite has record route headers in it.
* The response will have additional record route headers.
* However, for this dialog only the downstream record route
* headers matter. Ideally proxy servers should not be
* constructed as Back to Back User Agents. Remove all the
* record routes that are present in the incoming INVITE so
* you only have the downstream Route headers present in the
* dialog. Note that for an endpoint - you will have no
* record route headers present in the original request so
* the loop will not execute.
*/
if (this.getState() != DialogState.CONFIRMED
&& this.getState() != DialogState.TERMINATED) {
if (getOriginalRequestRecordRouteHeaders() != null) {
ListIterator<RecordRoute> it = getOriginalRequestRecordRouteHeaders()
.listIterator(
getOriginalRequestRecordRouteHeaders()
.size());
while (it.hasPrevious()) {
RecordRoute rr = (RecordRoute) it.previous();
Route route = (Route) routeList.getFirst();
if (route != null
&& rr.getAddress().equals(
route.getAddress())) {
routeList.removeFirst();
} else
break;
}
}
}
} else if (lastResponseMethod.equals(Request.NOTIFY)
&& (this.getMethod().equals(Request.SUBSCRIBE) || this
.getMethod().equals(Request.REFER))
&& sipResponse.getStatusCode() / 100 == 2
&& this.getState() == null) {
// This is a notify response.
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
this.setState(SIPDialog.CONFIRMED_STATE);
} else if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && isTerminatedOnBye()) {
// Dialog will be terminated when the transction is
// terminated.
setState(SIPDialog.TERMINATED_STATE);
}
} else {
// Processing Server Dialog.
if (lastResponseMethod.equals(Request.BYE)
&& statusCode / 100 == 2 && this.isTerminatedOnBye()) {
/*
* Only transition to terminated state when 200 OK is
* returned for the BYE. Other status codes just result in
* leaving the state in COMPLETED state.
*/
this.setState(SIPDialog.TERMINATED_STATE);
} else {
boolean doPutDialog = false;
if (getLocalTag() == null
&& sipResponse.getTo().getTag() != null
&& SIPTransactionStack.isDialogCreated(lastResponseMethod)
&& lastResponseMethod.equals(getMethod())) {
setLocalTag(sipResponse.getTo().getTag());
doPutDialog = true;
}
if (statusCode / 100 != 2) {
if (statusCode / 100 == 1) {
if (doPutDialog) {
setState(SIPDialog.EARLY_STATE);
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
} else {
/*
* RFC 3265 chapter 3.1.4.1 "Non-200 class final
* responses indicate that no subscription or dialog
* has been created, and no subsequent NOTIFY
* message will be sent. All non-200 class" +
* responses (with the exception of "489", described
* herein) have the same meanings and handling as
* described in SIP"
*/
// Bug Fix by Jens tinfors
// see
// https://jain-sip.dev.java.net/servlets/ReadMsg?list=users&msgNo=797
if (statusCode == 489
&& (lastResponseMethod
.equals(Request.NOTIFY) || lastResponseMethod
.equals(Request.SUBSCRIBE))) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger
.logDebug(
"RFC 3265 : Not setting dialog to TERMINATED for 489");
} else {
// baranowb: simplest fix to
// https://jain-sip.dev.java.net/issues/show_bug.cgi?id=175
// application is responsible for terminating in
// this case
// see rfc 5057 for better explanation
if (!this.isReInvite()
&& getState() != DialogState.CONFIRMED) {
this.setState(SIPDialog.TERMINATED_STATE);
}
}
}
} else {
/*
* JvB: RFC4235 says that when sending 2xx on UAS side,
* state should move to CONFIRMED
*/
if (this.dialogState <= SIPDialog.EARLY_STATE
&& (lastResponseMethod.equals(Request.INVITE)
|| lastResponseMethod
.equals(Request.SUBSCRIBE) || lastResponseMethod
.equals(Request.REFER))) {
this.setState(SIPDialog.CONFIRMED_STATE);
}
if (doPutDialog) {
this.setDialogId(sipResponse.getDialogId(true));
sipStack.putDialog(this);
}
/*
* We put the dialog into the table. We must wait for
* ACK before re-INVITE is sent.
*/
if (transaction.getInternalState() != TransactionState._TERMINATED
&& sipResponse.getStatusCode() == Response.OK
&& lastResponseMethod.equals(Request.INVITE)
&& this.isBackToBackUserAgent) {
//
// Acquire the flag for re-INVITE so that we cannot
// re-INVITE before
// ACK is received.
//
if (!this.takeAckSem()) {
if (logger
.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger
.logDebug(
"Delete dialog -- cannot acquire ackSem");
}
this
.raiseErrorEvent(SIPDialogErrorEvent.DIALOG_ERROR_INTERNAL_COULD_NOT_TAKE_ACK_SEM);
logger
.logError(
"IntenalError : Ack Sem already acquired ");
return;
}
}
}
}
}
} finally {
if (sipResponse.getCSeq().getMethod().equals(Request.INVITE)
&& transaction instanceof ClientTransaction && this.getState() != DialogState.TERMINATED) {
this.acquireTimerTaskSem();
try {
if (this.getState() == DialogState.EARLY) {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
}
logger.logDebug(
"EarlyStateTimerTask craeted "
+ this.earlyDialogTimeout * 1000);
this.earlyStateTimerTask = new EarlyStateTimerTask();
if (sipStack.getTimer() != null && sipStack.getTimer().isStarted() ) {
sipStack.getTimer().schedule(this.earlyStateTimerTask,
this.earlyDialogTimeout * 1000);
}
} else {
if (this.earlyStateTimerTask != null) {
sipStack.getTimer()
.cancel(this.earlyStateTimerTask);
this.earlyStateTimerTask = null;
}
}
} finally {
this.releaseTimerTaskSem();
}
}
}
}
|
diff --git a/src/com/kaist/crescendo/activity/IntroActivity.java b/src/com/kaist/crescendo/activity/IntroActivity.java
index a7b19b1..fc196af 100644
--- a/src/com/kaist/crescendo/activity/IntroActivity.java
+++ b/src/com/kaist/crescendo/activity/IntroActivity.java
@@ -1,68 +1,67 @@
package com.kaist.crescendo.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
import android.widget.ImageView;
import com.kaist.crescendo.R;
import com.kaist.crescendo.utils.MyPref;
public class IntroActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_intro);
Handler handler = new Handler();
handler.postDelayed(run, 3000);
}
Runnable run = new Runnable() {
@Override
public void run() {
/* Call Register Activity when session is not established */
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
boolean saved = prefs.getBoolean(MyPref.KEY_SESSION, false);
if(saved == false)
{
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), EntranceActivity.class));
}
else {
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), MainActivity.class));
- overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
- finish();
- overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
- //overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_in_left);
}
+ finish();
+ //overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
+ overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_in_left);
}
};
@Override
public void onBackPressed() {
//super.onBackPressed(); // it's intended
// consume back key
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
ImageView img = (ImageView)findViewById(R.id.imageanimation);
AnimationDrawable frameAnimation = (AnimationDrawable)img.getDrawable();
frameAnimation.setCallback(img);
frameAnimation.setVisible(true, true);
frameAnimation.start();
}
}
| false | true | public void run() {
/* Call Register Activity when session is not established */
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
boolean saved = prefs.getBoolean(MyPref.KEY_SESSION, false);
if(saved == false)
{
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), EntranceActivity.class));
}
else {
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), MainActivity.class));
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_in_left);
}
}
| public void run() {
/* Call Register Activity when session is not established */
SharedPreferences prefs = getSharedPreferences("MyPref", MODE_PRIVATE);
boolean saved = prefs.getBoolean(MyPref.KEY_SESSION, false);
if(saved == false)
{
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), EntranceActivity.class));
}
else {
Intent intent = new Intent();
startActivity(intent.setClass(getApplicationContext(), MainActivity.class));
}
finish();
//overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_in_left);
}
|
diff --git a/fabric/fabric-cxf-registry/src/test/java/io/fabric8/cxf/registry/JsonEncodeTest.java b/fabric/fabric-cxf-registry/src/test/java/io/fabric8/cxf/registry/JsonEncodeTest.java
index db7c9d82d..fbe96a813 100644
--- a/fabric/fabric-cxf-registry/src/test/java/io/fabric8/cxf/registry/JsonEncodeTest.java
+++ b/fabric/fabric-cxf-registry/src/test/java/io/fabric8/cxf/registry/JsonEncodeTest.java
@@ -1,35 +1,35 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.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 io.fabric8.cxf.registry;
import io.fabric8.internal.JsonHelper;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
*/
public class JsonEncodeTest {
@Test
public void testJsonEncoding() throws Exception {
String objectName = "org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\",port=\"CustomerService\",instance.id=1776063910";
- String expectedValue = "org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\\\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\\\",port=\\\"CustomerService\\\",instance.id=1776063910";
+ String expectedValue = "\"org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\\\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\\\",port=\\\"CustomerService\\\",instance.id=1776063910\"";
String jsonValue = JsonHelper.jsonEncodeString(objectName);
assertEquals("encoded JSON value", expectedValue, jsonValue);
}
}
| true | true | public void testJsonEncoding() throws Exception {
String objectName = "org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\",port=\"CustomerService\",instance.id=1776063910";
String expectedValue = "org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\\\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\\\",port=\\\"CustomerService\\\",instance.id=1776063910";
String jsonValue = JsonHelper.jsonEncodeString(objectName);
assertEquals("encoded JSON value", expectedValue, jsonValue);
}
| public void testJsonEncoding() throws Exception {
String objectName = "org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\",port=\"CustomerService\",instance.id=1776063910";
String expectedValue = "\"org.apache.cxf:bus.id=rest-cxf515624438,type=Bus.Service.Endpoint,service=\\\"{http://rest.fuse.quickstarts.jboss.org/}CustomerService\\\",port=\\\"CustomerService\\\",instance.id=1776063910\"";
String jsonValue = JsonHelper.jsonEncodeString(objectName);
assertEquals("encoded JSON value", expectedValue, jsonValue);
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java b/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
index 1cfc1588f..b6f7bd328 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/dto/RawDataImportRequest.java
@@ -1,230 +1,230 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package org.waterforpeople.mapping.app.web.dto;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.gallatinsystems.framework.rest.RestRequest;
public class RawDataImportRequest extends RestRequest {
private static final long serialVersionUID = 3792808180110794885L;
private static final ThreadLocal<DateFormat> IN_FMT = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
};
};
private static final String VALUE = "value=";
private static final String TYPE = "type=";
public static final String SURVEY_INSTANCE_ID_PARAM = "surveyInstanceId";
public static final String COLLECTION_DATE_PARAM = "collectionDate";
public static final String QUESTION_ID_PARAM = "questionId";
public static final String SURVEY_ID_PARAM = "surveyId";
public static final String SUBMITTER_PARAM = "submitter";
public static final String FIXED_FIELD_VALUE_PARAM = "values";
public static final String LOCALE_ID_PARAM = "surveyedLocale";
public static final String SAVE_SURVEY_INSTANCE_ACTION = "saveSurveyInstance";
public static final String RESET_SURVEY_INSTANCE_ACTION = "resetSurveyInstance";
public static final String SAVE_FIXED_FIELD_SURVEY_INSTANCE_ACTION = "ingestFixedFormat";
public static final String UPDATE_SUMMARIES_ACTION = "updateSummaries";
public static final String SAVE_MESSAGE_ACTION = "saveMessage";
public static final String FIELD_VAL_DELIMITER = ";;";
private Long surveyId;
private Long surveyedLocaleId;
private Long surveyInstanceId = null;
private Date collectionDate = null;
private String submitter = null;
private HashMap<Long, String[]> questionAnswerMap = null;
private List<String> fixedFieldValues;
public List<String> getFixedFieldValues() {
return fixedFieldValues;
}
public void setFixedFieldValues(List<String> fixedFieldValues) {
this.fixedFieldValues = fixedFieldValues;
}
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSurveyId() {
return surveyId;
}
public void setSurveyId(Long surveyId) {
this.surveyId = surveyId;
}
public Long getSurveyInstanceId() {
return surveyInstanceId;
}
public void setSurveyInstanceId(Long surveyInstanceId) {
this.surveyInstanceId = surveyInstanceId;
}
public Date getCollectionDate() {
return collectionDate;
}
public void setCollectionDate(Date collectionDate) {
this.collectionDate = collectionDate;
}
public HashMap<Long, String[]> getQuestionAnswerMap() {
return questionAnswerMap;
}
public void setQuestionAnswerMap(HashMap<Long, String[]> questionAnswerMap) {
this.questionAnswerMap = questionAnswerMap;
}
public void putQuestionAnswer(Long questionId, String value, String type) {
if (questionAnswerMap == null)
questionAnswerMap = new HashMap<Long, String[]>();
questionAnswerMap.put(questionId, new String[] { value,
(type != null ? type : "VALUE") });
}
@Override
protected void populateErrors() {
// TODO handle errors
}
@Override
protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
- String[] vals = req.getParameter(FIXED_FIELD_VALUE_PARAM).split(
+ String[] vals = URLDecoder.decode(req.getParameter(FIXED_FIELD_VALUE_PARAM), "UTF-8").split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
- String[] parts = answers[i].split("\\|");
+ String[] parts = URLDecoder.decode(answers[i], "UTF-8").split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
setSubmitter(req.getParameter(SUBMITTER_PARAM));
}
}
public void setSubmitter(String submitter) {
this.submitter = submitter;
}
public String getSubmitter() {
return submitter;
}
public Long getSurveyedLocaleId() {
return surveyedLocaleId;
}
public void setSurveyedLocaleId(Long surveyedLocaleId) {
this.surveyedLocaleId = surveyedLocaleId;
}
}
| false | true | protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
String[] vals = req.getParameter(FIXED_FIELD_VALUE_PARAM).split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
String[] parts = answers[i].split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
setSubmitter(req.getParameter(SUBMITTER_PARAM));
}
}
| protected void populateFields(HttpServletRequest req) throws Exception {
if (req.getParameter(LOCALE_ID_PARAM) != null) {
try {
setSurveyedLocaleId(new Long(req.getParameter(LOCALE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(SURVEY_INSTANCE_ID_PARAM) != null) {
try {
setSurveyInstanceId(new Long(
req.getParameter(SURVEY_INSTANCE_ID_PARAM)));
} catch (Exception e) {
// swallow
}
}
if (req.getParameter(FIXED_FIELD_VALUE_PARAM) != null) {
fixedFieldValues = new ArrayList<String>();
String[] vals = URLDecoder.decode(req.getParameter(FIXED_FIELD_VALUE_PARAM), "UTF-8").split(
FIELD_VAL_DELIMITER);
for (int i = 0; i < vals.length; i++) {
fixedFieldValues.add(vals[i]);
}
}
if (req.getParameter(QUESTION_ID_PARAM) != null) {
String[] answers = req.getParameterValues(QUESTION_ID_PARAM);
if (answers != null) {
for (int i = 0; i < answers.length; i++) {
String[] parts = URLDecoder.decode(answers[i], "UTF-8").split("\\|");
String qId = null;
String val = null;
String type = null;
if (parts.length > 1) {
qId = parts[0];
if (parts.length == 3) {
val = parts[1];
type = parts[2];
} else {
StringBuffer buf = new StringBuffer();
for (int idx = 1; idx < parts.length - 1; idx++) {
if (idx > 1) {
buf.append("|");
}
buf.append(parts[idx]);
}
val = buf.toString();
type = parts[parts.length - 1];
}
if (val != null) {
if (val.startsWith(VALUE)) {
val = val.substring(VALUE.length());
}
if (type.startsWith(TYPE)) {
type = type.substring(TYPE.length());
}
if (val != null && val.contains("^^")) {
val = val.replaceAll("\\^\\^", "|");
}
putQuestionAnswer(new Long(qId), val, type);
}
}
}
}
}
if (req.getParameter(SURVEY_ID_PARAM) != null) {
surveyId = new Long(req.getParameter(SURVEY_ID_PARAM).trim());
}
if (req.getParameter(COLLECTION_DATE_PARAM) != null
&& req.getParameter(COLLECTION_DATE_PARAM).trim().length() > 0 ) {
String colDate = req.getParameter(COLLECTION_DATE_PARAM).trim();
if (colDate.contains("%") || colDate.contains("+")) {
colDate = URLDecoder.decode(colDate, "UTF-8");
}
collectionDate = IN_FMT.get().parse(colDate);
}
if (req.getParameter(SUBMITTER_PARAM) != null) {
setSubmitter(req.getParameter(SUBMITTER_PARAM));
}
}
|
diff --git a/src/main/java/com/yahoo/ycsb/db/InfinispanClient.java b/src/main/java/com/yahoo/ycsb/db/InfinispanClient.java
index 0665cd0..fef6e09 100644
--- a/src/main/java/com/yahoo/ycsb/db/InfinispanClient.java
+++ b/src/main/java/com/yahoo/ycsb/db/InfinispanClient.java
@@ -1,320 +1,320 @@
package com.yahoo.ycsb.db;
import com.yahoo.ycsb.Client;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.StringByteIterator;
import org.infinispan.Cache;
import org.infinispan.atomic.AtomicMap;
import org.infinispan.atomic.AtomicMapLookup;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import javax.transaction.TransactionManager;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
/**
* This is a client implementation for Infinispan 5.x.
*
* Some settings:
*
* @author Manik Surtani (manik AT jboss DOT org)
*/
public class InfinispanClient extends DB {
// An optimisation for clustered mode
private final boolean clustered;
private static EmbeddedCacheManager infinispanManager = null;
private static Cache globalCache = null;
private static TransactionManager tm = null;
private static final Object syncObject = new Object();
private static final Log logger = LogFactory.getLog(InfinispanClient.class);
public InfinispanClient() {
clustered = Boolean.getBoolean("infinispan.clustered");
System.out.println("CLUSTERED: "+clustered);
}
public void init(int nodes) throws DBException {
try {
synchronized (syncObject) {
if(infinispanManager == null){
infinispanManager = new DefaultCacheManager("ispn.xml");
String table = "usertable";
globalCache = infinispanManager.getCache(table);
tm=globalCache.getAdvancedCache().getTransactionManager();
Client.NODE_INDEX = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash()).getMyId(infinispanManager.getTransport().getAddress());
MagicKey.ADDRESS = infinispanManager.getTransport().getAddress();
MagicKey.HASH = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash());
MagicKey.OWNERS = globalCache.getAdvancedCache().getConfiguration().getNumOwners();
Transport transport = infinispanManager.getTransport();
while (transport.getMembers().size() < nodes) {
try {
- Thread.sleep(1);
+ Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}
} catch (IOException e) {
throw new DBException(e);
}
}
public void cleanup() {
synchronized (syncObject) {
if(infinispanManager != null){
infinispanManager.stop();
infinispanManager = null;
}
}
}
public void waitLoad(){
Object waitValue = null;
while(waitValue == null || ((Integer)waitValue) != 1){
try{
waitValue = globalCache.get("Sebastiano_key");
}
catch(Exception e){
waitValue = null;
}
}
}
public void endLoad(){
boolean loaded = false;
while(!loaded){
try{
globalCache.put("Sebastiano_key", new Integer(1));
loaded = true;
}
catch(Exception e){
loaded = false;
}
}
}
public int read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
try {
Map<String, String> row;
if (clustered) {
row = AtomicMapLookup.getAtomicMap(globalCache, key, false);
} else {
Cache<Object, Map<String, String>> cache = globalCache;
row = cache.get(key);
}
if (row != null) {
result.clear();
if (fields == null || fields.isEmpty()) {
StringByteIterator.putAllAsByteIterators(result, row);
} else {
for (String field : fields) result.put(field, new StringByteIterator(row.get(field)));
}
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int read(MagicKey key, Set<String> fields, HashMap<String, ByteIterator> result) {
try {
Map<String, String> row;
if (clustered) {
row = AtomicMapLookup.getAtomicMap(globalCache, key, false);
} else {
Cache<Object, Map<String, String>> cache = globalCache;
row = cache.get(key.key);
}
if (row != null) {
result.clear();
if (fields == null || fields.isEmpty()) {
StringByteIterator.putAllAsByteIterators(result, row);
} else {
for (String field : fields) result.put(field, new StringByteIterator(row.get(field)));
}
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
logger.warn("Infinispan does not support scan semantics");
return OK;
}
public int update(String table, String key, HashMap<String, ByteIterator> values) {
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(globalCache, key);
StringByteIterator.putAllAsStrings(row, values);
} else {
Cache<Object, Map<String, String>> cache = globalCache;
Map<String, String> row = cache.get(key);
if (row == null) {
row = StringByteIterator.getStringMap(values);
cache.put(key, row);
} else {
StringByteIterator.putAllAsStrings(row, values);
}
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int update(MagicKey key, HashMap<String, ByteIterator> values) {
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(globalCache, key);
StringByteIterator.putAllAsStrings(row, values);
} else {
Cache<Object, Map<String, String>> cache = globalCache;
Map<String, String> row = cache.get(key);
if (row == null) {
row = StringByteIterator.getStringMap(values);
cache.put(key.key, row);
} else {
StringByteIterator.putAllAsStrings(row, values);
}
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int insert(String table, String key, HashMap<String, ByteIterator> values) {
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(globalCache, key);
row.clear();
StringByteIterator.putAllAsStrings(row, values);
} else {
//globalCache.put(key, values);
Cache<Object, Map<String, String>> cache = globalCache;
Map<String, String> row = StringByteIterator.getStringMap(values);
cache.put(key, row);
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int insert(MagicKey key, HashMap<String, ByteIterator> values) {
try {
if (clustered) {
AtomicMap<String, String> row = AtomicMapLookup.getAtomicMap(globalCache, key);
row.clear();
StringByteIterator.putAllAsStrings(row, values);
} else {
//globalCache.put(key, values);
Cache<Object, Map<String, String>> cache = globalCache;
Map<String, String> row = StringByteIterator.getStringMap(values);
cache.put(key.key, row);
}
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int delete(String table, String key) {
try {
if (clustered)
AtomicMapLookup.removeAtomicMap(globalCache, key);
else
globalCache.remove(key);
return OK;
} catch (Exception e) {
return ERROR;
}
}
public int beginTransaction(){
if (tm==null) return ERROR ;
try {
tm.begin();
return OK;
}
catch (Exception e) {
//throw new RuntimeException(e);
e.printStackTrace();
return DB.ERROR;
}
}
@Override
public void markWriteTx() {
globalCache.markAsWriteTransaction();
}
public int endTransaction(boolean commit){
if (tm == null){
return ERROR;
}
try {
if (commit){
tm.commit();
return OK;
}
else{
tm.rollback();
return ERROR;
}
}
catch (Exception e) {
//throw new RuntimeException(e);
return ERROR;
}
}
}
| true | true | public void init(int nodes) throws DBException {
try {
synchronized (syncObject) {
if(infinispanManager == null){
infinispanManager = new DefaultCacheManager("ispn.xml");
String table = "usertable";
globalCache = infinispanManager.getCache(table);
tm=globalCache.getAdvancedCache().getTransactionManager();
Client.NODE_INDEX = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash()).getMyId(infinispanManager.getTransport().getAddress());
MagicKey.ADDRESS = infinispanManager.getTransport().getAddress();
MagicKey.HASH = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash());
MagicKey.OWNERS = globalCache.getAdvancedCache().getConfiguration().getNumOwners();
Transport transport = infinispanManager.getTransport();
while (transport.getMembers().size() < nodes) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}
} catch (IOException e) {
throw new DBException(e);
}
}
| public void init(int nodes) throws DBException {
try {
synchronized (syncObject) {
if(infinispanManager == null){
infinispanManager = new DefaultCacheManager("ispn.xml");
String table = "usertable";
globalCache = infinispanManager.getCache(table);
tm=globalCache.getAdvancedCache().getTransactionManager();
Client.NODE_INDEX = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash()).getMyId(infinispanManager.getTransport().getAddress());
MagicKey.ADDRESS = infinispanManager.getTransport().getAddress();
MagicKey.HASH = ((CustomHashing)globalCache.getAdvancedCache().getDistributionManager().getConsistentHash());
MagicKey.OWNERS = globalCache.getAdvancedCache().getConfiguration().getNumOwners();
Transport transport = infinispanManager.getTransport();
while (transport.getMembers().size() < nodes) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}
} catch (IOException e) {
throw new DBException(e);
}
}
|
diff --git a/NoItem/src/net/worldoftomorrow/nala/ni/listeners/EventListener.java b/NoItem/src/net/worldoftomorrow/nala/ni/listeners/EventListener.java
index 8430252..45889a3 100644
--- a/NoItem/src/net/worldoftomorrow/nala/ni/listeners/EventListener.java
+++ b/NoItem/src/net/worldoftomorrow/nala/ni/listeners/EventListener.java
@@ -1,639 +1,664 @@
package net.worldoftomorrow.nala.ni.listeners;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.minecraft.server.Container;
import net.minecraft.server.CraftingManager;
import net.minecraft.server.InventoryCraftResult;
import net.minecraft.server.InventoryCrafting;
import net.worldoftomorrow.nala.ni.CustomBlocks;
import net.worldoftomorrow.nala.ni.Enchant;
import net.worldoftomorrow.nala.ni.EventTypes;
import net.worldoftomorrow.nala.ni.Log;
import net.worldoftomorrow.nala.ni.NoItem;
import net.worldoftomorrow.nala.ni.Perms;
import net.worldoftomorrow.nala.ni.StringHelper;
import net.worldoftomorrow.nala.ni.CustomItems.CustomBlock;
import net.worldoftomorrow.nala.ni.CustomItems.CustomFurnace;
import net.worldoftomorrow.nala.ni.CustomItems.CustomWorkbench;
import net.worldoftomorrow.nala.ni.tasks.LoginTask;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerShearEntityEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.scheduler.BukkitScheduler;
import forge.bukkit.ModInventoryView;
public class EventListener implements Listener {
private final NoItem plugin;
public EventListener(NoItem plugin) {
this.plugin = plugin;
}
/**
* <p>
* Check for the following: <br />
* NoHold
* </p>
*
* @param event
*/
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player p = event.getPlayer();
ItemStack inhand = p.getItemInHand();
BukkitScheduler scheduler = plugin.getServer().getScheduler();
if (inhand.getType() != Material.AIR && Perms.NOHOLD.has(p, inhand)) {
scheduler.scheduleSyncDelayedTask(plugin, new LoginTask(p), 60L);
}
}
/**
* <p>
* Check for the following: <br />
* NoDrop
* </p>
*
* @param event
*/
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
Player p = event.getPlayer();
ItemStack drop = event.getItemDrop().getItemStack();
if (Perms.NODROP.has(p, drop)) {
event.setCancelled(true);
this.notify(p, EventTypes.DROP, drop);
}
}
/**
* <p>
* Check for the following: <br />
* NoPickup<br />
* NoHave<br />
* NoHold<br />
* </p>
*
* @param event
*/
@EventHandler
public void onItemPickup(PlayerPickupItemEvent event) {
Player p = event.getPlayer();
ItemStack item = event.getItem().getItemStack();
if (Perms.NOPICKUP.has(p, item)) {
event.setCancelled(true);
this.notify(p, EventTypes.PICKUP, item);
} else if (Perms.NOHAVE.has(p, item)) {
event.setCancelled(true);
event.getItem().setPickupDelay(200);
this.notify(p, EventTypes.HAVE, item);
} else if (Perms.NOHOLD.has(p, item)) {
PlayerInventory inv = p.getInventory();
if (p.getItemInHand().getType() == Material.AIR
&& inv.firstEmpty() == inv.getHeldItemSlot()) {
event.setCancelled(true);
event.getItem().setPickupDelay(200);
this.notify(p, EventTypes.HOLD, item);
}
}
}
/**
* <p>
* Check for the following: <br />
* OnDeath
* </p>
*
* @param event
*/
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
Player p = event.getEntity();
if (Perms.ONDEATH.has(p, "keep")) {
List<ItemStack> drops = new ArrayList<ItemStack>(event.getDrops());
event.getDrops().clear();
plugin.getItemList().put(p.getName(), drops);
} else if (Perms.ONDEATH.has(p, "remove")) {
event.getDrops().clear();
}
}
/**
* <p>
* Check for the following: <br />
* OnDeath
* </p>
*
* @param event
*/
@EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) {
Player p = event.getPlayer();
Map<String, List<ItemStack>> itemList = plugin.getItemList();
if (itemList.containsKey(p.getName())) {
List<ItemStack> items = itemList.get(p.getName());
Map<Integer, ItemStack> r = p.getInventory().addItem(items.toArray(new ItemStack[items.size()]));
if(!r.values().isEmpty()) {
itemList.put(p.getName(), new ArrayList<ItemStack>(r.values()));
p.sendMessage(ChatColor.BLUE + "You have " + r.size() + " unclaimed items!");
p.sendMessage(ChatColor.BLUE + "Make room in your inventory, then type \"/noitem claim\" to claim them!");
}
}
}
/**
* <p>
* Check for the following: <br />
* NoBreak
* </p>
*
* @param event
*/
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Player p = event.getPlayer();
Block b = event.getBlock();
// Null check for certain custom blocks that show null
if(b != null && Perms.NOBREAK.has(p, b)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREAK, b);
}
}
/**
* <p>
* Check for the following: <br />
* NoPlace
* </p>
*
* @param event
*/
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player p = event.getPlayer();
Block b = event.getBlock();
// Null check for certain custom blocks that show null
if(b != null && Perms.NOPLACE.has(p, b)) {
event.setCancelled(true);
this.notify(p, EventTypes.PLACE, b);
}
}
/**
* <p>
* Check for the following: <br />
* NoHold<br />
* NoHave<br />
* NoWear<br />
* NoCook<br />
* NoCraft<br />
* NoBrew<br />
* </p>
*
* @param event
*/
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Player p = Bukkit.getPlayer(event.getWhoClicked().getName());
Inventory inv = event.getInventory();
ItemStack oncur = p.getItemOnCursor();
ItemStack current = event.getCurrentItem();
int rs = event.getRawSlot();
InventoryView view = event.getView();
switch(view.getType()) {
case CRAFTING:
if(event.getSlotType() == SlotType.ARMOR) {
if(oncur != null && Perms.NOWEAR.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, oncur);
}
} else if (event.isShiftClick() && current != null && Perms.NOWEAR.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, current);
}
break;
case BREWING:
+ // Ingredient slot
if(rs == 3 && oncur != null) {
for(ItemStack item : inv.getContents()) {
if(item != null) {
int dv = item.getDurability();
int id = oncur.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
}
+ // Potion Slots
} else if (rs < 3 && rs >= 0) {
ItemStack ing = inv.getItem(3);
if(ing != null && oncur != null) {
int dv = oncur.getDurability();
int id = ing.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
+ // Inventory Slot (shift clicking)
+ } else if (event.isShiftClick() && current != null) {
+ ItemStack ing = inv.getItem(3);
+ if(current.getType() == Material.POTION && ing != null) {
+ ItemStack item;
+ for(int i = 0; i < 3; i++) {
+ item = view.getItem(i);
+ if(item == null && Perms.NOBREW.has(p, ing.getDurability() + "." + current.getTypeId())) {
+ event.setCancelled(true);
+ this.notify(p, EventTypes.BREW, ing.getDurability() + "." + current.getTypeId());
+ break;
+ }
+ }
+ } else if (ing == null && current.getType() != Material.POTION) {
+ ItemStack item;
+ for(int i = 0; i < 3; i++) {
+ item = view.getItem(i);
+ if(item != null && Perms.NOBREW.has(p, item.getDurability() + "." + current.getTypeId())) {
+ event.setCancelled(true);
+ this.notify(p, EventTypes.BREW, item.getDurability() + "." + current.getTypeId());
+ }
+ }
+ }
}
break;
case FURNACE:
if(rs == 0 && oncur != null) {
if(Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
} else if (rs != 0 && event.isShiftClick()) {
if(Perms.NOCOOK.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, current);
}
}
break;
default:
Block b = p.getTargetBlock(null, 8);
if(!CustomBlocks.isCustomBlock(b))
break;
CustomBlock cb = CustomBlocks.getCustomBlock(b);
switch(cb.getType()) {
case FURNACE:
Log.debug("Is a furnace");
CustomFurnace cf = (CustomFurnace) cb;
if(cf.isFuelSlot((short) rs) && oncur != null) {
for(Short s : cf.getItemSlots()) {
ItemStack item = view.getItem(s);
if(item != null && Perms.NOCOOK.has(p, item)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, item);
break;
}
}
} else if (cf.isItemSlot((short) rs) && oncur != null) {
if(!cf.usesFuel() && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
break;
}
for(Short s : cf.getFuelSlots()) {
if(view.getItem(s) != null && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
}
}
break;
case WORKBENCH:
CustomWorkbench cw = (CustomWorkbench) cb;
if(cw.isRecipeSlot((short) rs)) {
try {
ModInventoryView miv = (ModInventoryView) view;
Field fcontainer = view.getClass().getDeclaredField("container");
fcontainer.setAccessible(true);
Container container = (Container) fcontainer.get(miv);
InventoryCrafting craftingInv = new InventoryCrafting(container, 3, 3);
craftingInv.resultInventory = new InventoryCraftResult();
for(int i = 0; i <= 8; i++) {
short slot = (Short) cw.getRecipeSlots().toArray()[i];
ItemStack item = slot == rs ? oncur : view.getItem(slot);
if(item == null) continue;
net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
craftingInv.setItem(i, stack);
}
//TODO: this is probably broken completely. I need to get the NMS World not Bukkit World; This also breaks new builds with Tekkit
net.minecraft.server.ItemStack mcResult = CraftingManager.getInstance().craft(craftingInv, null);
if(mcResult == null) break;
ItemStack result = new ItemStack(mcResult.id, 1, (short) mcResult.getData());
if (Perms.NOCRAFT.has(p, result)) {
event.setCancelled(true);
this.notify(p, EventTypes.CRAFT, result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
default:
Log.severe("Undefined custom block.");
break;
}
break;
}
//NoHold handling
if(event.getSlotType() == SlotType.QUICKBAR
&& oncur != null
&& !event.isCancelled()
&& Perms.NOHOLD.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, oncur);
} else if (event.getSlotType() != SlotType.QUICKBAR
&& event.isShiftClick()
&& !event.isCancelled()
&& current != null
&& Perms.NOHOLD.has(p, current)) {
Inventory binv = view.getBottomInventory();
if(binv instanceof PlayerInventory) {
for(int i = 0; i < 9; i++) {
ItemStack stack = binv.getItem(i);
if(stack != null) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, stack);
continue;
}
}
}
}
//NoHave handling
if(current != null && Perms.NOHAVE.has(p, current)) {
this.notify(p, EventTypes.HAVE, current);
p.getInventory().remove(current);
}
}
/**
* <p>
* Check for the following: <br />
* NoOpen
* </p>
* @param event
*/
@EventHandler
public void onInventoryOpen(InventoryOpenEvent event) {
Player p = Bukkit.getPlayer(event.getPlayer().getName());
List<Block> blocks = p.getLastTwoTargetBlocks(null, 8);
if(!blocks.isEmpty() && blocks.size() == 2) {
Block target = blocks.get(1);
if(Perms.NOOPEN.has(p, target)) {
event.setCancelled(true);
this.notify(p, EventTypes.OPEN, target);
return;
}
}
ItemStack inHand = p.getItemInHand();
CustomWorkbench cw = CustomBlocks.getWorkbench(inHand);
if(cw != null && !cw.isBlock()) {
if(Perms.NOOPEN.has(p, inHand)) {
event.setCancelled(true);
this.notify(p, EventTypes.OPEN, inHand);
}
}
}
/**
* <p>
* Check for the following: <br />
* NoHold<br />
* NoHave<br />
* </p>
*
* @param event
*/
@EventHandler
public void onItemHeld(PlayerItemHeldEvent event) {
Player p = event.getPlayer();
PlayerInventory inv = p.getInventory();
ItemStack allowed = inv.getItem(event.getPreviousSlot());
ItemStack notAllowed = inv.getItem(event.getNewSlot());
if(notAllowed != null) {
if(Perms.NOHOLD.has(p, notAllowed)) {
inv.setItem(event.getPreviousSlot(), notAllowed);
inv.setItem(event.getNewSlot(), allowed);
this.notify(p, EventTypes.HOLD, notAllowed);
}
if(Perms.NOHAVE.has(p, notAllowed)) {
this.notify(p, EventTypes.HAVE, notAllowed);
p.getInventory().remove(notAllowed);
}
}
}
/**
* <p>
* Check for the following:<br />
* NoCraft
* </p>
* @param event
*/
@EventHandler
public void onItemCraft(CraftItemEvent event) {
Player p = Bukkit.getPlayer(event.getWhoClicked().getName());
ItemStack result = event.getCurrentItem();
if(Perms.NOCRAFT.has(p, result)) {
event.setCancelled(true);
this.notify(p, EventTypes.CRAFT, result);
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* NoHave<br />
* </p>
* @param event
*/
@EventHandler
public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
Block b = event.getClickedBlock();
ItemStack inHand = event.getItem();
switch(event.getAction()) {
case RIGHT_CLICK_BLOCK:
case LEFT_CLICK_BLOCK:
if(Perms.NOUSE.has(p, b)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, b);
} else if (inHand != null && Perms.NOUSE.has(p, inHand)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, inHand);
}
break;
case RIGHT_CLICK_AIR:
if(inHand != null && Perms.NOUSE.has(p, inHand)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, inHand);
}
break;
case LEFT_CLICK_AIR:
break;
case PHYSICAL:
if(Perms.NOUSE.has(p, b)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, b);
}
}
if(inHand != null && Perms.NOHAVE.has(p, inHand)) {
event.setCancelled(true);
this.notify(p, EventTypes.HAVE, inHand);
p.getInventory().remove(inHand);
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* </p>
* @param event
*/
@EventHandler
public void onBowShoot(EntityShootBowEvent event) {
Entity e = event.getEntity();
if (e instanceof Player) {
Player p = (Player) e;
ItemStack bow = event.getBow().clone();
bow.setDurability((short) 0);
if(Perms.NOUSE.has(p, bow)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, bow);
}
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* </p>
* @param event
*/
@EventHandler
public void onBucketEmpty(PlayerBucketEmptyEvent event) {
Player p = event.getPlayer();
ItemStack bucket = p.getItemInHand();
if(Perms.NOUSE.has(p, bucket)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, bucket);
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* </p>
* @param event
*/
@EventHandler
public void onBucketFill(PlayerBucketFillEvent event) {
Player p = event.getPlayer();
ItemStack bucket = event.getItemStack();
if(Perms.NOUSE.has(p, bucket)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, bucket);
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* </p>
* @param event
*/
@EventHandler
public void onShear(PlayerShearEntityEvent event) {
Player p = event.getPlayer();
if(Perms.NOUSE.has(p, new ItemStack(Material.SHEARS))) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, new ItemStack(Material.SHEARS));
}
}
/**
* <p>
* Check for the following:<br />
* NoUse<br />
* </p>
* @param event
*/
@EventHandler
public void onPlayerAttack(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
if (damager instanceof Player) {
Player p = (Player) damager;
ItemStack inhand = p.getItemInHand().clone();
if(Perms.NOUSE.has(p, inhand)) {
event.setCancelled(true);
this.notify(p, EventTypes.USE, inhand);
}
}
}
/**
* <p>
* Check for the following:<br />
* NoEnchant<br />
* </p>
* @param event
*/
@EventHandler
public void onItemEnchant(EnchantItemEvent event) {
Player p = event.getEnchanter();
ItemStack item = event.getItem();
Map<Enchantment, Integer> enchantments = event.getEnchantsToAdd();
for(Enchantment enchantment : enchantments.keySet()) {
Enchant enchant = Enchant.getByID(enchantment.getId());
if(Perms.NOENCHANT.has(p, enchant.getName(), item)) {
//Silently remove the enchantment
enchantments.remove(enchantment);
//If there is not another enchantment, cancel the event.
if(enchantments.size() == 0) {
event.setCancelled(true);
this.notify(p, EventTypes.ENCHANT, enchant.getName());
break;
}
}
}
}
private void notify(Player p, EventTypes type, ItemStack stack) {
StringHelper.notifyPlayer(p, type, stack);
StringHelper.notifyAdmin(p, type, stack);
}
private void notify(Player p, EventTypes type, Block b) {
this.notify(p, type, new ItemStack(b.getType(), b.getData()));
}
private void notify(Player p, EventTypes type, String recipe) {
StringHelper.notifyAdmin(p, type, recipe);
StringHelper.notifyPlayer(p, type, recipe);
}
}
| false | true | public void onInventoryClick(InventoryClickEvent event) {
Player p = Bukkit.getPlayer(event.getWhoClicked().getName());
Inventory inv = event.getInventory();
ItemStack oncur = p.getItemOnCursor();
ItemStack current = event.getCurrentItem();
int rs = event.getRawSlot();
InventoryView view = event.getView();
switch(view.getType()) {
case CRAFTING:
if(event.getSlotType() == SlotType.ARMOR) {
if(oncur != null && Perms.NOWEAR.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, oncur);
}
} else if (event.isShiftClick() && current != null && Perms.NOWEAR.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, current);
}
break;
case BREWING:
if(rs == 3 && oncur != null) {
for(ItemStack item : inv.getContents()) {
if(item != null) {
int dv = item.getDurability();
int id = oncur.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
}
} else if (rs < 3 && rs >= 0) {
ItemStack ing = inv.getItem(3);
if(ing != null && oncur != null) {
int dv = oncur.getDurability();
int id = ing.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
}
break;
case FURNACE:
if(rs == 0 && oncur != null) {
if(Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
} else if (rs != 0 && event.isShiftClick()) {
if(Perms.NOCOOK.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, current);
}
}
break;
default:
Block b = p.getTargetBlock(null, 8);
if(!CustomBlocks.isCustomBlock(b))
break;
CustomBlock cb = CustomBlocks.getCustomBlock(b);
switch(cb.getType()) {
case FURNACE:
Log.debug("Is a furnace");
CustomFurnace cf = (CustomFurnace) cb;
if(cf.isFuelSlot((short) rs) && oncur != null) {
for(Short s : cf.getItemSlots()) {
ItemStack item = view.getItem(s);
if(item != null && Perms.NOCOOK.has(p, item)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, item);
break;
}
}
} else if (cf.isItemSlot((short) rs) && oncur != null) {
if(!cf.usesFuel() && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
break;
}
for(Short s : cf.getFuelSlots()) {
if(view.getItem(s) != null && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
}
}
break;
case WORKBENCH:
CustomWorkbench cw = (CustomWorkbench) cb;
if(cw.isRecipeSlot((short) rs)) {
try {
ModInventoryView miv = (ModInventoryView) view;
Field fcontainer = view.getClass().getDeclaredField("container");
fcontainer.setAccessible(true);
Container container = (Container) fcontainer.get(miv);
InventoryCrafting craftingInv = new InventoryCrafting(container, 3, 3);
craftingInv.resultInventory = new InventoryCraftResult();
for(int i = 0; i <= 8; i++) {
short slot = (Short) cw.getRecipeSlots().toArray()[i];
ItemStack item = slot == rs ? oncur : view.getItem(slot);
if(item == null) continue;
net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
craftingInv.setItem(i, stack);
}
//TODO: this is probably broken completely. I need to get the NMS World not Bukkit World; This also breaks new builds with Tekkit
net.minecraft.server.ItemStack mcResult = CraftingManager.getInstance().craft(craftingInv, null);
if(mcResult == null) break;
ItemStack result = new ItemStack(mcResult.id, 1, (short) mcResult.getData());
if (Perms.NOCRAFT.has(p, result)) {
event.setCancelled(true);
this.notify(p, EventTypes.CRAFT, result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
default:
Log.severe("Undefined custom block.");
break;
}
break;
}
//NoHold handling
if(event.getSlotType() == SlotType.QUICKBAR
&& oncur != null
&& !event.isCancelled()
&& Perms.NOHOLD.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, oncur);
} else if (event.getSlotType() != SlotType.QUICKBAR
&& event.isShiftClick()
&& !event.isCancelled()
&& current != null
&& Perms.NOHOLD.has(p, current)) {
Inventory binv = view.getBottomInventory();
if(binv instanceof PlayerInventory) {
for(int i = 0; i < 9; i++) {
ItemStack stack = binv.getItem(i);
if(stack != null) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, stack);
continue;
}
}
}
}
//NoHave handling
if(current != null && Perms.NOHAVE.has(p, current)) {
this.notify(p, EventTypes.HAVE, current);
p.getInventory().remove(current);
}
}
| public void onInventoryClick(InventoryClickEvent event) {
Player p = Bukkit.getPlayer(event.getWhoClicked().getName());
Inventory inv = event.getInventory();
ItemStack oncur = p.getItemOnCursor();
ItemStack current = event.getCurrentItem();
int rs = event.getRawSlot();
InventoryView view = event.getView();
switch(view.getType()) {
case CRAFTING:
if(event.getSlotType() == SlotType.ARMOR) {
if(oncur != null && Perms.NOWEAR.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, oncur);
}
} else if (event.isShiftClick() && current != null && Perms.NOWEAR.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.WEAR, current);
}
break;
case BREWING:
// Ingredient slot
if(rs == 3 && oncur != null) {
for(ItemStack item : inv.getContents()) {
if(item != null) {
int dv = item.getDurability();
int id = oncur.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
}
// Potion Slots
} else if (rs < 3 && rs >= 0) {
ItemStack ing = inv.getItem(3);
if(ing != null && oncur != null) {
int dv = oncur.getDurability();
int id = ing.getTypeId();
if (Perms.NOBREW.has(p, dv + "." + id)) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, dv + ":" + id);
}
}
// Inventory Slot (shift clicking)
} else if (event.isShiftClick() && current != null) {
ItemStack ing = inv.getItem(3);
if(current.getType() == Material.POTION && ing != null) {
ItemStack item;
for(int i = 0; i < 3; i++) {
item = view.getItem(i);
if(item == null && Perms.NOBREW.has(p, ing.getDurability() + "." + current.getTypeId())) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, ing.getDurability() + "." + current.getTypeId());
break;
}
}
} else if (ing == null && current.getType() != Material.POTION) {
ItemStack item;
for(int i = 0; i < 3; i++) {
item = view.getItem(i);
if(item != null && Perms.NOBREW.has(p, item.getDurability() + "." + current.getTypeId())) {
event.setCancelled(true);
this.notify(p, EventTypes.BREW, item.getDurability() + "." + current.getTypeId());
}
}
}
}
break;
case FURNACE:
if(rs == 0 && oncur != null) {
if(Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
} else if (rs != 0 && event.isShiftClick()) {
if(Perms.NOCOOK.has(p, current)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, current);
}
}
break;
default:
Block b = p.getTargetBlock(null, 8);
if(!CustomBlocks.isCustomBlock(b))
break;
CustomBlock cb = CustomBlocks.getCustomBlock(b);
switch(cb.getType()) {
case FURNACE:
Log.debug("Is a furnace");
CustomFurnace cf = (CustomFurnace) cb;
if(cf.isFuelSlot((short) rs) && oncur != null) {
for(Short s : cf.getItemSlots()) {
ItemStack item = view.getItem(s);
if(item != null && Perms.NOCOOK.has(p, item)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, item);
break;
}
}
} else if (cf.isItemSlot((short) rs) && oncur != null) {
if(!cf.usesFuel() && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
break;
}
for(Short s : cf.getFuelSlots()) {
if(view.getItem(s) != null && Perms.NOCOOK.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.COOK, oncur);
}
}
}
break;
case WORKBENCH:
CustomWorkbench cw = (CustomWorkbench) cb;
if(cw.isRecipeSlot((short) rs)) {
try {
ModInventoryView miv = (ModInventoryView) view;
Field fcontainer = view.getClass().getDeclaredField("container");
fcontainer.setAccessible(true);
Container container = (Container) fcontainer.get(miv);
InventoryCrafting craftingInv = new InventoryCrafting(container, 3, 3);
craftingInv.resultInventory = new InventoryCraftResult();
for(int i = 0; i <= 8; i++) {
short slot = (Short) cw.getRecipeSlots().toArray()[i];
ItemStack item = slot == rs ? oncur : view.getItem(slot);
if(item == null) continue;
net.minecraft.server.ItemStack stack = new net.minecraft.server.ItemStack(item.getTypeId(), item.getAmount(), item.getDurability());
craftingInv.setItem(i, stack);
}
//TODO: this is probably broken completely. I need to get the NMS World not Bukkit World; This also breaks new builds with Tekkit
net.minecraft.server.ItemStack mcResult = CraftingManager.getInstance().craft(craftingInv, null);
if(mcResult == null) break;
ItemStack result = new ItemStack(mcResult.id, 1, (short) mcResult.getData());
if (Perms.NOCRAFT.has(p, result)) {
event.setCancelled(true);
this.notify(p, EventTypes.CRAFT, result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
default:
Log.severe("Undefined custom block.");
break;
}
break;
}
//NoHold handling
if(event.getSlotType() == SlotType.QUICKBAR
&& oncur != null
&& !event.isCancelled()
&& Perms.NOHOLD.has(p, oncur)) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, oncur);
} else if (event.getSlotType() != SlotType.QUICKBAR
&& event.isShiftClick()
&& !event.isCancelled()
&& current != null
&& Perms.NOHOLD.has(p, current)) {
Inventory binv = view.getBottomInventory();
if(binv instanceof PlayerInventory) {
for(int i = 0; i < 9; i++) {
ItemStack stack = binv.getItem(i);
if(stack != null) {
event.setCancelled(true);
this.notify(p, EventTypes.HOLD, stack);
continue;
}
}
}
}
//NoHave handling
if(current != null && Perms.NOHAVE.has(p, current)) {
this.notify(p, EventTypes.HAVE, current);
p.getInventory().remove(current);
}
}
|
diff --git a/msv/src/com/sun/msv/reader/xmlschema/AnyState.java b/msv/src/com/sun/msv/reader/xmlschema/AnyState.java
index 28dfb512..ebcbd1d1 100644
--- a/msv/src/com/sun/msv/reader/xmlschema/AnyState.java
+++ b/msv/src/com/sun/msv/reader/xmlschema/AnyState.java
@@ -1,118 +1,122 @@
/*
* @(#)$Id$
*
* Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
*
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package com.sun.msv.reader.xmlschema;
import com.sun.msv.grammar.Expression;
import com.sun.msv.grammar.ReferenceExp;
import com.sun.msv.grammar.NameClass;
import com.sun.msv.grammar.NotNameClass;
import com.sun.msv.grammar.NamespaceNameClass;
import com.sun.msv.grammar.ChoiceNameClass;
import com.sun.msv.grammar.AnyNameClass;
import com.sun.msv.grammar.SimpleNameClass;
import com.sun.msv.grammar.DifferenceNameClass;
import com.sun.msv.grammar.xmlschema.ElementDeclExp;
import com.sun.msv.grammar.xmlschema.LaxDefaultNameClass;
import com.sun.msv.grammar.xmlschema.XMLSchemaSchema;
import com.sun.msv.reader.ExpressionWithoutChildState;
import java.util.StringTokenizer;
import java.util.Iterator;
/**
* base implementation of AnyAttributeState and AnyElementState.
*
* @author <a href="mailto:kohsuke.kawaguchi@eng.sun.com">Kohsuke KAWAGUCHI</a>
*/
public abstract class AnyState extends ExpressionWithoutChildState {
protected final Expression makeExpression() {
return createExpression(
startTag.getDefaultedAttribute("namespace","##any"),
startTag.getDefaultedAttribute("processContents","strict") );
}
/**
* creates AGM that corresponds to the specified parameters.
*/
protected abstract Expression createExpression( String namespace, String process );
/**
* processes 'namepsace' attribute and gets corresponding NameClass object.
*/
protected NameClass getNameClass( String namespace, XMLSchemaSchema currentSchema ) {
// we have to get currentSchema through parameter because
// this method is also used while back-patching, and
// reader.currentSchema points to the invalid schema in that case.
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
namespace = namespace.trim();
if( namespace.equals("##any") )
return AnyNameClass.theInstance;
if( namespace.equals("##other") )
- return new NotNameClass( new NamespaceNameClass(currentSchema.targetNamespace) );
+ // ##other means anything other than the target namespace and local.
+ return new NotNameClass(
+ new ChoiceNameClass(
+ new NamespaceNameClass(currentSchema.targetNamespace),
+ new NamespaceNameClass("")) );
NameClass choices=null;
StringTokenizer tokens = new StringTokenizer(namespace);
while( tokens.hasMoreTokens() ) {
String token = tokens.nextToken();
NameClass nc;
if( token.equals("##targetNamespace") )
nc = new NamespaceNameClass(currentSchema.targetNamespace);
else
if( token.equals("##local") )
nc = new NamespaceNameClass("");
else
nc = new NamespaceNameClass(token);
if( choices==null ) choices = nc;
else choices = new ChoiceNameClass(choices,nc);
}
if( choices==null ) {
// no item was found.
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "namespace", namespace );
return AnyNameClass.theInstance;
}
return choices;
}
protected abstract NameClass getNameClassFrom( ReferenceExp exp );
protected NameClass createLaxNameClass( NameClass allowedNc, XMLSchemaReader.RefResolver res ) {
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
LaxDefaultNameClass laxNc = new LaxDefaultNameClass(allowedNc);
Iterator itr = reader.grammar.iterateSchemas();
while( itr.hasNext() ) {
XMLSchemaSchema schema = (XMLSchemaSchema)itr.next();
if(allowedNc.accepts( schema.targetNamespace, NameClass.LOCALNAME_WILDCARD )) {
ReferenceExp[] refs = res.get(schema).getAll();
for( int i=0; i<refs.length; i++ ) {
NameClass name = getNameClassFrom(refs[i]);
if(!(name instanceof SimpleNameClass ))
// assertion failed.
// XML Schema's element declaration is always simple name.
throw new Error();
SimpleNameClass snc = (SimpleNameClass)name;
laxNc.addName(snc.namespaceURI,snc.localName);
}
}
}
// laxNc - names in namespaces that are not allowed.
return new DifferenceNameClass( laxNc, new NotNameClass(allowedNc) );
}
}
| true | true | protected NameClass getNameClass( String namespace, XMLSchemaSchema currentSchema ) {
// we have to get currentSchema through parameter because
// this method is also used while back-patching, and
// reader.currentSchema points to the invalid schema in that case.
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
namespace = namespace.trim();
if( namespace.equals("##any") )
return AnyNameClass.theInstance;
if( namespace.equals("##other") )
return new NotNameClass( new NamespaceNameClass(currentSchema.targetNamespace) );
NameClass choices=null;
StringTokenizer tokens = new StringTokenizer(namespace);
while( tokens.hasMoreTokens() ) {
String token = tokens.nextToken();
NameClass nc;
if( token.equals("##targetNamespace") )
nc = new NamespaceNameClass(currentSchema.targetNamespace);
else
if( token.equals("##local") )
nc = new NamespaceNameClass("");
else
nc = new NamespaceNameClass(token);
if( choices==null ) choices = nc;
else choices = new ChoiceNameClass(choices,nc);
}
if( choices==null ) {
// no item was found.
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "namespace", namespace );
return AnyNameClass.theInstance;
}
return choices;
}
| protected NameClass getNameClass( String namespace, XMLSchemaSchema currentSchema ) {
// we have to get currentSchema through parameter because
// this method is also used while back-patching, and
// reader.currentSchema points to the invalid schema in that case.
final XMLSchemaReader reader = (XMLSchemaReader)this.reader;
namespace = namespace.trim();
if( namespace.equals("##any") )
return AnyNameClass.theInstance;
if( namespace.equals("##other") )
// ##other means anything other than the target namespace and local.
return new NotNameClass(
new ChoiceNameClass(
new NamespaceNameClass(currentSchema.targetNamespace),
new NamespaceNameClass("")) );
NameClass choices=null;
StringTokenizer tokens = new StringTokenizer(namespace);
while( tokens.hasMoreTokens() ) {
String token = tokens.nextToken();
NameClass nc;
if( token.equals("##targetNamespace") )
nc = new NamespaceNameClass(currentSchema.targetNamespace);
else
if( token.equals("##local") )
nc = new NamespaceNameClass("");
else
nc = new NamespaceNameClass(token);
if( choices==null ) choices = nc;
else choices = new ChoiceNameClass(choices,nc);
}
if( choices==null ) {
// no item was found.
reader.reportError( reader.ERR_BAD_ATTRIBUTE_VALUE, "namespace", namespace );
return AnyNameClass.theInstance;
}
return choices;
}
|
diff --git a/src/cz/muni/stanse/CmdLineManager.java b/src/cz/muni/stanse/CmdLineManager.java
index a3456bb..9017f20 100644
--- a/src/cz/muni/stanse/CmdLineManager.java
+++ b/src/cz/muni/stanse/CmdLineManager.java
@@ -1,310 +1,310 @@
package cz.muni.stanse;
import cz.muni.stanse.configuration.Configuration;
import cz.muni.stanse.configuration.CheckerConfiguration;
import cz.muni.stanse.configuration.SourceConfiguration;
import cz.muni.stanse.configuration.source_enumeration.MakefileSourceEnumerator;
import cz.muni.stanse.configuration.source_enumeration.FileListEnumerator;
import cz.muni.stanse.configuration.source_enumeration.BatchFileEnumerator;
import cz.muni.stanse.configuration.source_enumeration
.DirectorySourceEnumerator;
import cz.muni.stanse.utils.Pair;
import java.util.List;
import java.util.Vector;
import java.io.File;
import static java.util.Arrays.asList;
import joptsimple.OptionParser;
import joptsimple.OptionSpec;
import joptsimple.OptionSet;
final class CmdLineManager {
// package-private section
CmdLineManager(final String[] args) {
parser = new OptionParser();
help =
parser.acceptsAll(asList("h", "?", "help"),
"Shows this help message.");
version =
parser.accepts("version","Prints the program version.");
// TODO: following option 'useIntraproceduralAnalysis' switches between
// (iter/intra)procedural analyses. But it does it globaly per all
// the checkers. This should be rewriten to enable swiching these
// options per checker.
useIntraproceduralAnalysis =
parser.accepts("intraprocedural",
"Use simpler intraprocedural analysis instead " +
"of much more complex interprocedural analysis. " +
"Affects all the checkers.");
checkers =
parser.acceptsAll(asList("c", "checker"),
"Checker name and (possibly) configuration. " +
"Can be used multiple times.")
.withRequiredArg()
- .describedAs("name:XMLdatabaseFile:" +
- "outputXMLfile:SortKeyword1:" +
- "SortKeyword2 ...]")
+ .describedAs("name[[:configuration_file1]:" +
+ "configuration_file2:name ...]")
.ofType(String.class);
makefile =
parser.accepts("makefile","Makefile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
makeParams =
parser.accepts("make-params",
"Parameters passed to the make tool.")
.withRequiredArg()
.describedAs("parameters")
.ofType(String.class);
jobfile =
parser.accepts("jobfile","Jobfile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
dir =
parser.accepts("dir","Directory to be (non-recursively) " +
"searched for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
rdir =
parser.accepts("rdir","Directory to be recursively searched " +
"for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
dumpCFG =
parser.accepts("dump-cfg",
"Dump control flow graphs in Dot format");
dumpXML =
parser.accepts("dump-xml",
"Dump XML representation of AST");
dumpCallGraph =
parser.accepts("dump-callgraph",
"Dump callgraph in Dot format");
outputDir =
parser.accepts("output-dir",
"Sets the output directory for generated files")
.withRequiredArg()
.describedAs("directory")
.ofType(File.class);
debugLevel =
parser.acceptsAll(asList("d","debug-level"),
"Sets the debug level")
.withRequiredArg()
.describedAs("n")
.ofType(Integer.class);
gui =
parser.acceptsAll(asList("g", "gui"), "Starts GUI")
.withOptionalArg()
.describedAs("name")
.ofType(String.class);
statsBuild =
parser.accepts("stats-build","Builds statistical data in XML " +
"format of processed checking. " +
"Output file for statistical data " +
"must be provided as an argument")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
statsSort =
parser.accepts("stats-err-sort",
"Loads statistical database file and then it " +
"will sort error messages by lexicografical " +
"order defined by these keywords: " +
"trace_end_desc " +
"(description of error occurence location), " +
"trace_begin_desc " +
"(description of error cause location), "+
"loc_unit " +
"(unit of location), " +
"loc_line " +
"(line number of location), " +
"checker_name " +
"(checker name), " +
"importance " +
"(importance), ")
.withRequiredArg()
- .describedAs("name[[:configuration_file1]:" +
- "configuration_file2:name ...]")
+ .describedAs("XMLdatabaseFile:" +
+ "outputXMLfile:SortKeyword1:" +
+ "SortKeyword2 ...]")
.ofType(String.class);
options = parser.parse(args);
numArgs = args.length;
}
SourceConfiguration getSourceConfiguration() {
if (getOptions().has(makefile))
return new SourceConfiguration(new MakefileSourceEnumerator(
getOptions().valueOf(makefile),
getOptions().has(makeParams) ?
getOptions().valueOf(makeParams) : ""));
if (getOptions().has(jobfile))
return new SourceConfiguration(new BatchFileEnumerator(
getOptions().valueOf(jobfile)));
if (getOptions().has(dir))
return new SourceConfiguration(new DirectorySourceEnumerator(
getOptions().valueOf(dir),"c",false));
if (getOptions().has(rdir))
return new SourceConfiguration(new DirectorySourceEnumerator(
getOptions().valueOf(dir),"c",true));
if (!getOptions().nonOptionArguments().isEmpty())
return new SourceConfiguration(new FileListEnumerator(
getOptions().nonOptionArguments()));
return Configuration.createDefaultSourceConfiguration();
}
List<CheckerConfiguration> getCheckerConfiguration() {
if (!getOptions().has(checkers))
return Configuration.createDefaultCheckerConfiguration();
Vector<CheckerConfiguration> checkerConfiguration =
new Vector<CheckerConfiguration>();
for (final String s: getOptions().valuesOf(checkers)) {
String[] cc = s.split(":");
final String checkerName = cc[0];
final Vector<File> checkerDataFiles = new Vector<File>();
for (int i = 1; i < cc.length; i++)
checkerDataFiles.add(new File(cc[i]));
checkerConfiguration.add(
new CheckerConfiguration(checkerName,checkerDataFiles,
!getOptions().has(useIntraproceduralAnalysis)));
}
return checkerConfiguration;
}
String getOutputDir() {
return getOptions().has(outputDir) ? getOptions().valueOf(outputDir)
.toString() :
null;
}
cz.muni.stanse.props.Properties.VerbosityLevel getVerbosityLevel() {
if (!getOptions().has(debugLevel))
return cz.muni.stanse.props.Properties.VerbosityLevel.LOW;
switch (getOptions().valueOf(debugLevel)) {
case 0:return cz.muni.stanse.props.Properties.VerbosityLevel.SILENT;
case 1:return cz.muni.stanse.props.Properties.VerbosityLevel.LOW;
case 2:return cz.muni.stanse.props.Properties.VerbosityLevel.MIDDLE;
case 3:return cz.muni.stanse.props.Properties.VerbosityLevel.HIGH;
default:
System.err.println("Illegal verbosity level. Falling " +
"back to default - 1");
return cz.muni.stanse.props.Properties.VerbosityLevel.LOW;
}
}
boolean infoMode() {
return numArgs == 0 || getOptions().has(help)
|| getOptions().has(version);
}
void printInfo(final java.io.OutputStream sink) {
if (numArgs == 0 || getOptions().has(help))
try { getParser().printHelpOn(sink); }
catch (final java.io.IOException e) {}
if (getOptions().has(version))
try { new java.io.DataOutputStream(sink).writeChars(
Stanse.class.getPackage().getImplementationVersion());
} catch (final java.io.IOException e) {}
}
boolean dumpAST() {
return getOptions().has(dumpXML);
}
boolean dumpCFG() {
return getOptions().has(dumpCFG);
}
boolean dumpCallGraph() {
return getOptions().has(dumpCallGraph);
}
boolean statsMode() {
return getOptions().has(statsBuild) || getOptions().has(statsSort);
}
String statsBuildFile() {
return (getOptions().has(statsBuild)) ?
getOptions().valueOf(statsBuild) : null;
}
String getStatsDatabase() {
if (!getOptions().has(statsSort))
return null;
String[] cc = getOptions().valueOf(statsSort).split(":");
final String database = cc[0];
return database;
}
String statsOrderingFile() {
if (!getOptions().has(statsSort))
return null;
String[] cc = getOptions().valueOf(statsSort).split(":");
final String orderingFile = cc[1];
return orderingFile;
}
Vector<String> getStatsOrdering() {
if (!getOptions().has(statsSort))
return null;
final Vector<String> ordering = new Vector<String>();
String[] cc = getOptions().valueOf(statsSort).split(":");
for (int i = 2; i < cc.length; i++)
ordering.add(cc[i]);
return ordering;
}
Pair<String,String> getUIdesc() {
if (!getOptions().has(gui))
return Pair.make("TUI","");
String value = getOptions().valueOf(gui);
if (value == null)
value = "default";
return Pair.make("GUI", value);
}
// private section
private OptionSet getOptions() {
return options;
}
private OptionParser getParser() {
return parser;
}
private final OptionParser parser;
private final OptionSpec<Void> help;
private final OptionSpec<Void> version;
private final OptionSpec<Void> useIntraproceduralAnalysis;
private final OptionSpec<String> checkers;
private final OptionSpec<String> makefile;
private final OptionSpec<String> makeParams;
private final OptionSpec<String> jobfile;
private final OptionSpec<String> dir;
private final OptionSpec<String> rdir;
private final OptionSpec<Void> dumpCFG;
private final OptionSpec<Void> dumpXML;
private final OptionSpec<Void> dumpCallGraph;
private final OptionSpec<File> outputDir;
private final OptionSpec<Integer> debugLevel;
private final OptionSpec<String> gui;
private final OptionSpec<String> statsBuild;
private final OptionSpec<String> statsSort;
private final OptionSet options;
private final int numArgs;
}
| false | true | CmdLineManager(final String[] args) {
parser = new OptionParser();
help =
parser.acceptsAll(asList("h", "?", "help"),
"Shows this help message.");
version =
parser.accepts("version","Prints the program version.");
// TODO: following option 'useIntraproceduralAnalysis' switches between
// (iter/intra)procedural analyses. But it does it globaly per all
// the checkers. This should be rewriten to enable swiching these
// options per checker.
useIntraproceduralAnalysis =
parser.accepts("intraprocedural",
"Use simpler intraprocedural analysis instead " +
"of much more complex interprocedural analysis. " +
"Affects all the checkers.");
checkers =
parser.acceptsAll(asList("c", "checker"),
"Checker name and (possibly) configuration. " +
"Can be used multiple times.")
.withRequiredArg()
.describedAs("name:XMLdatabaseFile:" +
"outputXMLfile:SortKeyword1:" +
"SortKeyword2 ...]")
.ofType(String.class);
makefile =
parser.accepts("makefile","Makefile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
makeParams =
parser.accepts("make-params",
"Parameters passed to the make tool.")
.withRequiredArg()
.describedAs("parameters")
.ofType(String.class);
jobfile =
parser.accepts("jobfile","Jobfile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
dir =
parser.accepts("dir","Directory to be (non-recursively) " +
"searched for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
rdir =
parser.accepts("rdir","Directory to be recursively searched " +
"for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
dumpCFG =
parser.accepts("dump-cfg",
"Dump control flow graphs in Dot format");
dumpXML =
parser.accepts("dump-xml",
"Dump XML representation of AST");
dumpCallGraph =
parser.accepts("dump-callgraph",
"Dump callgraph in Dot format");
outputDir =
parser.accepts("output-dir",
"Sets the output directory for generated files")
.withRequiredArg()
.describedAs("directory")
.ofType(File.class);
debugLevel =
parser.acceptsAll(asList("d","debug-level"),
"Sets the debug level")
.withRequiredArg()
.describedAs("n")
.ofType(Integer.class);
gui =
parser.acceptsAll(asList("g", "gui"), "Starts GUI")
.withOptionalArg()
.describedAs("name")
.ofType(String.class);
statsBuild =
parser.accepts("stats-build","Builds statistical data in XML " +
"format of processed checking. " +
"Output file for statistical data " +
"must be provided as an argument")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
statsSort =
parser.accepts("stats-err-sort",
"Loads statistical database file and then it " +
"will sort error messages by lexicografical " +
"order defined by these keywords: " +
"trace_end_desc " +
"(description of error occurence location), " +
"trace_begin_desc " +
"(description of error cause location), "+
"loc_unit " +
"(unit of location), " +
"loc_line " +
"(line number of location), " +
"checker_name " +
"(checker name), " +
"importance " +
"(importance), ")
.withRequiredArg()
.describedAs("name[[:configuration_file1]:" +
"configuration_file2:name ...]")
.ofType(String.class);
options = parser.parse(args);
numArgs = args.length;
}
| CmdLineManager(final String[] args) {
parser = new OptionParser();
help =
parser.acceptsAll(asList("h", "?", "help"),
"Shows this help message.");
version =
parser.accepts("version","Prints the program version.");
// TODO: following option 'useIntraproceduralAnalysis' switches between
// (iter/intra)procedural analyses. But it does it globaly per all
// the checkers. This should be rewriten to enable swiching these
// options per checker.
useIntraproceduralAnalysis =
parser.accepts("intraprocedural",
"Use simpler intraprocedural analysis instead " +
"of much more complex interprocedural analysis. " +
"Affects all the checkers.");
checkers =
parser.acceptsAll(asList("c", "checker"),
"Checker name and (possibly) configuration. " +
"Can be used multiple times.")
.withRequiredArg()
.describedAs("name[[:configuration_file1]:" +
"configuration_file2:name ...]")
.ofType(String.class);
makefile =
parser.accepts("makefile","Makefile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
makeParams =
parser.accepts("make-params",
"Parameters passed to the make tool.")
.withRequiredArg()
.describedAs("parameters")
.ofType(String.class);
jobfile =
parser.accepts("jobfile","Jobfile specifying input files.")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
dir =
parser.accepts("dir","Directory to be (non-recursively) " +
"searched for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
rdir =
parser.accepts("rdir","Directory to be recursively searched " +
"for input files.")
.withRequiredArg()
.describedAs("directory")
.ofType(String.class);
dumpCFG =
parser.accepts("dump-cfg",
"Dump control flow graphs in Dot format");
dumpXML =
parser.accepts("dump-xml",
"Dump XML representation of AST");
dumpCallGraph =
parser.accepts("dump-callgraph",
"Dump callgraph in Dot format");
outputDir =
parser.accepts("output-dir",
"Sets the output directory for generated files")
.withRequiredArg()
.describedAs("directory")
.ofType(File.class);
debugLevel =
parser.acceptsAll(asList("d","debug-level"),
"Sets the debug level")
.withRequiredArg()
.describedAs("n")
.ofType(Integer.class);
gui =
parser.acceptsAll(asList("g", "gui"), "Starts GUI")
.withOptionalArg()
.describedAs("name")
.ofType(String.class);
statsBuild =
parser.accepts("stats-build","Builds statistical data in XML " +
"format of processed checking. " +
"Output file for statistical data " +
"must be provided as an argument")
.withRequiredArg()
.describedAs("file")
.ofType(String.class);
statsSort =
parser.accepts("stats-err-sort",
"Loads statistical database file and then it " +
"will sort error messages by lexicografical " +
"order defined by these keywords: " +
"trace_end_desc " +
"(description of error occurence location), " +
"trace_begin_desc " +
"(description of error cause location), "+
"loc_unit " +
"(unit of location), " +
"loc_line " +
"(line number of location), " +
"checker_name " +
"(checker name), " +
"importance " +
"(importance), ")
.withRequiredArg()
.describedAs("XMLdatabaseFile:" +
"outputXMLfile:SortKeyword1:" +
"SortKeyword2 ...]")
.ofType(String.class);
options = parser.parse(args);
numArgs = args.length;
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/ClassMediatorSerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/ClassMediatorSerializer.java
index 7565281f7..37cf3c390 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/ClassMediatorSerializer.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/ClassMediatorSerializer.java
@@ -1,75 +1,75 @@
/*
* 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.synapse.config.xml;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.synapse.Mediator;
import org.apache.synapse.mediators.ext.ClassMediator;
import java.util.Iterator;
/**
* <pre>
* <class name="class-name">
* <property name="string" (value="literal" | expression="xpath")/>*
* </class>
* </pre>
*/
public class ClassMediatorSerializer extends AbstractMediatorSerializer {
public OMElement serializeSpecificMediator(Mediator m) {
if (!(m instanceof ClassMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
ClassMediator mediator = (ClassMediator) m;
OMElement clazz = fac.createOMElement("class", synNS);
saveTracingState(clazz, mediator);
if (mediator.getMediator() != null && mediator.getMediator().getClass().getName() != null) {
clazz.addAttribute(fac.createOMAttribute(
"name", nullNS, mediator.getMediator().getClass().getName()));
} else {
handleException("Invalid class mediator. The class name is required");
}
Iterator itr = mediator.getProperties().keySet().iterator();
while(itr.hasNext()) {
String propName = (String) itr.next();
Object o = mediator.getProperties().get(propName);
- OMElement prop = fac.createOMElement(PROP_Q);
+ OMElement prop = fac.createOMElement(PROP_Q, clazz);
prop.addAttribute(fac.createOMAttribute("name", nullNS, propName));
if (o instanceof String) {
prop.addAttribute(fac.createOMAttribute("value", nullNS, (String) o));
} else {
prop.addChild((OMNode) o);
}
clazz.addChild(prop);
}
return clazz;
}
public String getMediatorClassName() {
return ClassMediator.class.getName();
}
}
| true | true | public OMElement serializeSpecificMediator(Mediator m) {
if (!(m instanceof ClassMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
ClassMediator mediator = (ClassMediator) m;
OMElement clazz = fac.createOMElement("class", synNS);
saveTracingState(clazz, mediator);
if (mediator.getMediator() != null && mediator.getMediator().getClass().getName() != null) {
clazz.addAttribute(fac.createOMAttribute(
"name", nullNS, mediator.getMediator().getClass().getName()));
} else {
handleException("Invalid class mediator. The class name is required");
}
Iterator itr = mediator.getProperties().keySet().iterator();
while(itr.hasNext()) {
String propName = (String) itr.next();
Object o = mediator.getProperties().get(propName);
OMElement prop = fac.createOMElement(PROP_Q);
prop.addAttribute(fac.createOMAttribute("name", nullNS, propName));
if (o instanceof String) {
prop.addAttribute(fac.createOMAttribute("value", nullNS, (String) o));
} else {
prop.addChild((OMNode) o);
}
clazz.addChild(prop);
}
return clazz;
}
| public OMElement serializeSpecificMediator(Mediator m) {
if (!(m instanceof ClassMediator)) {
handleException("Unsupported mediator passed in for serialization : " + m.getType());
}
ClassMediator mediator = (ClassMediator) m;
OMElement clazz = fac.createOMElement("class", synNS);
saveTracingState(clazz, mediator);
if (mediator.getMediator() != null && mediator.getMediator().getClass().getName() != null) {
clazz.addAttribute(fac.createOMAttribute(
"name", nullNS, mediator.getMediator().getClass().getName()));
} else {
handleException("Invalid class mediator. The class name is required");
}
Iterator itr = mediator.getProperties().keySet().iterator();
while(itr.hasNext()) {
String propName = (String) itr.next();
Object o = mediator.getProperties().get(propName);
OMElement prop = fac.createOMElement(PROP_Q, clazz);
prop.addAttribute(fac.createOMAttribute("name", nullNS, propName));
if (o instanceof String) {
prop.addAttribute(fac.createOMAttribute("value", nullNS, (String) o));
} else {
prop.addChild((OMNode) o);
}
clazz.addChild(prop);
}
return clazz;
}
|
diff --git a/src/com/nijiko/coelho/iConomy/iConomy.java b/src/com/nijiko/coelho/iConomy/iConomy.java
index 18167f8..83e69b9 100644
--- a/src/com/nijiko/coelho/iConomy/iConomy.java
+++ b/src/com/nijiko/coelho/iConomy/iConomy.java
@@ -1,400 +1,400 @@
package com.nijiko.coelho.iConomy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Timer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.Server;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import org.bukkit.event.server.PluginEvent;
import org.bukkit.event.server.ServerListener;
import org.bukkit.plugin.Plugin;
import com.nijiko.coelho.iConomy.entity.Players;
import com.nijiko.coelho.iConomy.net.Database;
import com.nijiko.coelho.iConomy.system.Account;
import com.nijiko.coelho.iConomy.system.Bank;
import com.nijiko.coelho.iConomy.system.Interest;
import com.nijiko.coelho.iConomy.util.Constants;
import com.nijiko.coelho.iConomy.system.Transactions;
import com.nijiko.coelho.iConomy.util.Downloader;
import com.nijiko.coelho.iConomy.util.FileManager;
import com.nijiko.coelho.iConomy.util.Misc;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
import java.sql.Connection;
import java.sql.PreparedStatement;
/**
* iConomy by Team iCo
*
* @copyright Copyright AniGaiku LLC (C) 2010-2011
* @author Nijikokun <nijikokun@gmail.com>
* @author Coelho <robertcoelho@live.com>
* @author ShadowDrakken <shadowdrakken@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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, see <http://www.gnu.org/licenses/>.
*/
public class iConomy extends JavaPlugin {
private static Server Server = null;
private static Bank Bank = null;
private static Database iDatabase = null;
private static Transactions Transactions = null;
private static PermissionHandler Permissions = null;
private static Players playerListener = null;
private static Timer Interest_Timer = null;
@Override
public void onEnable() {
// Get the server
Server = getServer();
// Lib Directory
(new File("lib" + File.separator)).mkdir();
(new File("lib" + File.separator)).setWritable(true);
(new File("lib" + File.separator)).setExecutable(true);
// Plugin Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
Constants.Plugin_Directory = getDataFolder().getPath();
// Grab plugin details
PluginDescriptionFile pdfFile = this.getDescription();
// Versioning File
FileManager file = new FileManager(getDataFolder().getPath(), "VERSION", false);
// Default Files
extractDefaultFile("iConomy.yml");
extractDefaultFile("Messages.yml");
// Configuration
try {
Constants.load(new Configuration(new File(getDataFolder(), "iConomy.yml")));
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to retrieve configuration from directory.");
System.out.println("[iConomy] Please back up your current settings and let iConomy recreate it.");
return;
}
if(Misc.is(Constants.Database_Type, new String[] { "sqlite", "h2", "h2sql" })) {
if(!(new File("lib" + File.separator, "h2.jar").exists())) {
Downloader.install(Constants.H2_Jar_Location, "h2.jar");
}
} else {
if(!(new File("lib" + File.separator, "mysql-connector-java-bin.jar").exists())) {
Downloader.install(Constants.MySQL_Jar_Location, "mysql-connector-java-bin.jar");
}
}
// Load the database
try {
iDatabase = new Database();
} catch (Exception e) {
System.out.println("[iConomy] Failed to connect to database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
// File Logger
try {
Transactions = new Transactions();
Transactions.load();
} catch (Exception e) {
System.out.println("[iConomy] Could not load transaction logger: " + e);
Server.getPluginManager().disablePlugin(this);
}
// Check version details before the system loads
update(file, Double.valueOf(pdfFile.getVersion()));
// Load the bank system
try {
Bank = new Bank();
Bank.load();
} catch (Exception e) {
- System.out.println("[iConomy] Failed to load accounts from database: " + e);
+ System.out.println("[iConomy] Failed to load database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
try {
if (Constants.Interest) {
Interest_Timer = new Timer();
Interest_Timer.scheduleAtFixedRate(new Interest(),
Constants.Interest_Interval * 1000L, Constants.Interest_Interval * 1000L);
}
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to start interest system: " + e);
return;
}
// Initializing Listeners
playerListener = new Players(getDataFolder().getPath());
// Event Registration
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new Listener(this), Priority.Monitor, this);
// Console Detail
System.out.println("[iConomy] v" + pdfFile.getVersion() + " (" + Constants.Codename + ") loaded.");
System.out.println("[iConomy] Developed by: " + pdfFile.getAuthors());
}
@Override
public void onDisable() {
try {
System.out.println("[iConomy] Plugin disabled.");
} catch (Exception e) {
System.out.println("[iConomy] An error occured upon disabling: " + e);
} finally {
if (Interest_Timer != null) {
Interest_Timer.cancel();
}
Server = null;
Bank = null;
iDatabase = null;
Permissions = null;
Transactions = null;
playerListener = null;
Interest_Timer = null;
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
try {
String[] split = new String[args.length + 1];
split[0] = cmd.getName().toLowerCase();
for (int i = 0; i < args.length; i++) {
split[i + 1] = args[i];
}
playerListener.onPlayerCommand(sender, split);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
private void update(FileManager file, double version) {
if (file.exists()) {
file.read();
try {
double current = Double.parseDouble(file.getSource());
if(current != version) {
file.write(version);
}
} catch (Exception e) {
System.out.println("[iConomy] Invalid version file, deleting to be re-created on next load.");
file.delete();
}
} else {
if (!Constants.Database_Type.equalsIgnoreCase("flatfile")) {
String[] SQL = {};
String[] MySQL = {
"DROP TABLE " + Constants.SQL_Table + ";",
"RENAME TABLE ibalances TO " + Constants.SQL_Table + ";",
"ALTER TABLE " + Constants.SQL_Table + " CHANGE player username TEXT NOT NULL, CHANGE balance balance DECIMAL(65, 2) NOT NULL;"
};
String[] SQLite = {
"DROP TABLE " + Constants.SQL_Table + ";",
"CREATE TABLE '" + Constants.SQL_Table + "' ('id' INT ( 10 ) PRIMARY KEY , 'username' TEXT , 'balance' DECIMAL ( 65 , 2 ));",
"INSERT INTO " + Constants.SQL_Table + "(id, username, balance) SELECT id, player, balance FROM ibalances;",
"DROP TABLE ibalances;"
};
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
conn = iConomy.getDatabase().checkOut();
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "ibalances", null);
ps = null;
if (rs.next()) {
System.out.println(" - Updating " + Constants.Database_Type + " Database for latest iConomy");
int i = 1;
SQL = (Constants.Database_Type.equalsIgnoreCase("mysql")) ? MySQL : SQLite;
for (String Query : SQL) {
ps = conn.prepareStatement(Query);
ps.executeQuery(Query);
System.out.println(" Executing SQL Query #" + i + " of " + (SQL.length));
++i;
}
System.out.println(" + Database Update Complete.");
}
file.write(version);
} catch (SQLException e) {
System.out.println("[iConomy] Error updating database: " + e);
} finally {
if(ps != null)
try { ps.close(); } catch (SQLException ex) { }
if(rs != null)
try { rs.close(); } catch (SQLException ex) { }
if(conn != null)
iConomy.getDatabase().checkIn(conn);
}
}
file.create();
file.write(version);
}
}
private void extractDefaultFile(String name) {
File actual = new File(getDataFolder(), name);
if (!actual.exists()) {
InputStream input = this.getClass().getResourceAsStream("/default/" + name);
if (input != null) {
FileOutputStream output = null;
try {
output = new FileOutputStream(actual);
byte[] buf = new byte[8192];
int length = 0;
while ((length = input.read(buf)) > 0) {
output.write(buf, 0, length);
}
System.out.println("[iConomy] Default setup file written: " + name);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) { }
try {
if (output != null) {
output.close();
}
} catch (Exception e) { }
}
}
}
}
/**
* Grab the bank to modify and access bank accounts.
*
* @return Bank
*/
public static Bank getBank() {
return Bank;
}
/**
* Grabs Database controller.
*
* @return iDatabase
*/
public static Database getDatabase() {
return iDatabase;
}
/**
* Grabs Transaction Log Controller.
*
* Used to log transactions between a player and anything. Such as the
* system or another player or just enviroment.
*
* @return T
*/
public static Transactions getTransactions() {
return Transactions;
}
public static PermissionHandler getPermissions() {
return Permissions;
}
public static boolean hasPermissions(CommandSender sender, String node) {
if(sender instanceof Player) {
Player player = (Player)sender;
if(Permissions != null)
return Permissions.permission(player, node);
else {
return player.isOp();
}
}
return true;
}
public static void setPermissions(PermissionHandler ph) {
Permissions = ph;
}
public static Server getBukkitServer() {
return Server;
}
private class Listener extends ServerListener {
private iConomy plugin;
public Listener(iConomy thisPlugin) {
this.plugin = thisPlugin;
}
@Override
public void onPluginEnabled(PluginEvent event) {
if (plugin.Permissions == null) {
Plugin Permissions = plugin.getServer().getPluginManager().getPlugin("Permissions");
if (Permissions != null) {
if (Permissions.isEnabled()) {
plugin.Permissions = (((Permissions)Permissions).getHandler());
System.out.println("[iConomy] hooked into Permissions.");
}
}
}
}
}
}
| true | true | public void onEnable() {
// Get the server
Server = getServer();
// Lib Directory
(new File("lib" + File.separator)).mkdir();
(new File("lib" + File.separator)).setWritable(true);
(new File("lib" + File.separator)).setExecutable(true);
// Plugin Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
Constants.Plugin_Directory = getDataFolder().getPath();
// Grab plugin details
PluginDescriptionFile pdfFile = this.getDescription();
// Versioning File
FileManager file = new FileManager(getDataFolder().getPath(), "VERSION", false);
// Default Files
extractDefaultFile("iConomy.yml");
extractDefaultFile("Messages.yml");
// Configuration
try {
Constants.load(new Configuration(new File(getDataFolder(), "iConomy.yml")));
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to retrieve configuration from directory.");
System.out.println("[iConomy] Please back up your current settings and let iConomy recreate it.");
return;
}
if(Misc.is(Constants.Database_Type, new String[] { "sqlite", "h2", "h2sql" })) {
if(!(new File("lib" + File.separator, "h2.jar").exists())) {
Downloader.install(Constants.H2_Jar_Location, "h2.jar");
}
} else {
if(!(new File("lib" + File.separator, "mysql-connector-java-bin.jar").exists())) {
Downloader.install(Constants.MySQL_Jar_Location, "mysql-connector-java-bin.jar");
}
}
// Load the database
try {
iDatabase = new Database();
} catch (Exception e) {
System.out.println("[iConomy] Failed to connect to database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
// File Logger
try {
Transactions = new Transactions();
Transactions.load();
} catch (Exception e) {
System.out.println("[iConomy] Could not load transaction logger: " + e);
Server.getPluginManager().disablePlugin(this);
}
// Check version details before the system loads
update(file, Double.valueOf(pdfFile.getVersion()));
// Load the bank system
try {
Bank = new Bank();
Bank.load();
} catch (Exception e) {
System.out.println("[iConomy] Failed to load accounts from database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
try {
if (Constants.Interest) {
Interest_Timer = new Timer();
Interest_Timer.scheduleAtFixedRate(new Interest(),
Constants.Interest_Interval * 1000L, Constants.Interest_Interval * 1000L);
}
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to start interest system: " + e);
return;
}
// Initializing Listeners
playerListener = new Players(getDataFolder().getPath());
// Event Registration
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new Listener(this), Priority.Monitor, this);
// Console Detail
System.out.println("[iConomy] v" + pdfFile.getVersion() + " (" + Constants.Codename + ") loaded.");
System.out.println("[iConomy] Developed by: " + pdfFile.getAuthors());
}
| public void onEnable() {
// Get the server
Server = getServer();
// Lib Directory
(new File("lib" + File.separator)).mkdir();
(new File("lib" + File.separator)).setWritable(true);
(new File("lib" + File.separator)).setExecutable(true);
// Plugin Directory
getDataFolder().mkdir();
getDataFolder().setWritable(true);
getDataFolder().setExecutable(true);
Constants.Plugin_Directory = getDataFolder().getPath();
// Grab plugin details
PluginDescriptionFile pdfFile = this.getDescription();
// Versioning File
FileManager file = new FileManager(getDataFolder().getPath(), "VERSION", false);
// Default Files
extractDefaultFile("iConomy.yml");
extractDefaultFile("Messages.yml");
// Configuration
try {
Constants.load(new Configuration(new File(getDataFolder(), "iConomy.yml")));
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to retrieve configuration from directory.");
System.out.println("[iConomy] Please back up your current settings and let iConomy recreate it.");
return;
}
if(Misc.is(Constants.Database_Type, new String[] { "sqlite", "h2", "h2sql" })) {
if(!(new File("lib" + File.separator, "h2.jar").exists())) {
Downloader.install(Constants.H2_Jar_Location, "h2.jar");
}
} else {
if(!(new File("lib" + File.separator, "mysql-connector-java-bin.jar").exists())) {
Downloader.install(Constants.MySQL_Jar_Location, "mysql-connector-java-bin.jar");
}
}
// Load the database
try {
iDatabase = new Database();
} catch (Exception e) {
System.out.println("[iConomy] Failed to connect to database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
// File Logger
try {
Transactions = new Transactions();
Transactions.load();
} catch (Exception e) {
System.out.println("[iConomy] Could not load transaction logger: " + e);
Server.getPluginManager().disablePlugin(this);
}
// Check version details before the system loads
update(file, Double.valueOf(pdfFile.getVersion()));
// Load the bank system
try {
Bank = new Bank();
Bank.load();
} catch (Exception e) {
System.out.println("[iConomy] Failed to load database: " + e);
Server.getPluginManager().disablePlugin(this);
return;
}
try {
if (Constants.Interest) {
Interest_Timer = new Timer();
Interest_Timer.scheduleAtFixedRate(new Interest(),
Constants.Interest_Interval * 1000L, Constants.Interest_Interval * 1000L);
}
} catch (Exception e) {
Server.getPluginManager().disablePlugin(this);
System.out.println("[iConomy] Failed to start interest system: " + e);
return;
}
// Initializing Listeners
playerListener = new Players(getDataFolder().getPath());
// Event Registration
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLUGIN_ENABLE, new Listener(this), Priority.Monitor, this);
// Console Detail
System.out.println("[iConomy] v" + pdfFile.getVersion() + " (" + Constants.Codename + ") loaded.");
System.out.println("[iConomy] Developed by: " + pdfFile.getAuthors());
}
|
diff --git a/kernel/src/main/java/org/vosao/update/UpdateManager.java b/kernel/src/main/java/org/vosao/update/UpdateManager.java
index 5d2f331..4eedddb 100644
--- a/kernel/src/main/java/org/vosao/update/UpdateManager.java
+++ b/kernel/src/main/java/org/vosao/update/UpdateManager.java
@@ -1,79 +1,78 @@
/**
* Vosao CMS. Simple CMS for Google App Engine.
* Copyright (C) 2009 Vosao development 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 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.
*
* email: vosao.dev@gmail.com
*/
package org.vosao.update;
import java.util.ArrayList;
import java.util.List;
import org.vosao.dao.Dao;
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.Query;
/**
* @author Alexander Oleynik
*/
public class UpdateManager {
private List<UpdateTask> tasks;
private DatastoreService datastore;
private Dao dao;
public UpdateManager(Dao aDao) {
dao = aDao;
datastore = DatastoreServiceFactory.getDatastoreService();
tasks = new ArrayList<UpdateTask>();
tasks.add(new UpdateTask003());
tasks.add(new UpdateTask004(dao));
tasks.add(new UpdateTask01(dao));
}
public void update() throws UpdateException {
- Entity config = getConfig();
- if (config.getProperty("version") == null) {
+ if (getConfig().getProperty("version") == null) {
addConfigVersion();
}
- config = getConfig();
for (UpdateTask task : tasks) {
- if (config.getProperty("version").equals(task.getFromVersion())) {
+ if (getConfig().getProperty("version").equals(task.getFromVersion())) {
task.update();
+ Entity config = getConfig();
config.setProperty("version", task.getToVersion());
datastore.put(config);
}
}
}
private Entity getConfig() {
Query query = new Query("ConfigEntity");
return datastore.prepare(query).asIterator().next();
}
private void addConfigVersion() {
Entity config = getConfig();
config.setProperty("version", "0.0.2");
config.setProperty("enableRecaptcha", false);
datastore.put(config);
}
}
| false | true | public void update() throws UpdateException {
Entity config = getConfig();
if (config.getProperty("version") == null) {
addConfigVersion();
}
config = getConfig();
for (UpdateTask task : tasks) {
if (config.getProperty("version").equals(task.getFromVersion())) {
task.update();
config.setProperty("version", task.getToVersion());
datastore.put(config);
}
}
}
| public void update() throws UpdateException {
if (getConfig().getProperty("version") == null) {
addConfigVersion();
}
for (UpdateTask task : tasks) {
if (getConfig().getProperty("version").equals(task.getFromVersion())) {
task.update();
Entity config = getConfig();
config.setProperty("version", task.getToVersion());
datastore.put(config);
}
}
}
|
diff --git a/ch.deif.meander/src/ch/deif/meander/map/ComputeConfigurationTask.java b/ch.deif.meander/src/ch/deif/meander/map/ComputeConfigurationTask.java
index 56362eef..7d6d266b 100644
--- a/ch.deif.meander/src/ch/deif/meander/map/ComputeConfigurationTask.java
+++ b/ch.deif.meander/src/ch/deif/meander/map/ComputeConfigurationTask.java
@@ -1,33 +1,33 @@
package ch.deif.meander.map;
import ch.akuhn.hapax.index.LatentSemanticIndex;
import ch.akuhn.util.ProgressMonitor;
import ch.akuhn.values.Arguments;
import ch.akuhn.values.TaskValue;
import ch.akuhn.values.Value;
import ch.deif.meander.Configuration;
import ch.deif.meander.builder.Meander;
public class ComputeConfigurationTask extends TaskValue<Configuration> {
public Configuration previousConfiguration;
public ComputeConfigurationTask(Value<LatentSemanticIndex> index) {
- super("Multidimensional scaling...", index);
+ super("Computing map layout...", index);
this.previousConfiguration = new Configuration();
}
@Override
protected Configuration computeValue(ProgressMonitor monitor, Arguments args) {
LatentSemanticIndex index = args.nextOrFail();
return previousConfiguration = Meander.builder().addCorpus(index).makeMap(previousConfiguration);
}
public ComputeConfigurationTask initialConfiguration(Configuration configuration) {
this.previousConfiguration = configuration;
return this;
}
}
| true | true | public ComputeConfigurationTask(Value<LatentSemanticIndex> index) {
super("Multidimensional scaling...", index);
this.previousConfiguration = new Configuration();
}
| public ComputeConfigurationTask(Value<LatentSemanticIndex> index) {
super("Computing map layout...", index);
this.previousConfiguration = new Configuration();
}
|
diff --git a/src/com/earlofmarch/reach/input/BuzzerBindingFactory.java b/src/com/earlofmarch/reach/input/BuzzerBindingFactory.java
index e2edc9e..7989644 100644
--- a/src/com/earlofmarch/reach/input/BuzzerBindingFactory.java
+++ b/src/com/earlofmarch/reach/input/BuzzerBindingFactory.java
@@ -1,90 +1,90 @@
package com.earlofmarch.reach.input;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.*;
/**
* Return a {@link BuzzerBinding} appropriate to the system.
* @author Ian Dewan
*/
public class BuzzerBindingFactory {
private static Logger log;
static {
log = Logger.getLogger("reach.input");
log.setLevel(Level.ALL);
log.addHandler(new ConsoleHandler());
}
/**
* Return a {@link BuzzerBinding} appropriate to the system.
* @return The BuzzerBinding
* @throws IOException Something goes horribly wrong.
*/
public static BuzzerBinding getBinding() throws IOException {
log.log(Level.INFO, "Entering BuzzerBindingFactory.getBinding()");
if (System.getProperty("os.name").contains("Windows")) {
return windows();
} else { // assume Linux
//TODO
return null;
}
}
private static WindowsBuzzerBinding windows() throws IOException {
Process server = null;
log.log(Level.INFO, "Entering BuzzerBindingFactory.windows()");
try {
server = Runtime.getRuntime().exec("./glue.exe");
} catch (IOException e) {
log.log(Level.SEVERE, "Error creating glue.exe", e);
throw e;
}
new Thread(new ErrorEater(server.getErrorStream())).start();
- Runtime.addShutdownHook(new Thread(new Destroyer(server)));
+ Runtime.getRuntime().addShutdownHook(new Thread(new Destroyer(server)));
return new WindowsBuzzerBinding(server.getInputStream(),
server.getOutputStream());
}
/**
* Dispose of the stderr stream to keep the Windows process running.
*/
private static class ErrorEater implements Runnable {
private InputStreamReader src;
public ErrorEater(InputStream s) {
src = new InputStreamReader(s);
}
@Override
public void run() {
char buf;
while (true) {
try {
buf = (char) src.read();
} catch (IOException e) {
log.log(Level.WARNING, "Error reading glue.exe stderr", e);
return;
}
System.err.print(buf);
}
}
}
private static class Destroyer implements Runnable {
private Process p;
public Destroyer(Process p) {
this.p = p;
}
public void run() {
p.destroy();
}
}
}
| true | true | private static WindowsBuzzerBinding windows() throws IOException {
Process server = null;
log.log(Level.INFO, "Entering BuzzerBindingFactory.windows()");
try {
server = Runtime.getRuntime().exec("./glue.exe");
} catch (IOException e) {
log.log(Level.SEVERE, "Error creating glue.exe", e);
throw e;
}
new Thread(new ErrorEater(server.getErrorStream())).start();
Runtime.addShutdownHook(new Thread(new Destroyer(server)));
return new WindowsBuzzerBinding(server.getInputStream(),
server.getOutputStream());
}
| private static WindowsBuzzerBinding windows() throws IOException {
Process server = null;
log.log(Level.INFO, "Entering BuzzerBindingFactory.windows()");
try {
server = Runtime.getRuntime().exec("./glue.exe");
} catch (IOException e) {
log.log(Level.SEVERE, "Error creating glue.exe", e);
throw e;
}
new Thread(new ErrorEater(server.getErrorStream())).start();
Runtime.getRuntime().addShutdownHook(new Thread(new Destroyer(server)));
return new WindowsBuzzerBinding(server.getInputStream(),
server.getOutputStream());
}
|
diff --git a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
index 2eb6244..66455c1 100644
--- a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
+++ b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
@@ -1,244 +1,244 @@
package com.github.soniex2.endermoney.trading.tileentity;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import com.github.soniex2.endermoney.core.EnderCoin;
import com.github.soniex2.endermoney.core.EnderMoney;
import com.github.soniex2.endermoney.trading.TradeException;
import com.github.soniex2.endermoney.trading.base.AbstractTraderTileEntity;
import com.github.soniex2.endermoney.trading.helper.item.ItemStackMapKey;
public class TileEntityCreativeItemTrader extends AbstractTraderTileEntity {
public TileEntityCreativeItemTrader() {
super(18);
}
public ItemStack[] getTradeInputs() {
ItemStack[] tradeInputs = new ItemStack[9];
for (int i = 0; i < 9; i++) {
tradeInputs[i] = ItemStack.copyItemStack(inv[i]);
}
return tradeInputs;
}
public ItemStack[] getTradeOutputs() {
ItemStack[] tradeOutputs = new ItemStack[9];
for (int i = 0; i < 9; i++) {
tradeOutputs[i] = ItemStack.copyItemStack(inv[i + 9]);
}
return tradeOutputs;
}
public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeException {
if (fakeInv == null) { throw new TradeException(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
} else if (!newMoney.equals(BigInteger.ZERO)) {
ItemStack is = ((EnderCoin) EnderMoney.coin).getItemStack(newMoney.longValue(), 1);
ItemStackMapKey index = new ItemStackMapKey(is);
newInput.put(index, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeException(0, "Couldn't complete trade: Out of inventory space");
}
}
- for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) {
+ for (int _i = inputMinSlot; _i <= inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
- if (slot >= inputMaxSlot) { throw new TradeException(0,
+ if (slot > inputMaxSlot) { throw new TradeException(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
@Override
public String getInvName() {
return "endermoney.traders.item";
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public void openChest() {
}
@Override
public void closeChest() {
}
}
| false | true | public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeException {
if (fakeInv == null) { throw new TradeException(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
} else if (!newMoney.equals(BigInteger.ZERO)) {
ItemStack is = ((EnderCoin) EnderMoney.coin).getItemStack(newMoney.longValue(), 1);
ItemStackMapKey index = new ItemStackMapKey(is);
newInput.put(index, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeException(0, "Couldn't complete trade: Out of inventory space");
}
}
for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
if (slot >= inputMaxSlot) { throw new TradeException(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
| public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeException {
if (fakeInv == null) { throw new TradeException(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
} else if (!newMoney.equals(BigInteger.ZERO)) {
ItemStack is = ((EnderCoin) EnderMoney.coin).getItemStack(newMoney.longValue(), 1);
ItemStackMapKey index = new ItemStackMapKey(is);
newInput.put(index, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeException(0, "Couldn't complete trade: Out of inventory space");
}
}
for (int _i = inputMinSlot; _i <= inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
if (slot > inputMaxSlot) { throw new TradeException(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
|
diff --git a/src/main/java/ro/lmn/mantis/mpm/internal/HandleImpl.java b/src/main/java/ro/lmn/mantis/mpm/internal/HandleImpl.java
index d548b1f..aaf451b 100644
--- a/src/main/java/ro/lmn/mantis/mpm/internal/HandleImpl.java
+++ b/src/main/java/ro/lmn/mantis/mpm/internal/HandleImpl.java
@@ -1,291 +1,291 @@
package ro.lmn.mantis.mpm.internal;
import static com.google.common.base.Objects.equal;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Arrays.asList;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import biz.futureware.mantis.rpc.soap.client.AccountData;
import biz.futureware.mantis.rpc.soap.client.AttachmentData;
import biz.futureware.mantis.rpc.soap.client.IssueData;
import biz.futureware.mantis.rpc.soap.client.IssueNoteData;
import biz.futureware.mantis.rpc.soap.client.MantisConnectPortType;
import biz.futureware.mantis.rpc.soap.client.ObjectRef;
import biz.futureware.mantis.rpc.soap.client.ProjectData;
import biz.futureware.mantis.rpc.soap.client.ProjectVersionData;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
public class HandleImpl implements Handle {
private static final Logger LOGGER = LoggerFactory.getLogger(HandleImpl.class);
private final MantisConnectPortType mantisConnectPort;
private final String username;
private final String password;
private final BigInteger projectId;
public HandleImpl(MantisConnectPortType mantisConnectPort, String username, String password, int targetProjectId) throws Exception {
this.mantisConnectPort = mantisConnectPort;
this.username = username;
this.password = password;
this.projectId = BigInteger.valueOf(targetProjectId);
for ( ProjectData project : mantisConnectPort.mc_projects_get_user_accessible(username, password) )
if ( project.getId().equals(projectId) )
return;
else for ( ProjectData subProject : project.getSubprojects() )
if ( subProject.getId().equals(projectId) )
return;
throw new IllegalArgumentException("User " + username + " does not have access to project with id " + targetProjectId + " on " + mantisConnectPort);
}
@Override
public List<ProjectVersionData> getVersions() throws Exception {
return Arrays.asList(mantisConnectPort.mc_project_get_versions(username, password, projectId));
}
@Override
public void synchronizeVersions(List<ProjectVersionData> newVersions) throws Exception {
LOGGER.info("Synchronizing versions");
Map<String, ProjectVersionData> ourVersionsMap = Maps.newHashMap();
for( ProjectVersionData ourVersion : getVersions() )
ourVersionsMap.put(ourVersion.getName(), ourVersion);
for( ProjectVersionData newVersion : newVersions ) {
ProjectVersionData toCreate = new ProjectVersionData(null, newVersion.getName(), projectId,
newVersion.getDate_order(), newVersion.getDescription(), newVersion.getReleased(), newVersion.getObsolete());
newVersion.setProject_id(projectId);
normalizeDescription(newVersion);
ProjectVersionData ourVersion = ourVersionsMap.get(toCreate.getName());
if ( ourVersion == null ) {
LOGGER.info("Creating new version with name {} ", toCreate.getName());
mantisConnectPort.mc_project_version_add(username, password, newVersion);
} else {
normalizeDescription(ourVersion);
if ( !versionEq(ourVersion, newVersion)) {
LOGGER.info("Updating existing version with name {}", toCreate.getName());
mantisConnectPort.mc_project_version_update(username, password, ourVersion.getId(), toCreate);
} else {
LOGGER.info("Version with name {} already exists and is identical, skipping.", toCreate.getName());
}
}
}
LOGGER.info("Synchronized versions");
}
@Override
public List<String> getCategories() throws Exception {
return asList(mantisConnectPort.mc_project_get_categories(username, password, projectId));
}
@Override
public void synchronizeCategories(List<String> newCategories) throws Exception {
LOGGER.info("Synchronizing categories");
List<String> ourCategories = getCategories();
for ( String newCategory : newCategories ) {
if ( !ourCategories.contains(newCategory) ) {
LOGGER.info("Creating new category {}.", newCategory);
mantisConnectPort.mc_project_add_category(username, password, projectId, newCategory);
} else {
LOGGER.info("Category with name {} already exists, skipping.", newCategory);
}
}
LOGGER.info("Synchronized categories");
}
@Override
public List<IssueData> getIssues(int filterId) throws Exception {
LOGGER.info("Reading issues for project {}, filter {}", projectId, filterId);
BigInteger perPage = BigInteger.valueOf(50);
BigInteger currentPage= BigInteger.ONE;
List<IssueData> allIssues = new ArrayList<>();
while ( true ) {
IssueData[] issues = mantisConnectPort.mc_filter_get_issues(username, password, projectId, BigInteger.valueOf(filterId), currentPage, perPage);
allIssues.addAll(Arrays.asList(issues));
currentPage = currentPage.add(BigInteger.ONE);
LOGGER.info("Read {} issues", allIssues.size());
if ( issues.length != perPage.intValue() )
break;
}
LOGGER.info("Finished reading issues");
return allIssues;
}
@Override
public List<AccountData> getUsers() throws Exception {
return Arrays.asList(mantisConnectPort.mc_project_get_users(username, password, projectId, BigInteger.ZERO /* all users */));
}
@Override
public void synchronizeIssues(int filterId, List<IssueData> newIssues, String oldIssueTrackerUrl, Handle sourceHandle) throws Exception {
Map<String, AccountData> ourUsers = new HashMap<>();
for ( AccountData ourUser : getUsers() )
ourUsers.put(ourUser.getName(), ourUser);
AccountData thisUser = checkNotNull(ourUsers.get(username));
Map<String, IssueData> ourIssues = new HashMap<>();
for( IssueData ourIssue : getIssues(filterId))
ourIssues.put(ourIssue.getSummary(), ourIssue); // TODO use a compound issue key
for ( IssueData newIssue : newIssues ) {
if ( ourIssues.containsKey(newIssue.getSummary())) {
LOGGER.info("For issue to import with id {} found issue with id {} and same name {}. Skipping", newIssue.getId(), ourIssues.get(newIssue.getSummary()), newIssue.getSummary());
} else {
IssueData toCreate = new IssueData();
toCreate.setAdditional_information(newIssue.getAdditional_information());
toCreate.setBuild(newIssue.getBuild());
toCreate.setCategory(newIssue.getCategory());
toCreate.setDate_submitted(newIssue.getDate_submitted());
toCreate.setDescription(newIssue.getDescription());
toCreate.setDue_date(newIssue.getDue_date());
toCreate.setEta(newIssue.getEta());
toCreate.setFixed_in_version(newIssue.getFixed_in_version());
toCreate.setLast_updated(newIssue.getLast_updated());
toCreate.setOs(newIssue.getOs());
toCreate.setOs_build(newIssue.getOs_build());
toCreate.setPlatform(newIssue.getPlatform());
toCreate.setPriority(newIssue.getPriority());
toCreate.setProject(new ObjectRef(projectId, null));
toCreate.setProjection(newIssue.getProjection());
toCreate.setReproducibility(newIssue.getReproducibility());
toCreate.setResolution(newIssue.getResolution());
toCreate.setSeverity(newIssue.getSeverity());
toCreate.setStatus(newIssue.getStatus());
toCreate.setSteps_to_reproduce(newIssue.getSteps_to_reproduce());
toCreate.setSticky(newIssue.getSticky());
toCreate.setSummary(newIssue.getSummary());
toCreate.setTarget_version(newIssue.getTarget_version());
toCreate.setVersion(newIssue.getVersion());
toCreate.setView_state(newIssue.getView_state());
if ( newIssue.getReporter() != null )
toCreate.setReporter(getAccountDataByName(ourUsers, newIssue.getReporter().getName(), thisUser));
if ( newIssue.getHandler() != null )
toCreate.setHandler(getAccountDataByName(ourUsers, newIssue.getHandler().getName(), null));
List<IssueNoteData> notes = new ArrayList<>();
if ( newIssue.getNotes() != null ) {
for ( IssueNoteData newNote : newIssue.getNotes() ) {
AccountData noteAuthor = getAccountDataByName(ourUsers, newNote.getReporter().getName(), thisUser);
String text = "";
if ( !accountEq(noteAuthor, newNote.getReporter()) )
text = "Original note author: " + newNote.getReporter().getName()+ "\n\n";
text += newNote.getText();
notes.add(new IssueNoteData(null, noteAuthor, text, newNote.getView_state(),
newNote.getDate_submitted(), newNote.getLast_modified(), newNote.getTime_tracking(),
newNote.getNote_type(), newNote.getNote_attr()));
}
}
StringBuilder additionalNoteText = new StringBuilder();
additionalNoteText.append("Originally reported at ").append(oldIssueTrackerUrl)
.append("/view.php?id=").append(newIssue.getId() );
if ( ! accountEq(newIssue.getReporter(), toCreate.getReporter()));
additionalNoteText.append(" by ").append(newIssue.getReporter().getName());
if ( ! accountEq(newIssue.getHandler(), toCreate.getHandler()) )
additionalNoteText.append(", handled by ").append(newIssue.getHandler().getName());
IssueNoteData importNote = new IssueNoteData();
importNote.setReporter(thisUser);
importNote.setText(additionalNoteText.toString());
notes.add(importNote);
toCreate.setNotes(notes.toArray(new IssueNoteData[notes.size()]));
// TODO - tags
// TODO - relationships
// TODO - monitors ?
LOGGER.info("Importing issue {}. [{}] {}", newIssue.getId(), newIssue.getCategory(), newIssue.getSummary());
BigInteger createdIssueId = mantisConnectPort.mc_issue_add(username, password, toCreate);
- if ( newIssue.getAttachments() != null ) {
+ if ( newIssue.getAttachments() != null && newIssue.getAttachments().length > 0) {
LOGGER.info("Importing {} attachments for issue {}", newIssue.getAttachments().length, newIssue.getId());
for ( AttachmentData attachment : newIssue.getAttachments() ) {
byte[] attachmentData = sourceHandle.getIssueAttachment(attachment.getId().intValue());
mantisConnectPort.mc_issue_attachment_add(username, password, createdIssueId, attachment.getFilename(), attachment.getContent_type(), attachmentData);
}
}
}
}
}
@Override
public byte[] getIssueAttachment(int attachmentId) throws Exception {
return mantisConnectPort.mc_issue_attachment_get(username, password, BigInteger.valueOf(attachmentId));
}
private static AccountData getAccountDataByName(Map<String, AccountData> accounts, String name, AccountData defaultValue) {
AccountData toReturn = accounts.get(name);
if ( toReturn == null )
toReturn = defaultValue;
return toReturn;
}
private static void normalizeDescription(ProjectVersionData version) {
if ( version.getDescription() == null )
version.setDescription("");
}
private static boolean versionEq(ProjectVersionData ourVersion, ProjectVersionData newVersion) {
return equal(ourVersion.getName(), newVersion.getName()) && equal(ourVersion.getDate_order(), newVersion.getDate_order()) &&
equal(ourVersion.getDescription(), newVersion.getDescription()) && equal(ourVersion.getObsolete(), newVersion.getObsolete()) &&
equal(ourVersion.getReleased(), newVersion.getReleased());
}
private static boolean accountEq(AccountData first, AccountData second) {
if ( first == null && second == null )
return true;
if ( first == null ^ second == null )
return false;
return Objects.equal(first.getName(), second.getName());
}
}
| true | true | public void synchronizeIssues(int filterId, List<IssueData> newIssues, String oldIssueTrackerUrl, Handle sourceHandle) throws Exception {
Map<String, AccountData> ourUsers = new HashMap<>();
for ( AccountData ourUser : getUsers() )
ourUsers.put(ourUser.getName(), ourUser);
AccountData thisUser = checkNotNull(ourUsers.get(username));
Map<String, IssueData> ourIssues = new HashMap<>();
for( IssueData ourIssue : getIssues(filterId))
ourIssues.put(ourIssue.getSummary(), ourIssue); // TODO use a compound issue key
for ( IssueData newIssue : newIssues ) {
if ( ourIssues.containsKey(newIssue.getSummary())) {
LOGGER.info("For issue to import with id {} found issue with id {} and same name {}. Skipping", newIssue.getId(), ourIssues.get(newIssue.getSummary()), newIssue.getSummary());
} else {
IssueData toCreate = new IssueData();
toCreate.setAdditional_information(newIssue.getAdditional_information());
toCreate.setBuild(newIssue.getBuild());
toCreate.setCategory(newIssue.getCategory());
toCreate.setDate_submitted(newIssue.getDate_submitted());
toCreate.setDescription(newIssue.getDescription());
toCreate.setDue_date(newIssue.getDue_date());
toCreate.setEta(newIssue.getEta());
toCreate.setFixed_in_version(newIssue.getFixed_in_version());
toCreate.setLast_updated(newIssue.getLast_updated());
toCreate.setOs(newIssue.getOs());
toCreate.setOs_build(newIssue.getOs_build());
toCreate.setPlatform(newIssue.getPlatform());
toCreate.setPriority(newIssue.getPriority());
toCreate.setProject(new ObjectRef(projectId, null));
toCreate.setProjection(newIssue.getProjection());
toCreate.setReproducibility(newIssue.getReproducibility());
toCreate.setResolution(newIssue.getResolution());
toCreate.setSeverity(newIssue.getSeverity());
toCreate.setStatus(newIssue.getStatus());
toCreate.setSteps_to_reproduce(newIssue.getSteps_to_reproduce());
toCreate.setSticky(newIssue.getSticky());
toCreate.setSummary(newIssue.getSummary());
toCreate.setTarget_version(newIssue.getTarget_version());
toCreate.setVersion(newIssue.getVersion());
toCreate.setView_state(newIssue.getView_state());
if ( newIssue.getReporter() != null )
toCreate.setReporter(getAccountDataByName(ourUsers, newIssue.getReporter().getName(), thisUser));
if ( newIssue.getHandler() != null )
toCreate.setHandler(getAccountDataByName(ourUsers, newIssue.getHandler().getName(), null));
List<IssueNoteData> notes = new ArrayList<>();
if ( newIssue.getNotes() != null ) {
for ( IssueNoteData newNote : newIssue.getNotes() ) {
AccountData noteAuthor = getAccountDataByName(ourUsers, newNote.getReporter().getName(), thisUser);
String text = "";
if ( !accountEq(noteAuthor, newNote.getReporter()) )
text = "Original note author: " + newNote.getReporter().getName()+ "\n\n";
text += newNote.getText();
notes.add(new IssueNoteData(null, noteAuthor, text, newNote.getView_state(),
newNote.getDate_submitted(), newNote.getLast_modified(), newNote.getTime_tracking(),
newNote.getNote_type(), newNote.getNote_attr()));
}
}
StringBuilder additionalNoteText = new StringBuilder();
additionalNoteText.append("Originally reported at ").append(oldIssueTrackerUrl)
.append("/view.php?id=").append(newIssue.getId() );
if ( ! accountEq(newIssue.getReporter(), toCreate.getReporter()));
additionalNoteText.append(" by ").append(newIssue.getReporter().getName());
if ( ! accountEq(newIssue.getHandler(), toCreate.getHandler()) )
additionalNoteText.append(", handled by ").append(newIssue.getHandler().getName());
IssueNoteData importNote = new IssueNoteData();
importNote.setReporter(thisUser);
importNote.setText(additionalNoteText.toString());
notes.add(importNote);
toCreate.setNotes(notes.toArray(new IssueNoteData[notes.size()]));
// TODO - tags
// TODO - relationships
// TODO - monitors ?
LOGGER.info("Importing issue {}. [{}] {}", newIssue.getId(), newIssue.getCategory(), newIssue.getSummary());
BigInteger createdIssueId = mantisConnectPort.mc_issue_add(username, password, toCreate);
if ( newIssue.getAttachments() != null ) {
LOGGER.info("Importing {} attachments for issue {}", newIssue.getAttachments().length, newIssue.getId());
for ( AttachmentData attachment : newIssue.getAttachments() ) {
byte[] attachmentData = sourceHandle.getIssueAttachment(attachment.getId().intValue());
mantisConnectPort.mc_issue_attachment_add(username, password, createdIssueId, attachment.getFilename(), attachment.getContent_type(), attachmentData);
}
}
}
}
}
| public void synchronizeIssues(int filterId, List<IssueData> newIssues, String oldIssueTrackerUrl, Handle sourceHandle) throws Exception {
Map<String, AccountData> ourUsers = new HashMap<>();
for ( AccountData ourUser : getUsers() )
ourUsers.put(ourUser.getName(), ourUser);
AccountData thisUser = checkNotNull(ourUsers.get(username));
Map<String, IssueData> ourIssues = new HashMap<>();
for( IssueData ourIssue : getIssues(filterId))
ourIssues.put(ourIssue.getSummary(), ourIssue); // TODO use a compound issue key
for ( IssueData newIssue : newIssues ) {
if ( ourIssues.containsKey(newIssue.getSummary())) {
LOGGER.info("For issue to import with id {} found issue with id {} and same name {}. Skipping", newIssue.getId(), ourIssues.get(newIssue.getSummary()), newIssue.getSummary());
} else {
IssueData toCreate = new IssueData();
toCreate.setAdditional_information(newIssue.getAdditional_information());
toCreate.setBuild(newIssue.getBuild());
toCreate.setCategory(newIssue.getCategory());
toCreate.setDate_submitted(newIssue.getDate_submitted());
toCreate.setDescription(newIssue.getDescription());
toCreate.setDue_date(newIssue.getDue_date());
toCreate.setEta(newIssue.getEta());
toCreate.setFixed_in_version(newIssue.getFixed_in_version());
toCreate.setLast_updated(newIssue.getLast_updated());
toCreate.setOs(newIssue.getOs());
toCreate.setOs_build(newIssue.getOs_build());
toCreate.setPlatform(newIssue.getPlatform());
toCreate.setPriority(newIssue.getPriority());
toCreate.setProject(new ObjectRef(projectId, null));
toCreate.setProjection(newIssue.getProjection());
toCreate.setReproducibility(newIssue.getReproducibility());
toCreate.setResolution(newIssue.getResolution());
toCreate.setSeverity(newIssue.getSeverity());
toCreate.setStatus(newIssue.getStatus());
toCreate.setSteps_to_reproduce(newIssue.getSteps_to_reproduce());
toCreate.setSticky(newIssue.getSticky());
toCreate.setSummary(newIssue.getSummary());
toCreate.setTarget_version(newIssue.getTarget_version());
toCreate.setVersion(newIssue.getVersion());
toCreate.setView_state(newIssue.getView_state());
if ( newIssue.getReporter() != null )
toCreate.setReporter(getAccountDataByName(ourUsers, newIssue.getReporter().getName(), thisUser));
if ( newIssue.getHandler() != null )
toCreate.setHandler(getAccountDataByName(ourUsers, newIssue.getHandler().getName(), null));
List<IssueNoteData> notes = new ArrayList<>();
if ( newIssue.getNotes() != null ) {
for ( IssueNoteData newNote : newIssue.getNotes() ) {
AccountData noteAuthor = getAccountDataByName(ourUsers, newNote.getReporter().getName(), thisUser);
String text = "";
if ( !accountEq(noteAuthor, newNote.getReporter()) )
text = "Original note author: " + newNote.getReporter().getName()+ "\n\n";
text += newNote.getText();
notes.add(new IssueNoteData(null, noteAuthor, text, newNote.getView_state(),
newNote.getDate_submitted(), newNote.getLast_modified(), newNote.getTime_tracking(),
newNote.getNote_type(), newNote.getNote_attr()));
}
}
StringBuilder additionalNoteText = new StringBuilder();
additionalNoteText.append("Originally reported at ").append(oldIssueTrackerUrl)
.append("/view.php?id=").append(newIssue.getId() );
if ( ! accountEq(newIssue.getReporter(), toCreate.getReporter()));
additionalNoteText.append(" by ").append(newIssue.getReporter().getName());
if ( ! accountEq(newIssue.getHandler(), toCreate.getHandler()) )
additionalNoteText.append(", handled by ").append(newIssue.getHandler().getName());
IssueNoteData importNote = new IssueNoteData();
importNote.setReporter(thisUser);
importNote.setText(additionalNoteText.toString());
notes.add(importNote);
toCreate.setNotes(notes.toArray(new IssueNoteData[notes.size()]));
// TODO - tags
// TODO - relationships
// TODO - monitors ?
LOGGER.info("Importing issue {}. [{}] {}", newIssue.getId(), newIssue.getCategory(), newIssue.getSummary());
BigInteger createdIssueId = mantisConnectPort.mc_issue_add(username, password, toCreate);
if ( newIssue.getAttachments() != null && newIssue.getAttachments().length > 0) {
LOGGER.info("Importing {} attachments for issue {}", newIssue.getAttachments().length, newIssue.getId());
for ( AttachmentData attachment : newIssue.getAttachments() ) {
byte[] attachmentData = sourceHandle.getIssueAttachment(attachment.getId().intValue());
mantisConnectPort.mc_issue_attachment_add(username, password, createdIssueId, attachment.getFilename(), attachment.getContent_type(), attachmentData);
}
}
}
}
}
|
diff --git a/src/java/se/idega/idegaweb/commune/school/presentation/StudentPlacings.java b/src/java/se/idega/idegaweb/commune/school/presentation/StudentPlacings.java
index b8aeabd9..9ee7ad2f 100644
--- a/src/java/se/idega/idegaweb/commune/school/presentation/StudentPlacings.java
+++ b/src/java/se/idega/idegaweb/commune/school/presentation/StudentPlacings.java
@@ -1,288 +1,295 @@
/*
* Created on 19.10.2003
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package se.idega.idegaweb.commune.school.presentation;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import se.idega.idegaweb.commune.school.data.SchoolChoice;
import com.idega.block.process.business.CaseBusiness;
import com.idega.block.school.data.School;
import com.idega.block.school.data.SchoolClass;
import com.idega.block.school.data.SchoolClassMember;
import com.idega.business.IBOLookup;
import com.idega.core.contact.data.Email;
import com.idega.core.contact.data.Phone;
import com.idega.core.location.data.Address;
import com.idega.presentation.IWContext;
import com.idega.presentation.Table;
import com.idega.presentation.text.Link;
import com.idega.presentation.ui.GenericButton;
import com.idega.user.data.User;
import com.idega.util.IWTimestamp;
import com.idega.util.PersonalIDFormatter;
/**
* @author laddi
*/
public class StudentPlacings extends SchoolCommuneBlock {
private boolean showChoicesTable = false;
/* (non-Javadoc)
* @see se.idega.idegaweb.commune.school.presentation.SchoolCommuneBlock#init(com.idega.presentation.IWContext)
*/
public void init(IWContext iwc) throws Exception {
Table table = new Table();
table.setCellpadding(0);
table.setCellspacing(0);
table.setWidth(getWidth());
int row = 1;
GenericButton back = (GenericButton) getStyledInterface(new GenericButton("back",localize("back","Back")));
if (getResponsePage() != null)
back.setPageToOpen(getResponsePage());
if (getSession().getStudentID() != -1) {
table.add(getInformationTable(iwc), 1, row++);
table.setRowHeight(row++, "16");
table.add(getSmallHeader(localize("school.placements", "Placements")), 1, row++);
table.setRowHeight(row++, "3");
table.add(getPlacingsTable(iwc), 1, row++);
if (showChoicesTable) {
table.setRowHeight(row++, "16");
table.add(getSmallHeader(localize("school.choices", "Choices")), 1, row++);
table.setRowHeight(row++, "3");
table.add(getChoicesTable(iwc), 1, row++);
}
table.setRowHeight(row++, "16");
table.add(back, 1, row++);
}
else {
table.add(getLocalizedHeader("school.no_student_found","No student found."), 1, 1);
table.add(back, 1, 3);
}
add(table);
}
protected Table getPlacingsTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(4);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
table.add(getLocalizedSmallHeader("school.school","Provider"), column++, row);
table.add(getLocalizedSmallHeader("school.group","Group"), column++, row);
table.add(getLocalizedSmallHeader("school.valid_from","Valid from"), column++, row);
table.add(getLocalizedSmallHeader("school.removed","Removed"), column++, row++);
SchoolClassMember member;
SchoolClass group;
School provider;
IWTimestamp validFrom;
IWTimestamp terminated = null;
Collection placings = getBusiness().getSchoolBusiness().findClassMemberInSchool(getSession().getStudentID(), getSession().getSchoolID());
Iterator iter = placings.iterator();
while (iter.hasNext()) {
column = 1;
member = (SchoolClassMember) iter.next();
group = member.getSchoolClass();
provider = group.getSchool();
validFrom = new IWTimestamp(member.getRegisterDate());
if (member.getRemovedDate() != null)
terminated = new IWTimestamp(member.getRemovedDate());
if (row % 2 == 0)
table.setRowColor(row, getZebraColor1());
else
table.setRowColor(row, getZebraColor2());
table.add(getSmallText(provider.getSchoolName()), column++, row);
table.add(getSmallText(group.getSchoolClassName()), column++, row);
table.add(getSmallText(validFrom.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT)), column++, row);
if (member.getRemovedDate() != null)
table.add(getSmallText(terminated.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT)), column++, row++);
else
table.add(getSmallText("-"), column++, row++);
}
table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER);
return table;
}
protected Table getChoicesTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(6);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
CaseBusiness caseBusiness = (CaseBusiness) IBOLookup.getServiceInstance(iwc, CaseBusiness.class);
Locale currentLocale = iwc.getCurrentLocale();
table.add(getLocalizedSmallHeader("school.school","Provider"), column++, row);
table.add(getLocalizedSmallHeader("school.status","Status"), column++, row);
table.add(getLocalizedSmallHeader("school.created","Created"), column++, row);
table.add(getLocalizedSmallHeader("school.grade","Grade"), column++, row);
table.add(getLocalizedSmallHeader("school.order","Order"), column++, row);
table.add(getLocalizedSmallHeader("school.language","Language"), column++, row);
School provider =getSession().getSchool();
SchoolChoice choice;
Timestamp created;
IWTimestamp iwCreated;
int grade;
+ String strGrade;
String langChoice;
String status;
int orderChoice;
Collection choices = getBusiness().getSchoolChoiceBusiness().findByStudentAndSchool(getSession().getStudentID(), getSession().getSchoolID());
Iterator iter = choices.iterator();
while (iter.hasNext()) {
++row;
column = 1;
choice = (SchoolChoice) iter.next();
status = caseBusiness.getLocalizedCaseStatusDescription(choice.getCaseStatus(), currentLocale);
created = choice.getCreated();
if (created != null) {
iwCreated = new IWTimestamp(created);
} else {
iwCreated = null;
}
try {
grade = choice.getGrade() +1;
+ if (grade != 0) {
+ strGrade = getBusiness().getSchoolYear(grade).getSchoolYearName();
+ } else {
+ strGrade = null;
+ }
} catch (Exception e) {
grade = -1;
+ strGrade = null;
}
orderChoice = choice.getChoiceOrder();
langChoice = choice.getLanguageChoice();
if (row % 2 == 0)
table.setRowColor(row, getZebraColor1());
else
table.setRowColor(row, getZebraColor2());
table.add(getSmallText(provider.getSchoolName()), column++, row);
table.add(getSmallText(status), column++, row);
if (iwCreated != null) {
table.add(getSmallText(iwCreated.getLocaleDate(currentLocale, IWTimestamp.SHORT)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
- if (grade != -1) {
- table.add(getSmallText(Integer.toString(grade)), column++, row);
+ if (strGrade != null) {
+ table.add(getSmallText(strGrade), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (orderChoice != -1) {
table.add(getSmallText(Integer.toString(orderChoice)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (langChoice != null) {
table.add(getSmallText(langChoice), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
}
table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(5, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(6, Table.HORIZONTAL_ALIGN_CENTER);
return table;
}
protected Table getInformationTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(Table.HUNDRED_PERCENT);
table.setCellpadding(0);
table.setCellspacing(0);
table.setColumns(3);
table.setWidth(1, "100");
table.setWidth(2, "6");
int row = 1;
User child = getBusiness().getUserBusiness().getUser(getSession().getStudentID());
if (child != null) {
Address address = getBusiness().getUserBusiness().getUsersMainAddress(child);
Collection parents = getBusiness().getUserBusiness().getParentsForChild(child);
table.add(getLocalizedSmallHeader("school.student","Student"), 1, row);
table.add(getSmallText(child.getNameLastFirst(true)), 3, row);
table.add(getSmallText(" - "), 3, row);
table.add(getSmallText(PersonalIDFormatter.format(child.getPersonalID(), iwc.getCurrentLocale())), 3, row++);
if (address != null) {
table.add(getLocalizedSmallHeader("school.address","Address"), 1, row);
table.add(getSmallText(address.getStreetAddress()), 3, row);
if (address.getPostalAddress() != null)
table.add(getSmallText(", "+address.getPostalAddress()), 3, row);
row++;
}
table.setHeight(row++, 12);
if (parents != null) {
table.add(getLocalizedSmallHeader("school.parents","Parents"), 1, row);
Phone phone;
Email email;
Iterator iter = parents.iterator();
while (iter.hasNext()) {
User parent = (User) iter.next();
address = getBusiness().getUserBusiness().getUsersMainAddress(parent);
email = getBusiness().getUserBusiness().getEmail(parent);
phone = getBusiness().getUserBusiness().getHomePhone(parent);
table.add(getSmallText(parent.getNameLastFirst(true)), 3, row);
table.add(getSmallText(" - "), 3, row);
table.add(getSmallText(PersonalIDFormatter.format(parent.getPersonalID(), iwc.getCurrentLocale())), 3, row++);
if (address != null) {
table.add(getSmallText(address.getStreetAddress()), 3, row);
if (address.getPostalAddress() != null)
table.add(getSmallText(", "+address.getPostalAddress()), 3, row);
row++;
}
if (phone != null && phone.getNumber() != null) {
table.add(getSmallText(localize("school.phone","Phone")+": "), 3, row);
table.add(getSmallText(phone.getNumber()), 3, row++);
}
if (email != null && email.getEmailAddress() != null) {
Link link = getSmallLink(email.getEmailAddress());
link.setURL("mailto:"+email.getEmailAddress(), false, false);
table.add(link, 3, row++);
}
table.setHeight(row++, 12);
}
}
}
return table;
}
public void setShowChoicesTable(boolean show) {
this.showChoicesTable = show;
}
}
| false | true | protected Table getChoicesTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(6);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
CaseBusiness caseBusiness = (CaseBusiness) IBOLookup.getServiceInstance(iwc, CaseBusiness.class);
Locale currentLocale = iwc.getCurrentLocale();
table.add(getLocalizedSmallHeader("school.school","Provider"), column++, row);
table.add(getLocalizedSmallHeader("school.status","Status"), column++, row);
table.add(getLocalizedSmallHeader("school.created","Created"), column++, row);
table.add(getLocalizedSmallHeader("school.grade","Grade"), column++, row);
table.add(getLocalizedSmallHeader("school.order","Order"), column++, row);
table.add(getLocalizedSmallHeader("school.language","Language"), column++, row);
School provider =getSession().getSchool();
SchoolChoice choice;
Timestamp created;
IWTimestamp iwCreated;
int grade;
String langChoice;
String status;
int orderChoice;
Collection choices = getBusiness().getSchoolChoiceBusiness().findByStudentAndSchool(getSession().getStudentID(), getSession().getSchoolID());
Iterator iter = choices.iterator();
while (iter.hasNext()) {
++row;
column = 1;
choice = (SchoolChoice) iter.next();
status = caseBusiness.getLocalizedCaseStatusDescription(choice.getCaseStatus(), currentLocale);
created = choice.getCreated();
if (created != null) {
iwCreated = new IWTimestamp(created);
} else {
iwCreated = null;
}
try {
grade = choice.getGrade() +1;
} catch (Exception e) {
grade = -1;
}
orderChoice = choice.getChoiceOrder();
langChoice = choice.getLanguageChoice();
if (row % 2 == 0)
table.setRowColor(row, getZebraColor1());
else
table.setRowColor(row, getZebraColor2());
table.add(getSmallText(provider.getSchoolName()), column++, row);
table.add(getSmallText(status), column++, row);
if (iwCreated != null) {
table.add(getSmallText(iwCreated.getLocaleDate(currentLocale, IWTimestamp.SHORT)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (grade != -1) {
table.add(getSmallText(Integer.toString(grade)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (orderChoice != -1) {
table.add(getSmallText(Integer.toString(orderChoice)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (langChoice != null) {
table.add(getSmallText(langChoice), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
}
table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(5, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(6, Table.HORIZONTAL_ALIGN_CENTER);
return table;
}
| protected Table getChoicesTable(IWContext iwc) throws RemoteException {
Table table = new Table();
table.setWidth(getWidth());
table.setCellpadding(getCellpadding());
table.setCellspacing(getCellspacing());
table.setColumns(6);
table.setRowColor(1, getHeaderColor());
int column = 1;
int row = 1;
CaseBusiness caseBusiness = (CaseBusiness) IBOLookup.getServiceInstance(iwc, CaseBusiness.class);
Locale currentLocale = iwc.getCurrentLocale();
table.add(getLocalizedSmallHeader("school.school","Provider"), column++, row);
table.add(getLocalizedSmallHeader("school.status","Status"), column++, row);
table.add(getLocalizedSmallHeader("school.created","Created"), column++, row);
table.add(getLocalizedSmallHeader("school.grade","Grade"), column++, row);
table.add(getLocalizedSmallHeader("school.order","Order"), column++, row);
table.add(getLocalizedSmallHeader("school.language","Language"), column++, row);
School provider =getSession().getSchool();
SchoolChoice choice;
Timestamp created;
IWTimestamp iwCreated;
int grade;
String strGrade;
String langChoice;
String status;
int orderChoice;
Collection choices = getBusiness().getSchoolChoiceBusiness().findByStudentAndSchool(getSession().getStudentID(), getSession().getSchoolID());
Iterator iter = choices.iterator();
while (iter.hasNext()) {
++row;
column = 1;
choice = (SchoolChoice) iter.next();
status = caseBusiness.getLocalizedCaseStatusDescription(choice.getCaseStatus(), currentLocale);
created = choice.getCreated();
if (created != null) {
iwCreated = new IWTimestamp(created);
} else {
iwCreated = null;
}
try {
grade = choice.getGrade() +1;
if (grade != 0) {
strGrade = getBusiness().getSchoolYear(grade).getSchoolYearName();
} else {
strGrade = null;
}
} catch (Exception e) {
grade = -1;
strGrade = null;
}
orderChoice = choice.getChoiceOrder();
langChoice = choice.getLanguageChoice();
if (row % 2 == 0)
table.setRowColor(row, getZebraColor1());
else
table.setRowColor(row, getZebraColor2());
table.add(getSmallText(provider.getSchoolName()), column++, row);
table.add(getSmallText(status), column++, row);
if (iwCreated != null) {
table.add(getSmallText(iwCreated.getLocaleDate(currentLocale, IWTimestamp.SHORT)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (strGrade != null) {
table.add(getSmallText(strGrade), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (orderChoice != -1) {
table.add(getSmallText(Integer.toString(orderChoice)), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
if (langChoice != null) {
table.add(getSmallText(langChoice), column++, row);
} else {
table.add(getSmallText("-"), column++, row);
}
}
table.setColumnAlignment(3, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(4, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(5, Table.HORIZONTAL_ALIGN_CENTER);
table.setColumnAlignment(6, Table.HORIZONTAL_ALIGN_CENTER);
return table;
}
|
diff --git a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/providers/ModuleViewProvider.java b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/providers/ModuleViewProvider.java
index bfdad66a2..9093ab7fa 100755
--- a/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/providers/ModuleViewProvider.java
+++ b/as/plugins/org.jboss.ide.eclipse.as.ui/jbossui/org/jboss/ide/eclipse/as/ui/views/server/providers/ModuleViewProvider.java
@@ -1,298 +1,299 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ide.eclipse.as.ui.views.server.providers;
import java.util.Properties;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.IServerLifecycleListener;
import org.eclipse.wst.server.core.IServerListener;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.ServerCore;
import org.eclipse.wst.server.core.ServerEvent;
import org.eclipse.wst.server.core.ServerUtil;
import org.eclipse.wst.server.core.model.ServerBehaviourDelegate;
import org.eclipse.wst.server.ui.ServerUICore;
import org.eclipse.wst.server.ui.internal.view.servers.ModuleServer;
import org.jboss.ide.eclipse.as.core.server.internal.DeployableServerBehavior;
import org.jboss.ide.eclipse.as.core.server.internal.JBossServer;
import org.jboss.ide.eclipse.as.core.util.ServerConverter;
import org.jboss.ide.eclipse.as.ui.JBossServerUISharedImages;
import org.jboss.ide.eclipse.as.ui.Messages;
import org.jboss.ide.eclipse.as.ui.views.server.extensions.ServerViewProvider;
import org.jboss.ide.eclipse.as.ui.views.server.extensions.SimplePropertiesViewExtension;
public class ModuleViewProvider extends SimplePropertiesViewExtension {
private ModuleContentProvider contentProvider;
private ModuleLabelProvider labelProvider;
private Action deleteModuleAction, fullPublishModuleAction, incrementalPublishModuleAction;
private ModuleServer selection;
private IServerLifecycleListener serverResourceListener;
private IServerListener serverListener;
public ModuleViewProvider() {
contentProvider = new ModuleContentProvider();
labelProvider = new ModuleLabelProvider();
createActions();
addListeners();
}
private void createActions() {
deleteModuleAction = new Action() {
public void run() {
if (MessageDialog.openConfirm(new Shell(), Messages.ServerDialogHeading, Messages.DeleteModuleConfirm)) {
Thread t = new Thread() { public void run() {
try {
IServerWorkingCopy server = selection.server.createWorkingCopy();
- IServer server2 = server.save(true, null);
if( ServerConverter.getDeployableServer(selection.server) != null ) {
ServerConverter.getDeployableServerBehavior(selection.server)
.publishOneModule(IServer.PUBLISH_FULL, selection.module, ServerBehaviourDelegate.REMOVED, new NullProgressMonitor());
} else {
+ ServerUtil.modifyModules(server, new IModule[0], selection.module, new NullProgressMonitor());
+ IServer server2 = server.save(true, null);
server2.publish(IServer.PUBLISH_INCREMENTAL, new NullProgressMonitor());
}
} catch (Exception e) {
// ignore
}
}};
t.start();
}
}
};
deleteModuleAction.setText(Messages.DeleteModuleText);
deleteModuleAction.setDescription(Messages.DeleteModuleDescription);
deleteModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.UNPUBLISH_IMAGE));
fullPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_FULL);
}
};
fullPublishModuleAction.setText(Messages.PublishModuleText);
fullPublishModuleAction.setDescription(Messages.PublishModuleDescription);
fullPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
incrementalPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_INCREMENTAL);
}
};
incrementalPublishModuleAction.setText("Incremental Publish");
incrementalPublishModuleAction.setDescription(Messages.PublishModuleDescription);
incrementalPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
}
protected void actionPublish(int type) {
try {
if( ServerConverter.getDeployableServer(selection.server) != null ) {
ServerConverter.getDeployableServerBehavior(selection.server)
.publishOneModule(type, selection.module,
ServerBehaviourDelegate.CHANGED, new NullProgressMonitor());
} else {
selection.server.publish(IServer.PUBLISH_INCREMENTAL, new NullProgressMonitor());
}
} catch( Exception e ) {
// ignore
}
}
public void fillContextMenu(Shell shell, IMenuManager menu, Object selection) {
if( selection instanceof ModuleServer) {
this.selection = (ModuleServer)selection;
menu.add(deleteModuleAction);
menu.add(fullPublishModuleAction);
menu.add(incrementalPublishModuleAction);
}
}
public ITreeContentProvider getContentProvider() {
return contentProvider;
}
public LabelProvider getLabelProvider() {
return labelProvider;
}
public boolean supports(IServer server) {
return true;
}
class ModuleContentProvider implements ITreeContentProvider {
private IServer input;
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof ModuleServer) {
ModuleServer ms = (ModuleServer) parentElement;
try {
IModule[] children = ms.server.getChildModules(ms.module, null);
int size = children.length;
ModuleServer[] ms2 = new ModuleServer[size];
for (int i = 0; i < size; i++) {
int size2 = ms.module.length;
IModule[] module = new IModule[size2 + 1];
System.arraycopy(ms.module, 0, module, 0, size2);
module[size2] = children[i];
ms2[i] = new ModuleServer(ms.server, module);
}
return ms2;
} catch (Exception e) {
return new Object[]{};
}
}
if( parentElement instanceof ServerViewProvider && input != null ) {
IModule[] modules = input.getModules();
int size = modules.length;
ModuleServer[] ms = new ModuleServer[size];
for (int i = 0; i < size; i++) {
ms[i] = new ModuleServer(input, new IModule[] { modules[i] });
}
return ms;
}
return new Object[] {};
}
public Object getParent(Object element) {
if( element instanceof ModuleServer ) {
return provider;
}
return null;
}
public boolean hasChildren(Object element) {
return getChildren(element).length > 0 ? true : false;
}
// unused
public Object[] getElements(Object inputElement) {
return null;
}
public void dispose() {
// TODO Auto-generated method stub
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
input = (IServer)newInput;
}
public IServer getServer() {
return input;
}
}
class ModuleLabelProvider extends LabelProvider {
public String getText(Object obj) {
if( obj instanceof ModuleServer ) {
ModuleServer ms = (ModuleServer)obj;
int size = ms.module.length;
return ms.module[size - 1].getName();
}
return "garbage";
}
public Image getImage(Object obj) {
if( obj instanceof ModuleServer ) {
ModuleServer ms = (ModuleServer)obj;
int size = ms.module.length;
return ServerUICore.getLabelProvider().getImage(ms.module[ms.module.length - 1]);
}
return null;
}
}
public String[] getPropertyKeys(Object selected) {
return new String[] { Messages.ModulePropertyType, Messages.ModulePropertyProject };
}
public Properties getProperties(Object selected) {
Properties props = new Properties();
if( selected != null && selected instanceof ModuleServer) {
IModule mod = ((ModuleServer)selected).module[0];
if( mod != null && mod.getProject() != null ) {
props.setProperty(Messages.ModulePropertyType, mod.getModuleType().getId());
props.setProperty(Messages.ModulePropertyProject, mod.getProject().getName());
}
}
return props;
}
private void addListeners() {
serverResourceListener = new IServerLifecycleListener() {
public void serverAdded(IServer server) {
if( ServerConverter.getJBossServer(server) != null )
server.addServerListener(serverListener);
}
public void serverChanged(IServer server) {
}
public void serverRemoved(IServer server) {
if( ServerConverter.getJBossServer(server) != null )
server.removeServerListener(serverListener);
}
};
ServerCore.addServerLifecycleListener(serverResourceListener);
serverListener = new IServerListener() {
public void serverChanged(ServerEvent event) {
int eventKind = event.getKind();
if ((eventKind & ServerEvent.MODULE_CHANGE) != 0) {
// module change event
if ((eventKind & ServerEvent.STATE_CHANGE) != 0 || (eventKind & ServerEvent.PUBLISH_STATE_CHANGE) != 0) {
refreshViewer();
}
}
}
};
// add listeners to servers
JBossServer[] servers = ServerConverter.getAllJBossServers();
if (servers != null) {
int size = servers.length;
for (int i = 0; i < size; i++) {
servers[i].getServer().addServerListener(serverListener);
}
}
}
}
| false | true | private void createActions() {
deleteModuleAction = new Action() {
public void run() {
if (MessageDialog.openConfirm(new Shell(), Messages.ServerDialogHeading, Messages.DeleteModuleConfirm)) {
Thread t = new Thread() { public void run() {
try {
IServerWorkingCopy server = selection.server.createWorkingCopy();
IServer server2 = server.save(true, null);
if( ServerConverter.getDeployableServer(selection.server) != null ) {
ServerConverter.getDeployableServerBehavior(selection.server)
.publishOneModule(IServer.PUBLISH_FULL, selection.module, ServerBehaviourDelegate.REMOVED, new NullProgressMonitor());
} else {
server2.publish(IServer.PUBLISH_INCREMENTAL, new NullProgressMonitor());
}
} catch (Exception e) {
// ignore
}
}};
t.start();
}
}
};
deleteModuleAction.setText(Messages.DeleteModuleText);
deleteModuleAction.setDescription(Messages.DeleteModuleDescription);
deleteModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.UNPUBLISH_IMAGE));
fullPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_FULL);
}
};
fullPublishModuleAction.setText(Messages.PublishModuleText);
fullPublishModuleAction.setDescription(Messages.PublishModuleDescription);
fullPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
incrementalPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_INCREMENTAL);
}
};
incrementalPublishModuleAction.setText("Incremental Publish");
incrementalPublishModuleAction.setDescription(Messages.PublishModuleDescription);
incrementalPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
}
| private void createActions() {
deleteModuleAction = new Action() {
public void run() {
if (MessageDialog.openConfirm(new Shell(), Messages.ServerDialogHeading, Messages.DeleteModuleConfirm)) {
Thread t = new Thread() { public void run() {
try {
IServerWorkingCopy server = selection.server.createWorkingCopy();
if( ServerConverter.getDeployableServer(selection.server) != null ) {
ServerConverter.getDeployableServerBehavior(selection.server)
.publishOneModule(IServer.PUBLISH_FULL, selection.module, ServerBehaviourDelegate.REMOVED, new NullProgressMonitor());
} else {
ServerUtil.modifyModules(server, new IModule[0], selection.module, new NullProgressMonitor());
IServer server2 = server.save(true, null);
server2.publish(IServer.PUBLISH_INCREMENTAL, new NullProgressMonitor());
}
} catch (Exception e) {
// ignore
}
}};
t.start();
}
}
};
deleteModuleAction.setText(Messages.DeleteModuleText);
deleteModuleAction.setDescription(Messages.DeleteModuleDescription);
deleteModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.UNPUBLISH_IMAGE));
fullPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_FULL);
}
};
fullPublishModuleAction.setText(Messages.PublishModuleText);
fullPublishModuleAction.setDescription(Messages.PublishModuleDescription);
fullPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
incrementalPublishModuleAction = new Action() {
public void run() {
actionPublish(IServer.PUBLISH_INCREMENTAL);
}
};
incrementalPublishModuleAction.setText("Incremental Publish");
incrementalPublishModuleAction.setDescription(Messages.PublishModuleDescription);
incrementalPublishModuleAction.setImageDescriptor(JBossServerUISharedImages.getImageDescriptor(JBossServerUISharedImages.PUBLISH_IMAGE));
}
|
diff --git a/srcj/com/sun/electric/technology/Xml.java b/srcj/com/sun/electric/technology/Xml.java
index d45e6998f..9bf4a149c 100644
--- a/srcj/com/sun/electric/technology/Xml.java
+++ b/srcj/com/sun/electric/technology/Xml.java
@@ -1,2379 +1,2392 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Xml.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.technology;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EGraphics;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.technology.Technology.TechPoint;
import com.sun.electric.tool.Job;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
*/
public class Xml {
/** Default Logical effort gate capacitance. */ public static final double DEFAULT_LE_GATECAP = 0.4;
/** Default Logical effort wire ratio. */ public static final double DEFAULT_LE_WIRERATIO = 0.16;
/** Default Logical effort diff alpha. */ public static final double DEFAULT_LE_DIFFALPHA = 0.7;
public static class Technology implements Serializable {
public String techName;
public String className;
public String shortTechName;
public String description;
public final List<Version> versions = new ArrayList<Version>();
public int minNumMetals;
public int maxNumMetals;
public int defaultNumMetals;
public double scaleValue;
public double resolutionValue; // min resolution value allowed by the foundry
public boolean scaleRelevant;
public String defaultFoundry;
public double minResistance;
public double minCapacitance;
public double leGateCapacitance = DEFAULT_LE_GATECAP;
public double leWireRatio = DEFAULT_LE_WIRERATIO;
public double leDiffAlpha = DEFAULT_LE_DIFFALPHA;
public final List<Color> transparentLayers = new ArrayList<Color>();
public final List<Layer> layers = new ArrayList<Layer>();
public final List<ArcProto> arcs = new ArrayList<ArcProto>();
public final List<PrimitiveNodeGroup> nodeGroups = new ArrayList<PrimitiveNodeGroup>();
public final List<SpiceHeader> spiceHeaders = new ArrayList<SpiceHeader>();
public MenuPalette menuPalette;
public final List<Foundry> foundries = new ArrayList<Foundry>();
public Layer findLayer(String name) {
for (Layer layer: layers) {
if (layer.name.equals(name))
return layer;
}
return null;
}
public ArcProto findArc(String name) {
for (ArcProto arc: arcs) {
if (arc.name.equals(name))
return arc;
}
return null;
}
public PrimitiveNodeGroup findNodeGroup(String name) {
for (PrimitiveNodeGroup nodeGroup: nodeGroups) {
for (PrimitiveNode n: nodeGroup.nodes) {
if (n.name.equals(name))
return nodeGroup;
}
}
return null;
}
public PrimitiveNode findNode(String name) {
for (PrimitiveNodeGroup nodeGroup: nodeGroups) {
for (PrimitiveNode n: nodeGroup.nodes) {
if (n.name.equals(name))
return n;
}
}
return null;
}
public void writeXml(String fileName) {
writeXml(fileName, true, null);
}
public void writeXml(String fileName, boolean includeDateAndVersion, String copyrightMessage) {
try {
PrintWriter out = new PrintWriter(fileName);
Writer writer = new Writer(out);
writer.writeTechnology(this, includeDateAndVersion, copyrightMessage);
out.close();
System.out.println("Wrote " + fileName);
System.out.println(" (Add this file to the 'Added Technologies' Project Preferences to install it in Electric)");
} catch (IOException e) {
System.out.println("Error creating " + fileName);
}
}
public Technology deepClone() {
try {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteStream);
out.writeObject(this);
out.flush();
byte[] serializedXml = byteStream.toByteArray();
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serializedXml));
Xml.Technology clone = (Xml.Technology)in.readObject();
in.close();
return clone;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
public static class Version implements Serializable {
public int techVersion;
public com.sun.electric.database.text.Version electricVersion;
}
public static class Layer implements Serializable {
public String name;
public com.sun.electric.technology.Layer.Function function;
public int extraFunction;
public EGraphics desc;
public double thick3D;
public double height3D;
public String cif;
public String skill;
public double resistance;
public double capacitance;
public double edgeCapacitance;
public PureLayerNode pureLayerNode;
}
public static class PureLayerNode implements Serializable {
public String name;
public String oldName;
public Poly.Type style;
public String port;
public final Distance size = new Distance();
public final List<String> portArcs = new ArrayList<String>();
}
public static class ArcProto implements Serializable {
public String name;
public String oldName;
public com.sun.electric.technology.ArcProto.Function function;
public boolean wipable;
public boolean curvable;
public boolean special;
public boolean notUsed;
public boolean skipSizeInPalette;
public final Map<Integer,Double> diskOffset = new TreeMap<Integer,Double>();
public final Distance defaultWidth = new Distance();
public boolean extended;
public boolean fixedAngle;
public int angleIncrement;
public double antennaRatio;
public final List<ArcLayer> arcLayers = new ArrayList<ArcLayer>();
}
public static class ArcLayer implements Serializable {
public String layer;
public final Distance extend = new Distance();
public Poly.Type style;
}
public static class PrimitiveNode implements Serializable {
public String name;
public com.sun.electric.technology.PrimitiveNode.Function function;
public String oldName;
public boolean lowVt;
public boolean highVt;
public boolean nativeBit;
public boolean od18;
public boolean od25;
public boolean od33;
}
public static class PrimitiveNodeGroup implements Serializable {
public boolean isSingleton;
public final List<PrimitiveNode> nodes = new ArrayList<PrimitiveNode>();
public boolean shrinkArcs;
public boolean square;
public boolean canBeZeroSize;
public boolean wipes;
public boolean lockable;
public boolean edgeSelect;
public boolean skipSizeInPalette;
public boolean notUsed;
public final Map<Integer,EPoint> diskOffset = new TreeMap<Integer,EPoint>();
public final Distance defaultWidth = new Distance();
public final Distance defaultHeight = new Distance();
public final Distance baseLX = new Distance();
public final Distance baseHX = new Distance();
public final Distance baseLY = new Distance();
public final Distance baseHY = new Distance();
public ProtectionType protection;
public final List<NodeLayer> nodeLayers = new ArrayList<NodeLayer>();
public final List<PrimitivePort> ports = new ArrayList<PrimitivePort>();
public int specialType;
public double[] specialValues;
public NodeSizeRule nodeSizeRule;
public String spiceTemplate;
}
public enum ProtectionType {
both, left, right, none;
}
public static class NodeLayer implements Serializable {
public String layer;
public BitSet inNodes;
public Poly.Type style;
public int portNum;
public boolean inLayers;
public boolean inElectricalLayers;
public int representation;
public final Distance lx = new Distance();
public final Distance hx = new Distance();
public final Distance ly = new Distance();
public final Distance hy = new Distance();
public final List<TechPoint> techPoints = new ArrayList<TechPoint>();
public double sizex, sizey, sep1d, sep2d;
public double lWidth, rWidth, tExtent, bExtent;
}
public static class NodeSizeRule implements Serializable {
public double width;
public double height;
public String rule;
}
public static class PrimitivePort implements Serializable {
public String name;
public int portAngle;
public int portRange;
public int portTopology;
public final Distance lx = new Distance();
public final Distance hx = new Distance();
public final Distance ly = new Distance();
public final Distance hy = new Distance();
public final List<String> portArcs = new ArrayList<String>();
}
public static class SpiceHeader implements Serializable {
public int level;
public final List<String> spiceLines = new ArrayList<String>();
}
public static class MenuPalette implements Serializable {
public int numColumns;
public List<List<?>> menuBoxes = new ArrayList<List<?>>();
public String writeXml() {
StringWriter sw = new StringWriter();
PrintWriter out = new PrintWriter(sw);
Xml.OneLineWriter writer = new Xml.OneLineWriter(out);
writer.writeMenuPaletteXml(this);
out.close();
return sw.getBuffer().toString();
}
}
public static class MenuNodeInst implements Serializable {
/** the name of the prototype in the menu */ public String protoName;
/** the function of the prototype */ public com.sun.electric.technology.PrimitiveNode.Function function;
/** tech bits */ public int techBits;
/** label to draw in the menu entry (may be null) */ public String text;
/** the rotation of the node in the menu entry */ public int rotation;
}
public static class Distance implements Serializable {
public double k;
public double value;
public void addLambda(double lambdaValue) {
value += lambdaValue;
}
}
public static class Foundry implements Serializable {
public String name;
public final Map<String,String> layerGds = new LinkedHashMap<String,String>();
public final List<DRCTemplate> rules = new ArrayList<DRCTemplate>();
}
private Xml() {}
private static enum XmlKeyword {
technology,
shortName(true),
description(true),
version,
numMetals,
scale,
resolution,
defaultFoundry,
minResistance,
minCapacitance,
logicalEffort,
transparentLayer,
r(true),
g(true),
b(true),
layer,
transparentColor,
opaqueColor,
patternedOnDisplay(true),
patternedOnPrinter(true),
pattern(true),
outlined(true),
opacity(true),
foreground(true),
display3D,
cifLayer,
skillLayer,
parasitics,
pureLayerNode,
arcProto,
oldName(true),
wipable,
curvable,
special,
notUsed,
skipSizeInPalette,
extended(true),
fixedAngle(true),
angleIncrement(true),
antennaRatio(true),
diskOffset,
defaultWidth,
arcLayer,
primitiveNodeGroup,
inNodes,
primitiveNode,
//oldName(true),
shrinkArcs,
square,
canBeZeroSize,
wipes,
lockable,
edgeSelect,
// skipSizeInPalette,
// notUsed,
lowVt,
highVt,
nativeBit,
od18,
od25,
od33,
// defaultWidth,
defaultHeight,
nodeBase,
sizeOffset,
nodeLayer,
box,
multicutbox,
serpbox,
lambdaBox,
points,
techPoint,
primitivePort,
portAngle,
portTopology(true),
// techPoint,
portArc(true),
polygonal,
serpTrans,
specialValue(true),
// Protection layer for transistors
protection,
// location(true),
minSizeRule,
spiceTemplate,
spiceHeader,
spiceLine,
menuPalette,
menuBox,
menuArc(true),
menuNode(true),
menuText(true),
menuNodeInst,
menuNodeText,
lambda(true),
Foundry,
layerGds,
LayerRule,
LayersRule,
NodeLayersRule,
NodeRule;
private final boolean hasText;
private XmlKeyword() {
hasText = false;
};
private XmlKeyword(boolean hasText) {
this.hasText = hasText;
}
};
private static final Map<String,XmlKeyword> xmlKeywords = new HashMap<String,XmlKeyword>();
static {
for (XmlKeyword k: XmlKeyword.class.getEnumConstants())
xmlKeywords.put(k.name(), k);
}
private static Schema schema = null;
private static synchronized void loadTechnologySchema() throws SAXException {
if (schema != null) return;
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL technologySchemaUrl = Technology.class.getResource("Technology.xsd");
if (technologySchemaUrl != null)
schema = schemaFactory.newSchema(technologySchemaUrl);
else
{
System.err.println("Schema file Technology.xsd, working without XML schema");
System.out.println("Schema file Technology.xsd, working without XML schema");
}
}
public static Technology parseTechnology(URL fileURL) {
// System.out.println("Memory usage " + Main.getMemoryUsage() + " bytes");
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
try {
if (schema == null)
loadTechnologySchema();
factory.setSchema(schema);
// factory.setValidating(true);
// System.out.println("Memory usage " + Main.getMemoryUsage() + " bytes");
// create the parser
long startTime = System.currentTimeMillis();
SAXParser parser = factory.newSAXParser();
URLConnection urlCon = fileURL.openConnection();
InputStream inputStream = urlCon.getInputStream();
XMLReader handler = new XMLReader();
parser.parse(inputStream, handler);
if (Job.getDebug())
{
long stopTime = System.currentTimeMillis();
System.out.println("Loading technology " + fileURL + " ... " + (stopTime - startTime) + " msec");
}
return handler.tech;
} catch (SAXParseException e) {
String msg = "Error parsing Xml technology:\n" +
e.getMessage() + "\n" +
" Line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + fileURL;
msg = msg.replaceAll("\"http://electric.sun.com/Technology\":", "");
System.out.println(msg);
Job.getUserInterface().showErrorMessage(msg, "Error parsing Xml technology");
} catch (Exception e) {
String msg = "Error loading Xml technology " + fileURL + " :\n"
+ e.getMessage() + "\n";
System.out.println(msg);
Job.getUserInterface().showErrorMessage(msg, "Error loading Xml technology");
}
return null;
}
/**
* Method to parse a string of XML that describes the component menu in a Technology Editing context.
* Normal parsing of XML returns objects in the Xml class, but
* this method returns objects in a given Technology-Editor world.
* @param xml the XML string
* @param nodeGroups the PrimitiveNodeGroup objects describing nodes in the technology.
* @param arcs the ArcProto objects describing arcs in the technology.
* @return the MenuPalette describing the component menu.
*/
public static MenuPalette parseComponentMenuXMLTechEdit(String xml, List<PrimitiveNodeGroup> nodeGroups, List<ArcProto> arcs)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
try
{
SAXParser parser = factory.newSAXParser();
InputSource is = new InputSource(new StringReader(xml));
XMLReader handler = new XMLReader(nodeGroups, arcs);
parser.parse(is, handler);
return handler.tech.menuPalette;
} catch (Exception e)
{
System.out.println("Error parsing XML component menu data");
e.printStackTrace();
}
return null;
}
private static class XMLReader extends DefaultHandler {
private static boolean DEBUG = false;
private Locator locator;
private Xml.Technology tech = new Xml.Technology();
private int curTransparent = 0;
private int curR;
private int curG;
private int curB;
private Layer curLayer;
private boolean patternedOnDisplay;
private boolean patternedOnPrinter;
private final int[] pattern = new int[16];
private int curPatternIndex;
private EGraphics.Outline outline;
private double opacity;
private boolean foreground;
private EGraphics.J3DTransparencyOption transparencyMode;
private double transparencyFactor;
private ArcProto curArc;
private PrimitiveNodeGroup curNodeGroup;
private boolean curNodeGroupHasNodeBase;
private PrimitiveNode curNode;
private NodeLayer curNodeLayer;
private PrimitivePort curPort;
private int curSpecialValueIndex;
private ArrayList<Object> curMenuBox;
private MenuNodeInst curMenuNodeInst;
private Distance curDistance;
private SpiceHeader curSpiceHeader;
private Foundry curFoundry;
private boolean acceptCharacters;
private StringBuilder charBuffer = new StringBuilder();
private Attributes attributes;
XMLReader() {
}
XMLReader(List<PrimitiveNodeGroup> nodeGroups, List<ArcProto> arcs)
{
tech.arcs.addAll(arcs);
tech.nodeGroups.addAll(nodeGroups);
}
private void beginCharacters() {
assert !acceptCharacters;
acceptCharacters = true;
assert charBuffer.length() == 0;
}
private String endCharacters() {
assert acceptCharacters;
String s = charBuffer.toString();
charBuffer.setLength(0);
acceptCharacters = false;
return s;
}
////////////////////////////////////////////////////////////////////
// Default implementation of the EntityResolver interface.
////////////////////////////////////////////////////////////////////
/**
* Resolve an external entity.
*
* <p>Always return null, so that the parser will use the system
* identifier provided in the XML document. This method implements
* the SAX default behaviour: application writers can override it
* in a subclass to do special translations such as catalog lookups
* or URI redirection.</p>
*
* @param publicId The public identifier, or null if none is
* available.
* @param systemId The system identifier provided in the XML
* document.
* @return The new input source, or null to require the
* default behaviour.
* @exception java.io.IOException If there is an error setting
* up the new input source.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.EntityResolver#resolveEntity
*/
public InputSource resolveEntity(String publicId, String systemId)
throws IOException, SAXException {
return null;
}
////////////////////////////////////////////////////////////////////
// Default implementation of DTDHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive notification of a notation declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to keep track of the notations
* declared in a document.</p>
*
* @param name The notation name.
* @param publicId The notation public identifier, or null if not
* available.
* @param systemId The notation system identifier.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#notationDecl
*/
public void notationDecl(String name, String publicId, String systemId)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of an unparsed entity declaration.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to keep track of the unparsed entities
* declared in a document.</p>
*
* @param name The entity name.
* @param publicId The entity public identifier, or null if not
* available.
* @param systemId The entity system identifier.
* @param notationName The name of the associated notation.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void unparsedEntityDecl(String name, String publicId,
String systemId, String notationName)
throws SAXException {
// int x = 0;
}
////////////////////////////////////////////////////////////////////
// Default implementation of ContentHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive a Locator object for document events.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass if they wish to store the locator for use
* with other document events.</p>
*
* @param locator A locator for all SAX document events.
* @see org.xml.sax.ContentHandler#setDocumentLocator
* @see org.xml.sax.Locator
*/
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
private void printLocator() {
System.out.println("publicId=" + locator.getPublicId() + " systemId=" + locator.getSystemId() +
" line=" + locator.getLineNumber() + " column=" + locator.getColumnNumber());
}
/**
* Receive notification of the beginning of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the beginning
* of a document (such as allocating the root node of a tree or
* creating an output file).</p>
*
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startDocument
*/
public void startDocument()
throws SAXException {
if (DEBUG) {
System.out.println("startDocument");
}
}
/**
* Receive notification of the end of the document.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end
* of a document (such as finalising a tree or closing an output
* file).</p>
*
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endDocument
*/
public void endDocument()
throws SAXException {
if (DEBUG) {
System.out.println("endDocument");
}
}
/**
* Receive notification of the start of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each Namespace prefix scope (such as storing the prefix mapping).</p>
*
* @param prefix The Namespace prefix being declared.
* @param uri The Namespace URI mapped to the prefix.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startPrefixMapping
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
if (DEBUG) {
System.out.println("startPrefixMapping prefix=" + prefix + " uri=" + uri);
}
}
/**
* Receive notification of the end of a Namespace mapping.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each prefix mapping.</p>
*
* @param prefix The Namespace prefix being declared.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endPrefixMapping
*/
public void endPrefixMapping(String prefix)
throws SAXException {
if (DEBUG) {
System.out.println("endPrefixMapping prefix=" + prefix);
}
}
/**
* Receive notification of the start of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the start of
* each element (such as allocating a new tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @param attributes The attributes attached to the element. If
* there are no attributes, it shall be an empty
* Attributes object.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#startElement
*/
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
+ if (tech.className != null)
+ {
+ int index = tech.className.indexOf(".");
+ String realName = tech.className;
+ while (index != -1)
+ {
+ realName = realName.substring(index+1);
+ index = realName.indexOf(".");
+ }
+ if (!realName.toLowerCase().equals(tech.techName.toLowerCase()))
+ System.out.println("Mismatch between techName '" + tech.techName +
+ "' and className '" + realName + "' in the XML technology file.");
+ }
// dump = true;
break;
case version:
- Version version = new Version();
- version.techVersion = Integer.parseInt(a("tech"));
- version.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
- tech.versions.add(version);
+ Version localVersion = new Version();
+ localVersion.techVersion = Integer.parseInt(a("tech"));
+ localVersion.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
+ tech.versions.add(localVersion);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("function"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
DRCTemplate.parseXmlElement(curFoundry.rules, key.name(), attributes, localName);
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
private double da_(String attrName, double defaultValue) {
String s = a_(attrName);
return s != null ? Double.parseDouble(s) : defaultValue;
}
private String a(String attrName) {
String v = attributes.getValue(attrName);
// System.out.print(" " + attrName + "=\"" + v + "\"");
return v;
}
private String a_(String attrName) {
String v = attributes.getValue(attrName);
if (v == null) return null;
// System.out.print(" " + attrName + "=\"" + v + "\"");
return v;
}
/**
* Receive notification of the end of an element.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions at the end of
* each element (such as finalising a tree node or writing
* output to a file).</p>
*
* @param uri The Namespace URI, or the empty string if the
* element has no Namespace URI or if Namespace
* processing is not being performed.
* @param localName The local name (without prefix), or the
* empty string if Namespace processing is not being
* performed.
* @param qName The qualified name (with prefix), or the
* empty string if qualified names are not available.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#endElement
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
XmlKeyword key = xmlKeywords.get(localName);
if (key.hasText) {
String text = endCharacters();
// System.out.println(text + "</" + localName + ">");
switch (key) {
case shortName:
tech.shortTechName = text;
break;
case description:
tech.description = text;
break;
case r:
curR = Integer.parseInt(text);
break;
case g:
curG = Integer.parseInt(text);
break;
case b:
curB = Integer.parseInt(text);
break;
case patternedOnDisplay:
patternedOnDisplay = Boolean.parseBoolean(text);
break;
case patternedOnPrinter:
patternedOnPrinter = Boolean.parseBoolean(text);
break;
case pattern:
int p = 0;
assert text.length() == 16;
for (int j = 0; j < text.length(); j++) {
if (text.charAt(text.length() - j - 1) != ' ')
p |= (1 << j);
}
pattern[curPatternIndex++] = p;
break;
case outlined:
outline = EGraphics.Outline.valueOf(text);
break;
case opacity:
opacity = Double.parseDouble(text);
break;
case foreground:
foreground = Boolean.parseBoolean(text);
break;
case oldName:
if (curLayer != null) {
curLayer.pureLayerNode.oldName = text;
} else if (curArc != null) {
curArc.oldName = text;
} else {
curNode.oldName = text;
}
break;
case extended:
curArc.extended = Boolean.parseBoolean(text);
break;
case fixedAngle:
curArc.fixedAngle = Boolean.parseBoolean(text);
break;
case wipable:
curArc.wipable = Boolean.parseBoolean(text);
break;
case angleIncrement:
curArc.angleIncrement = Integer.parseInt(text);
break;
case antennaRatio:
curArc.antennaRatio = Double.parseDouble(text);
break;
case portTopology:
curPort.portTopology = Integer.parseInt(text);
break;
case portArc:
if (curLayer != null && curLayer.pureLayerNode != null)
curLayer.pureLayerNode.portArcs.add(text);
if (curPort != null)
curPort.portArcs.add(text);
break;
case specialValue:
curNodeGroup.specialValues[curSpecialValueIndex++] = Double.parseDouble(text);
break;
case menuArc:
ArcProto ap = tech.findArc(text);
if (ap == null) System.out.println("Warning: cannot find arc '" + text + "' for component menu"); else
curMenuBox.add(ap);
break;
case menuNode:
PrimitiveNode np = tech.findNode(text);
if (np == null) System.out.println("Warning: cannot find node '" + text + "' for component menu"); else
curMenuBox.add(np);
break;
case menuText:
curMenuBox.add(text);
break;
case lambda:
curDistance.addLambda(Double.parseDouble(text));
break;
default:
assert false;
}
return;
}
// System.out.println("</" + localName + ">");
switch (key) {
case technology:
break;
case transparentLayer:
while (curTransparent > tech.transparentLayers.size())
tech.transparentLayers.add(null);
Color oldColor = tech.transparentLayers.set(curTransparent - 1, new Color(curR, curG, curB));
assert oldColor == null;
break;
case layer:
assert curPatternIndex == pattern.length;
curLayer.desc = new EGraphics(patternedOnDisplay, patternedOnPrinter, outline, curTransparent,
curR, curG, curB, opacity, foreground, pattern.clone(), transparencyMode, transparencyFactor);
assert tech.findLayer(curLayer.name) == null;
tech.layers.add(curLayer);
curLayer = null;
break;
case arcProto:
tech.arcs.add(curArc);
curArc = null;
break;
case primitiveNodeGroup:
fixNodeBase();
tech.nodeGroups.add(curNodeGroup);
curNodeGroup = null;
curNode = null;
break;
case primitiveNode:
if (curNodeGroup.isSingleton) {
fixNodeBase();
tech.nodeGroups.add(curNodeGroup);
curNodeGroup = null;
curNode = null;
} else if (curNodeLayer == null) {
assert !curNodeGroup.isSingleton;
curNode = null;
}
break;
case nodeLayer:
curNodeGroup.nodeLayers.add(curNodeLayer);
curNodeLayer = null;
break;
case primitivePort:
curNodeGroup.ports.add(curPort);
curPort = null;
break;
case menuNodeInst:
curMenuBox.add(curMenuNodeInst);
curMenuNodeInst = null;
break;
case version:
case spiceHeader:
case numMetals:
case scale:
case resolution:
case defaultFoundry:
case minResistance:
case minCapacitance:
case logicalEffort:
case transparentColor:
case opaqueColor:
case display3D:
case cifLayer:
case skillLayer:
case parasitics:
case pureLayerNode:
case wipable:
case curvable:
case special:
case notUsed:
case skipSizeInPalette:
case diskOffset:
case defaultWidth:
case arcLayer:
case inNodes:
case shrinkArcs:
case square:
case canBeZeroSize:
case wipes:
case lockable:
case edgeSelect:
case lowVt:
case highVt:
case nativeBit:
case od18:
case od25:
case od33:
case defaultHeight:
case nodeBase:
case sizeOffset:
case protection:
case box:
case points:
case multicutbox:
case serpbox:
case lambdaBox:
case techPoint:
case portAngle:
case polygonal:
case serpTrans:
case minSizeRule:
case spiceLine:
case spiceTemplate:
case menuPalette:
case menuBox:
case menuNodeText:
case Foundry:
case layerGds:
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
break;
default:
assert false;
}
}
private void fixNodeBase() {
if (curNodeGroupHasNodeBase) return;
double lx, hx, ly, hy;
if (curNodeGroup.nodeSizeRule != null) {
hx = 0.5*curNodeGroup.nodeSizeRule.width;
lx = -hx;
hy = 0.5*curNodeGroup.nodeSizeRule.height;
ly = -hy;
} else {
lx = Double.POSITIVE_INFINITY;
hx = Double.NEGATIVE_INFINITY;
ly = Double.POSITIVE_INFINITY;
hy = Double.NEGATIVE_INFINITY;
for (int i = 0; i < curNodeGroup.nodeLayers.size(); i++) {
Xml.NodeLayer nl = curNodeGroup.nodeLayers.get(i);
double x, y;
if (nl.representation == com.sun.electric.technology.Technology.NodeLayer.BOX || nl.representation == com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX) {
x = nl.lx.value;
lx = Math.min(lx, x);
hx = Math.max(hx, x);
x = nl.hx.value;
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = nl.ly.value;
ly = Math.min(ly, y);
hy = Math.max(hy, y);
y = nl.hy.value;
ly = Math.min(ly, y);
hy = Math.max(hy, y);
} else {
for (com.sun.electric.technology.Technology.TechPoint p: nl.techPoints) {
x = p.getX().getAdder();
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = p.getY().getAdder();
ly = Math.min(ly, y);
hy = Math.max(hy, y);
}
}
}
}
curNodeGroup.baseLX.value = DBMath.round(lx + curNodeGroup.baseLX.value);
curNodeGroup.baseHX.value = DBMath.round(hx + curNodeGroup.baseHX.value);
curNodeGroup.baseLY.value = DBMath.round(ly + curNodeGroup.baseLY.value);
curNodeGroup.baseHY.value = DBMath.round(hy + curNodeGroup.baseHY.value);
}
/**
* Receive notification of character data inside an element.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of character data
* (such as adding the data to a node or buffer, or printing it to
* a file).</p>
*
* @param ch The characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#characters
*/
public void characters(char ch[], int start, int length)
throws SAXException {
if (acceptCharacters) {
charBuffer.append(ch, start, length);
} else {
boolean nonBlank = false;
for (int i = 0; i < length; i++) {
char c = ch[start + i];
nonBlank = nonBlank || c != ' ' && c != '\n' && c != '\t';
}
if (nonBlank) {
System.out.print("characters size=" + ch.length + " start=" + start + " length=" + length + " {");
for (int i = 0; i < length; i++)
System.out.print(ch[start + i]);
System.out.println("}");
}
}
}
/**
* Receive notification of ignorable whitespace in element content.
*
* <p>By default, do nothing. Application writers may override this
* method to take specific actions for each chunk of ignorable
* whitespace (such as adding data to a node or buffer, or printing
* it to a file).</p>
*
* @param ch The whitespace characters.
* @param start The start position in the character array.
* @param length The number of characters to use from the
* character array.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#ignorableWhitespace
*/
public void ignorableWhitespace(char ch[], int start, int length)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of a processing instruction.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param target The processing instruction target.
* @param data The processing instruction data, or null if
* none is supplied.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*/
public void processingInstruction(String target, String data)
throws SAXException {
// int x = 0;
}
/**
* Receive notification of a skipped entity.
*
* <p>By default, do nothing. Application writers may override this
* method in a subclass to take specific actions for each
* processing instruction, such as setting status variables or
* invoking other methods.</p>
*
* @param name The name of the skipped entity.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ContentHandler#processingInstruction
*/
public void skippedEntity(String name)
throws SAXException {
// int x = 0;
}
////////////////////////////////////////////////////////////////////
// Default implementation of the ErrorHandler interface.
////////////////////////////////////////////////////////////////////
/**
* Receive notification of a parser warning.
*
* <p>The default implementation does nothing. Application writers
* may override this method in a subclass to take specific actions
* for each warning, such as inserting the message in a log file or
* printing it to the console.</p>
*
* @param e The warning information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#warning
* @see org.xml.sax.SAXParseException
*/
public void warning(SAXParseException e)
throws SAXException {
System.out.println("warning publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
" line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
}
/**
* Receive notification of a recoverable parser error.
*
* <p>The default implementation does nothing. Application writers
* may override this method in a subclass to take specific actions
* for each error, such as inserting the message in a log file or
* printing it to the console.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#warning
* @see org.xml.sax.SAXParseException
*/
public void error(SAXParseException e)
throws SAXException {
// System.out.println("error publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
// " line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
throw e;
}
/**
* Report a fatal XML parsing error.
*
* <p>The default implementation throws a SAXParseException.
* Application writers may override this method in a subclass if
* they need to take specific actions for each fatal error (such as
* collecting all of the errors into a single report): in any case,
* the application must stop all regular processing when this
* method is invoked, since the document is no longer reliable, and
* the parser may no longer report parsing events.</p>
*
* @param e The error information encoded as an exception.
* @exception org.xml.sax.SAXException Any SAX exception, possibly
* wrapping another exception.
* @see org.xml.sax.ErrorHandler#fatalError
* @see org.xml.sax.SAXParseException
*/
public void fatalError(SAXParseException e)
throws SAXException {
// System.out.println("fatal error publicId=" + e.getPublicId() + " systemId=" + e.getSystemId() +
// " line=" + e.getLineNumber() + " column=" + e.getColumnNumber() + " message=" + e.getMessage() + " exception=" + e.getException());
throw e;
}
}
private static class Writer {
private static final int INDENT_WIDTH = 4;
protected final PrintWriter out;
private int indent;
protected boolean indentEmitted;
private Writer(PrintWriter out) {
this.out = out;
}
private void writeTechnology(Xml.Technology t, boolean includeDateAndVersion, String copyrightMessage) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
header();
pl("");
out.println("<!--");
pl(" *");
if (includeDateAndVersion)
{
pl(" * Electric(tm) VLSI Design System, version " + com.sun.electric.database.text.Version.getVersion());
} else
{
pl(" * Electric(tm) VLSI Design System");
}
pl(" *");
pl(" * File: " + t.techName + ".xml");
pl(" * " + t.techName + " technology description");
pl(" * Generated automatically from a library");
pl(" *");
if (copyrightMessage != null)
{
int start = 0;
while (start < copyrightMessage.length())
{
int endPos = copyrightMessage.indexOf('\n', start);
if (endPos < 0) endPos = copyrightMessage.length();
String oneLine = copyrightMessage.substring(start, endPos);
pl(" * " + oneLine);
start = endPos+1;
}
}
out.println("-->");
l();
b(XmlKeyword.technology); a("name", t.techName); a("class", t.className); l();
a("xmlns", "http://electric.sun.com/Technology"); l();
a("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); l();
a("xsi:schemaLocation", "http://electric.sun.com/Technology ../../technology/Technology.xsd"); cl();
l();
bcpel(XmlKeyword.shortName, t.shortTechName);
bcpel(XmlKeyword.description, t.description);
for (Version version: t.versions) {
b(XmlKeyword.version); a("tech", version.techVersion); a("electric", version.electricVersion); el();
}
b(XmlKeyword.numMetals); a("min", t.minNumMetals); a("max", t.maxNumMetals); a("default", t.defaultNumMetals); el();
b(XmlKeyword.scale); a("value", t.scaleValue); a("relevant", Boolean.valueOf(t.scaleRelevant)); el();
b(XmlKeyword.resolution); a("value", t.resolutionValue); el();
b(XmlKeyword.defaultFoundry); a("value", t.defaultFoundry); el();
b(XmlKeyword.minResistance); a("value", t.minResistance); el();
b(XmlKeyword.minCapacitance); a("value", t.minCapacitance); el();
if (t.leGateCapacitance != DEFAULT_LE_GATECAP || t.leWireRatio != DEFAULT_LE_WIRERATIO || t.leDiffAlpha != DEFAULT_LE_DIFFALPHA) {
b(XmlKeyword.logicalEffort);
a("gateCapacitance", t.leGateCapacitance);
a("wireRatio", t.leWireRatio);
a("diffAlpha", t.leDiffAlpha);
el();
}
// printlnAttribute(" gateLengthSubtraction", gi.gateShrinkage);
// printlnAttribute(" gateInclusion", gi.includeGateInResistance);
// printlnAttribute(" groundNetInclusion", gi.includeGround);
l();
if (t.transparentLayers.size() != 0) {
comment("Transparent layers");
for (int i = 0; i < t.transparentLayers.size(); i++) {
Color color = t.transparentLayers.get(i);
b(XmlKeyword.transparentLayer); a("transparent", i + 1); cl();
bcpel(XmlKeyword.r, color.getRed());
bcpel(XmlKeyword.g, color.getGreen());
bcpel(XmlKeyword.b, color.getBlue());
el(XmlKeyword.transparentLayer);
}
l();
}
comment("**************************************** LAYERS ****************************************");
for (Xml.Layer li: t.layers) {
writeXml(li);
}
comment("******************** ARCS ********************");
for (Xml.ArcProto ai: t.arcs) {
writeXml(ai);
l();
}
comment("******************** NODES ********************");
for (Xml.PrimitiveNodeGroup nodeGroup: t.nodeGroups) {
writeXml(nodeGroup);
l();
}
for (Xml.SpiceHeader spiceHeader: t.spiceHeaders)
writeSpiceHeaderXml(spiceHeader);
writeMenuPaletteXml(t.menuPalette);
for (Xml.Foundry foundry: t.foundries)
writeFoundryXml(foundry);
el(XmlKeyword.technology);
}
private void writeXml(Xml.Layer li) {
EGraphics desc = li.desc;
String funString = null;
int funExtra = li.extraFunction;
if (funExtra != 0) {
final int deplEnhMask = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.ENHANCEMENT;
if ((funExtra&deplEnhMask) != 0) {
funString = com.sun.electric.technology.Layer.Function.getExtraName(funExtra&(deplEnhMask));
funExtra &= ~deplEnhMask;
if (funExtra != 0)
funString += "_" + com.sun.electric.technology.Layer.Function.getExtraName(funExtra);
} else {
funString = com.sun.electric.technology.Layer.Function.getExtraName(funExtra);
}
}
b(XmlKeyword.layer); a("name", li.name); a("fun", li.function.name()); a("extraFun", funString); cl();
if (desc.getTransparentLayer() > 0) {
b(XmlKeyword.transparentColor); a("transparent", desc.getTransparentLayer()); el();
} else {
Color color = desc.getColor();
b(XmlKeyword.opaqueColor); a("r", color.getRed()); a("g", color.getGreen()); a("b", color.getBlue()); el();
}
bcpel(XmlKeyword.patternedOnDisplay, Boolean.valueOf(desc.isPatternedOnDisplay()));
bcpel(XmlKeyword.patternedOnPrinter, Boolean.valueOf(desc.isPatternedOnPrinter()));
int [] pattern = desc.getPattern();
for(int j=0; j<16; j++) {
String p = "";
for(int k=0; k<16; k++)
p += (pattern[j] & (1 << (15-k))) != 0 ? 'X' : ' ';
bcpel(XmlKeyword.pattern, p);
}
if (li.desc.getOutlined() != null)
bcpel(XmlKeyword.outlined, desc.getOutlined().getConstName());
bcpel(XmlKeyword.opacity, desc.getOpacity());
bcpel(XmlKeyword.foreground, Boolean.valueOf(desc.getForeground()));
// write the 3D information
b(XmlKeyword.display3D);
a("thick", li.thick3D); a("height", li.height3D);
a("mode", li.desc.getTransparencyMode());
a("factor", li.desc.getTransparencyFactor());
el();
if (li.cif != null && li.cif.length() > 0) {
b(XmlKeyword.cifLayer); a("cif", li.cif); el();
}
if (li.skill != null && li.skill.length() > 0) {
b(XmlKeyword.skillLayer); a("skill", li.skill); el();
}
// write the SPICE information
if (li.resistance != 0 || li.capacitance != 0 || li.edgeCapacitance != 0) {
b(XmlKeyword.parasitics); a("resistance", li.resistance); a("capacitance", li.capacitance); a("edgeCapacitance", li.edgeCapacitance); el();
}
if (li.pureLayerNode != null) {
String nodeName = li.pureLayerNode.name;
Poly.Type style = li.pureLayerNode.style;
String styleStr = style == Poly.Type.FILLED ? null : style.name();
String portName = li.pureLayerNode.port;
b(XmlKeyword.pureLayerNode); a("name", nodeName); a("style", styleStr); a("port", portName); cl();
bcpel(XmlKeyword.oldName, li.pureLayerNode.oldName);
bcpel(XmlKeyword.lambda, li.pureLayerNode.size.value);
for (String portArc: li.pureLayerNode.portArcs)
bcpel(XmlKeyword.portArc, portArc);
el(XmlKeyword.pureLayerNode);
}
el(XmlKeyword.layer);
l();
}
private void writeXml(Xml.ArcProto ai) {
b(XmlKeyword.arcProto); a("name", ai.name); a("fun", ai.function.getConstantName()); cl();
bcpel(XmlKeyword.oldName, ai.oldName);
if (ai.wipable)
bel(XmlKeyword.wipable);
if (ai.curvable)
bel(XmlKeyword.curvable);
if (ai.special)
bel(XmlKeyword.special);
if (ai.notUsed)
bel(XmlKeyword.notUsed);
if (ai.skipSizeInPalette)
bel(XmlKeyword.skipSizeInPalette);
bcpel(XmlKeyword.extended, Boolean.valueOf(ai.extended));
bcpel(XmlKeyword.fixedAngle, Boolean.valueOf(ai.fixedAngle));
bcpel(XmlKeyword.angleIncrement, ai.angleIncrement);
if (ai.antennaRatio != 0)
bcpel(XmlKeyword.antennaRatio, ai.antennaRatio);
for (Map.Entry<Integer,Double> e: ai.diskOffset.entrySet()) {
b(XmlKeyword.diskOffset); a("untilVersion", e.getKey()); a("width", e.getValue()); el();
}
if (ai.defaultWidth.value != 0) {
bcl(XmlKeyword.defaultWidth);
bcpel(XmlKeyword.lambda, ai.defaultWidth.value);
el(XmlKeyword.defaultWidth);
}
for (Xml.ArcLayer al: ai.arcLayers) {
String style = al.style == Poly.Type.FILLED ? "FILLED" : "CLOSED";
b(XmlKeyword.arcLayer); a("layer", al.layer); a("style", style);
double extend = al.extend.value;
if (extend == 0) {
el();
} else {
cl();
bcpel(XmlKeyword.lambda, extend);
el(XmlKeyword.arcLayer);
}
}
el(XmlKeyword.arcProto);
}
private void writeXml(Xml.PrimitiveNodeGroup ng) {
if (ng.isSingleton) {
PrimitiveNode n = ng.nodes.get(0);
b(XmlKeyword.primitiveNode); a("name", n.name); a("fun", n.function.name()); cl();
bcpel(XmlKeyword.oldName, n.oldName);
} else {
bcl(XmlKeyword.primitiveNodeGroup);
for (PrimitiveNode n: ng.nodes) {
b(XmlKeyword.primitiveNode); a("name", n.name); a("fun", n.function.name());
if (n.oldName != null || n.highVt || n.lowVt || n.nativeBit || n.od18 || n.od25 || n.od33) {
cl();
bcpel(XmlKeyword.oldName, n.oldName);
if (n.lowVt)
bel(XmlKeyword.lowVt);
if (n.highVt)
bel(XmlKeyword.highVt);
if (n.nativeBit)
bel(XmlKeyword.nativeBit);
if (n.od18)
bel(XmlKeyword.od18);
if (n.od25)
bel(XmlKeyword.od25);
if (n.od33)
bel(XmlKeyword.od33);
el(XmlKeyword.primitiveNode);
} else {
el();
}
}
}
if (ng.shrinkArcs)
bel(XmlKeyword.shrinkArcs);
if (ng.square)
bel(XmlKeyword.square);
if (ng.canBeZeroSize)
bel(XmlKeyword.canBeZeroSize);
if (ng.wipes)
bel(XmlKeyword.wipes);
if (ng.lockable)
bel(XmlKeyword.lockable);
if (ng.edgeSelect)
bel(XmlKeyword.edgeSelect);
if (ng.skipSizeInPalette)
bel(XmlKeyword.skipSizeInPalette);
if (ng.notUsed)
bel(XmlKeyword.notUsed);
if (ng.isSingleton) {
PrimitiveNode n = ng.nodes.get(0);
if (n.lowVt)
bel(XmlKeyword.lowVt);
if (n.highVt)
bel(XmlKeyword.highVt);
if (n.nativeBit)
bel(XmlKeyword.nativeBit);
if (n.od18)
bel(XmlKeyword.od18);
if (n.od25)
bel(XmlKeyword.od25);
if (n.od33)
bel(XmlKeyword.od33);
}
for (Map.Entry<Integer,EPoint> e: ng.diskOffset.entrySet()) {
EPoint p = e.getValue();
b(XmlKeyword.diskOffset); a("untilVersion", e.getKey()); a("x", p.getLambdaX()); a("y", p.getLambdaY()); el();
}
if (ng.defaultWidth.value != 0) {
bcl(XmlKeyword.defaultWidth);
bcpel(XmlKeyword.lambda, ng.defaultWidth.value);
el(XmlKeyword.defaultWidth);
}
if (ng.defaultHeight.value != 0) {
bcl(XmlKeyword.defaultHeight);
bcpel(XmlKeyword.lambda, ng.defaultHeight.value);
el(XmlKeyword.defaultHeight);
}
bcl(XmlKeyword.nodeBase);
bcl(XmlKeyword.box);
b(XmlKeyword.lambdaBox); a("klx", ng.baseLX.value); a("khx", ng.baseHX.value); a("kly", ng.baseLY.value); a("khy", ng.baseHY.value); el();
el(XmlKeyword.box);
el(XmlKeyword.nodeBase);
if (ng.protection != null) {
b(XmlKeyword.protection); a("location", ng.protection); el();
}
for(int j=0; j<ng.nodeLayers.size(); j++) {
Xml.NodeLayer nl = ng.nodeLayers.get(j);
b(XmlKeyword.nodeLayer); a("layer", nl.layer); a("style", nl.style.name());
if (nl.portNum != 0) a("portNum", Integer.valueOf(nl.portNum));
if (!(nl.inLayers && nl.inElectricalLayers))
a("electrical", Boolean.valueOf(nl.inElectricalLayers));
cl();
if (nl.inNodes != null) {
assert !ng.isSingleton;
bcl(XmlKeyword.inNodes);
for (int i = 0; i < ng.nodes.size(); i++) {
if (nl.inNodes.get(i)) {
b(XmlKeyword.primitiveNode); a("name", ng.nodes.get(i).name); el();
}
}
el(XmlKeyword.inNodes);
}
switch (nl.representation) {
case com.sun.electric.technology.Technology.NodeLayer.BOX:
if (ng.specialType == com.sun.electric.technology.PrimitiveNode.SERPTRANS) {
writeBox(XmlKeyword.serpbox, nl.lx, nl.hx, nl.ly, nl.hy);
a("lWidth", nl.lWidth); a("rWidth", nl.rWidth); a("tExtent", nl.tExtent); a("bExtent", nl.bExtent); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.serpbox);
} else {
writeBox(XmlKeyword.box, nl.lx, nl.hx, nl.ly, nl.hy); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.box);
}
break;
case com.sun.electric.technology.Technology.NodeLayer.POINTS:
b(XmlKeyword.points); el();
break;
case com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX:
writeBox(XmlKeyword.multicutbox, nl.lx, nl.hx, nl.ly, nl.hy);
a("sizex", nl.sizex); a("sizey", nl.sizey); a("sep1d", nl.sep1d); a("sep2d", nl.sep2d); cl();
b(XmlKeyword.lambdaBox); a("klx", nl.lx.value); a("khx", nl.hx.value); a("kly", nl.ly.value); a("khy", nl.hy.value); el();
el(XmlKeyword.multicutbox);
break;
}
for (TechPoint tp: nl.techPoints) {
double xm = tp.getX().getMultiplier();
double xa = tp.getX().getAdder();
double ym = tp.getY().getMultiplier();
double ya = tp.getY().getAdder();
b(XmlKeyword.techPoint); a("xm", xm); a("xa", xa); a("ym", ym); a("ya", ya); el();
}
el(XmlKeyword.nodeLayer);
}
for (int j = 0; j < ng.ports.size(); j++) {
Xml.PrimitivePort pd = ng.ports.get(j);
b(XmlKeyword.primitivePort); a("name", pd.name); cl();
b(XmlKeyword.portAngle); a("primary", pd.portAngle); a("range", pd.portRange); el();
bcpel(XmlKeyword.portTopology, pd.portTopology);
writeBox(XmlKeyword.box, pd.lx, pd.hx, pd.ly, pd.hy); cl();
b(XmlKeyword.lambdaBox); a("klx", pd.lx.value); a("khx", pd.hx.value); a("kly", pd.ly.value); a("khy", pd.hy.value); el();
el(XmlKeyword.box);
for (String portArc: pd.portArcs)
bcpel(XmlKeyword.portArc, portArc);
el(XmlKeyword.primitivePort);
}
switch (ng.specialType) {
case com.sun.electric.technology.PrimitiveNode.POLYGONAL:
bel(XmlKeyword.polygonal);
break;
case com.sun.electric.technology.PrimitiveNode.SERPTRANS:
b(XmlKeyword.serpTrans); cl();
for (int i = 0; i < 6; i++) {
bcpel(XmlKeyword.specialValue, ng.specialValues[i]);
}
el(XmlKeyword.serpTrans);
break;
}
if (ng.nodeSizeRule != null) {
NodeSizeRule r = ng.nodeSizeRule;
b(XmlKeyword.minSizeRule); a("width", r.width); a("height", r.height); a("rule", r.rule); el();
}
if (ng.spiceTemplate != null)
{
b(XmlKeyword.spiceTemplate); a("value", ng.spiceTemplate); el();
}
el(ng.isSingleton ? XmlKeyword.primitiveNode : XmlKeyword.primitiveNodeGroup);
}
private void writeBox(XmlKeyword keyword, Distance lx, Distance hx, Distance ly, Distance hy) {
b(keyword);
if (lx.k != -1) a("klx", lx.k);
if (hx.k != 1) a("khx", hx.k);
if (ly.k != -1) a("kly", ly.k);
if (hy.k != 1) a("khy", hy.k);
}
private void writeSpiceHeaderXml(Xml.SpiceHeader spiceHeader) {
b(XmlKeyword.spiceHeader); a("level", spiceHeader.level); cl();
for (String line: spiceHeader.spiceLines) {
b(XmlKeyword.spiceLine); a("line", line); el();
}
el(XmlKeyword.spiceHeader);
l();
}
public void writeMenuPaletteXml(Xml.MenuPalette menuPalette) {
if (menuPalette == null) return;
b(XmlKeyword.menuPalette); a("numColumns", menuPalette.numColumns); cl();
for (int i = 0; i < menuPalette.menuBoxes.size(); i++) {
if (i % menuPalette.numColumns == 0)
l();
writeMenuBoxXml(menuPalette.menuBoxes.get(i));
}
l();
el(XmlKeyword.menuPalette);
l();
}
private void writeMenuBoxXml(List<?> list) {
b(XmlKeyword.menuBox);
if (list == null || list.size() == 0) {
el();
return;
}
cl();
for (Object o: list) {
if (o instanceof Xml.ArcProto) {
bcpel(XmlKeyword.menuArc, ((Xml.ArcProto)o).name);
} else if (o instanceof Xml.PrimitiveNode) {
bcpel(XmlKeyword.menuNode, ((Xml.PrimitiveNode)o).name);
} else if (o instanceof Xml.MenuNodeInst) {
Xml.MenuNodeInst ni = (Xml.MenuNodeInst)o;
b(XmlKeyword.menuNodeInst); a("protoName", ni.protoName); a("function", ni.function.name());
if (ni.techBits != 0) a("techBits", ni.techBits);
if (ni.rotation != 0) a("rotation", ni.rotation);
if (ni.text == null) {
el();
} else {
cl();
b(XmlKeyword.menuNodeText); a("text", ni.text); /*a("size", ni.fontSize);*/ el();
el(XmlKeyword.menuNodeInst);
}
} else {
if (o == null) bel(XmlKeyword.menuText); else
bcpel(XmlKeyword.menuText, o);
}
}
el(XmlKeyword.menuBox);
}
private void writeFoundryXml(Xml.Foundry foundry) {
b(XmlKeyword.Foundry); a("name", foundry.name); cl();
l();
for (Map.Entry<String,String> e: foundry.layerGds.entrySet()) {
b(XmlKeyword.layerGds); a("layer", e.getKey()); a("gds", e.getValue()); el();
}
l();
for (DRCTemplate rule: foundry.rules)
DRCTemplate.exportDRCRule(out, rule);
el(XmlKeyword.Foundry);
}
private void header() {
checkIndent();
out.print("<?xml"); a("version", "1.0"); a("encoding", "UTF-8"); out.println("?>");
}
private void comment(String s) {
checkIndent();
out.print("<!-- "); p(s); out.print(" -->"); l();
}
/**
* Print attribute.
*/
private void a(String name, Object value) {
checkIndent();
if (value == null) return;
out.print(" " + name + "=\"");
p(value.toString());
out.print("\"");
}
private void a(String name, double value) { a(name, new Double(value)); }
private void a(String name, int value) { a(name, new Integer(value)); }
private void bcpel(XmlKeyword key, Object v) {
if (v == null) return;
b(key); c(); p(v.toString()); el(key);
}
private void bcpel(XmlKeyword key, int v) { bcpel(key, new Integer(v)); }
private void bcpel(XmlKeyword key, double v) { bcpel(key, new Double(v)); }
private void bcl(XmlKeyword key) {
b(key); cl();
}
private void bel(XmlKeyword key) {
b(key); el();
}
/**
* Print text with replacement of special chars.
*/
private void pl(String s) {
checkIndent();
p(s); l();
}
/**
* Print text with replacement of special chars.
*/
protected void p(String s) {
assert indentEmitted;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '<':
out.print("<");
break;
case '>':
out.print(">");
break;
case '&':
out.print("&");
break;
case '\'':
out.print("'");
break;
case '"':
out.print("quot;");
break;
default:
out.print(c);
}
}
}
/**
* Print element name, and indent.
*/
private void b(XmlKeyword key) {
checkIndent();
out.print('<');
out.print(key.name());
indent += INDENT_WIDTH;
}
private void cl() {
assert indentEmitted;
out.print('>');
l();
}
private void c() {
assert indentEmitted;
out.print('>');
}
private void el() {
e(); l();
}
private void e() {
assert indentEmitted;
out.print("/>");
indent -= INDENT_WIDTH;
}
private void el(XmlKeyword key) {
indent -= INDENT_WIDTH;
checkIndent();
out.print("</");
out.print(key.name());
out.print(">");
l();
}
protected void checkIndent() {
if (indentEmitted) return;
for (int i = 0; i < indent; i++)
out.print(' ');
indentEmitted = true;
}
/**
* Print new line.
*/
protected void l() {
out.println();
indentEmitted = false;
}
}
/**
* Class to write the XML without multiple lines and indentation.
* Useful when the XML is to be a single string.
*/
private static class OneLineWriter extends Writer
{
private OneLineWriter(PrintWriter out)
{
super(out);
}
/**
* Print text without replacement of special chars.
*/
@Override
protected void p(String s)
{
for (int i = 0; i < s.length(); i++)
out.print(s.charAt(i));
}
@Override
protected void checkIndent() { indentEmitted = true; }
/**
* Do not print new line.
*/
@Override
protected void l() { indentEmitted = false; }
}
}
| false | true | public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
// dump = true;
break;
case version:
Version version = new Version();
version.techVersion = Integer.parseInt(a("tech"));
version.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
tech.versions.add(version);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("function"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
DRCTemplate.parseXmlElement(curFoundry.rules, key.name(), attributes, localName);
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
| public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
boolean dump = false;
XmlKeyword key = xmlKeywords.get(localName);
// System.out.print("<" + key.name());
this.attributes = attributes;
switch (key) {
case technology:
tech.techName = a("name");
tech.className = a_("class");
if (tech.className != null)
{
int index = tech.className.indexOf(".");
String realName = tech.className;
while (index != -1)
{
realName = realName.substring(index+1);
index = realName.indexOf(".");
}
if (!realName.toLowerCase().equals(tech.techName.toLowerCase()))
System.out.println("Mismatch between techName '" + tech.techName +
"' and className '" + realName + "' in the XML technology file.");
}
// dump = true;
break;
case version:
Version localVersion = new Version();
localVersion.techVersion = Integer.parseInt(a("tech"));
localVersion.electricVersion = com.sun.electric.database.text.Version.parseVersion(a("electric"));
tech.versions.add(localVersion);
break;
case numMetals:
tech.minNumMetals = Integer.parseInt(a("min"));
tech.maxNumMetals = Integer.parseInt(a("max"));
tech.defaultNumMetals = Integer.parseInt(a("default"));
break;
case scale:
tech.scaleValue = Double.parseDouble(a("value"));
tech.scaleRelevant = Boolean.parseBoolean(a("relevant"));
break;
case resolution:
tech.resolutionValue = Double.parseDouble(a("value")); // default is 0;
break;
case defaultFoundry:
tech.defaultFoundry = a("value");
break;
case minResistance:
tech.minResistance = Double.parseDouble(a("value"));
break;
case minCapacitance:
tech.minCapacitance = Double.parseDouble(a("value"));
break;
case logicalEffort:
tech.leGateCapacitance = Double.parseDouble(a("gateCapacitance"));
tech.leWireRatio = Double.parseDouble(a("wireRatio"));
tech.leDiffAlpha = Double.parseDouble(a("diffAlpha"));
break;
case transparentLayer:
curTransparent = Integer.parseInt(a("transparent"));
curR = curG = curB = 0;
break;
case layer:
curLayer = new Layer();
curLayer.name = a("name");
curLayer.function = com.sun.electric.technology.Layer.Function.valueOf(a("fun"));
String extraFunStr = a_("extraFun");
if (extraFunStr != null) {
if (extraFunStr.equals("depletion_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("depletion_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.DEPLETION|com.sun.electric.technology.Layer.Function.LIGHT;
else if (extraFunStr.equals("enhancement_heavy"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.HEAVY;
else if (extraFunStr.equals("enhancement_light"))
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.ENHANCEMENT|com.sun.electric.technology.Layer.Function.LIGHT;
else
curLayer.extraFunction = com.sun.electric.technology.Layer.Function.parseExtraName(extraFunStr);
}
curTransparent = 0;
curR = curG = curB = 0;
patternedOnDisplay = false;
patternedOnPrinter = false;
Arrays.fill(pattern, 0);
curPatternIndex = 0;
transparencyMode = EGraphics.DEFAULT_MODE;
transparencyFactor = EGraphics.DEFAULT_FACTOR;
// EGraphics.Outline outline = null;
break;
case transparentColor:
curTransparent = Integer.parseInt(a("transparent"));
if (curTransparent > 0) {
Color color = tech.transparentLayers.get(curTransparent - 1);
curR = color.getRed();
curG = color.getGreen();
curB = color.getBlue();
}
break;
case opaqueColor:
curR = Integer.parseInt(a("r"));
curG = Integer.parseInt(a("g"));
curB = Integer.parseInt(a("b"));
break;
case display3D:
curLayer.thick3D = Double.parseDouble(a("thick"));
curLayer.height3D = Double.parseDouble(a("height"));
String modeStr = a_("mode");
if (modeStr != null)
transparencyMode = EGraphics.J3DTransparencyOption.valueOf(modeStr);
String factorStr = a_("factor");
if (factorStr != null)
transparencyFactor = Double.parseDouble(factorStr);
break;
case cifLayer:
curLayer.cif = a("cif");
break;
case skillLayer:
curLayer.skill = a("skill");
break;
case parasitics:
curLayer.resistance = Double.parseDouble(a("resistance"));
curLayer.capacitance = Double.parseDouble(a("capacitance"));
curLayer.edgeCapacitance = Double.parseDouble(a("edgeCapacitance"));
break;
case pureLayerNode:
curLayer.pureLayerNode = new PureLayerNode();
curLayer.pureLayerNode.name = a("name");
String styleStr = a_("style");
curLayer.pureLayerNode.style = styleStr != null ? Poly.Type.valueOf(styleStr) : Poly.Type.FILLED;
curLayer.pureLayerNode.port = a("port");
curDistance = curLayer.pureLayerNode.size;
break;
case arcProto:
curArc = new ArcProto();
curArc.name = a("name");
curArc.function = com.sun.electric.technology.ArcProto.Function.valueOf(a("fun"));
break;
case wipable:
curArc.wipable = true;
break;
case curvable:
curArc.curvable = true;
break;
case special:
curArc.special = true;
break;
case notUsed:
if (curArc != null)
curArc.notUsed = true;
else if (curNodeGroup != null)
curNodeGroup.notUsed = true;
break;
case skipSizeInPalette:
if (curArc != null)
curArc.skipSizeInPalette = true;
else if (curNodeGroup != null)
curNodeGroup.skipSizeInPalette = true;
break;
case diskOffset:
if (curArc != null)
curArc.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
new Double(Double.parseDouble(a("width"))));
else if (curNodeGroup != null)
curNodeGroup.diskOffset.put(new Integer(Integer.parseInt(a("untilVersion"))),
EPoint.fromLambda(Double.parseDouble(a("x")), Double.parseDouble(a("y"))));
break;
case defaultWidth:
if (curArc != null)
curDistance = curArc.defaultWidth;
else if (curNodeGroup != null)
curDistance = curNodeGroup.defaultWidth;
break;
case arcLayer:
ArcLayer arcLayer = new ArcLayer();
arcLayer.layer = a("layer");
curDistance = arcLayer.extend;
arcLayer.style = Poly.Type.valueOf(a("style"));
curArc.arcLayers.add(arcLayer);
break;
case primitiveNodeGroup:
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNode = null;
if (a_("name") != null)
System.out.println("Attribute 'name' in <primitiveNodeGroup> is deprecated");
if (a_("fun") != null)
System.out.println("Attribute 'fun' in <primitiveNodeGroup> is deprecated");
break;
case inNodes:
if (curNodeGroup.isSingleton)
throw new SAXException("<inNodes> can be used only inside <primitiveNodeGroup>");
curNodeLayer.inNodes = new BitSet();
break;
case primitiveNode:
if (curNodeLayer != null) {
assert !curNodeGroup.isSingleton && curNode == null;
String nodeName = a("name");
int i = 0;
while (i < curNodeGroup.nodes.size() && !curNodeGroup.nodes.get(i).name.equals(nodeName))
i++;
if (i >= curNodeGroup.nodes.size())
throw new SAXException("No node "+nodeName+" in group");
curNodeLayer.inNodes.set(i);
} else if (curNodeGroup != null) {
assert !curNodeGroup.isSingleton;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
} else {
curNodeGroup = new PrimitiveNodeGroup();
curNodeGroupHasNodeBase = false;
curNodeGroup.isSingleton = true;
curNode = new PrimitiveNode();
curNode.name = a("name");
curNode.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("fun"));
curNodeGroup.nodes.add(curNode);
}
break;
case shrinkArcs:
curNodeGroup.shrinkArcs = true;
break;
case square:
curNodeGroup.square = true;
break;
case canBeZeroSize:
curNodeGroup.canBeZeroSize = true;
break;
case wipes:
curNodeGroup.wipes = true;
break;
case lockable:
curNodeGroup.lockable = true;
break;
case edgeSelect:
curNodeGroup.edgeSelect = true;
break;
case lowVt:
curNode.lowVt = true;
break;
case highVt:
curNode.highVt = true;
break;
case nativeBit:
curNode.nativeBit = true;
break;
case od18:
curNode.od18 = true;
break;
case od25:
curNode.od25 = true;
break;
case od33:
curNode.od33 = true;
break;
case defaultHeight:
curDistance = curNodeGroup.defaultHeight;
break;
case nodeBase:
curNodeGroupHasNodeBase = true;
break;
case sizeOffset:
curNodeGroup.baseLX.value = Double.parseDouble(a("lx"));
curNodeGroup.baseHX.value = -Double.parseDouble(a("hx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("ly"));
curNodeGroup.baseHY.value = -Double.parseDouble(a("hy"));
break;
case protection:
curNodeGroup.protection = ProtectionType.valueOf(a("location"));
break;
case nodeLayer:
curNodeLayer = new NodeLayer();
curNodeLayer.layer = a("layer");
curNodeLayer.style = Poly.Type.valueOf(a("style"));
String portNum = a_("portNum");
if (portNum != null)
curNodeLayer.portNum = Integer.parseInt(portNum);
String electrical = a_("electrical");
if (electrical != null) {
if (Boolean.parseBoolean(electrical))
curNodeLayer.inElectricalLayers = true;
else
curNodeLayer.inLayers = true;
} else {
curNodeLayer.inElectricalLayers = curNodeLayer.inLayers = true;
}
break;
case box:
if (curNodeLayer != null) {
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
} else if (curPort != null) {
curPort.lx.k = da_("klx", -1);
curPort.hx.k = da_("khx", 1);
curPort.ly.k = da_("kly", -1);
curPort.hy.k = da_("khy", 1);
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.k = curNodeGroup.baseLY.k = -1;
curNodeGroup.baseHX.k = curNodeGroup.baseHY.k = 1;
}
break;
case points:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.POINTS;
break;
case multicutbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.MULTICUTBOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.sizex = Double.parseDouble(a("sizex"));
curNodeLayer.sizey = Double.parseDouble(a("sizey"));
curNodeLayer.sep1d = Double.parseDouble(a("sep1d"));
curNodeLayer.sep2d = Double.parseDouble(a("sep2d"));
break;
case serpbox:
curNodeLayer.representation = com.sun.electric.technology.Technology.NodeLayer.BOX;
curNodeLayer.lx.k = da_("klx", -1);
curNodeLayer.hx.k = da_("khx", 1);
curNodeLayer.ly.k = da_("kly", -1);
curNodeLayer.hy.k = da_("khy", 1);
curNodeLayer.lWidth = Double.parseDouble(a("lWidth"));
curNodeLayer.rWidth = Double.parseDouble(a("rWidth"));
curNodeLayer.tExtent = Double.parseDouble(a("tExtent"));
curNodeLayer.bExtent = Double.parseDouble(a("bExtent"));
break;
case lambdaBox:
if (curNodeLayer != null) {
curNodeLayer.lx.value = Double.parseDouble(a("klx"));
curNodeLayer.hx.value = Double.parseDouble(a("khx"));
curNodeLayer.ly.value = Double.parseDouble(a("kly"));
curNodeLayer.hy.value = Double.parseDouble(a("khy"));
} else if (curPort != null) {
curPort.lx.value = Double.parseDouble(a("klx"));
curPort.hx.value = Double.parseDouble(a("khx"));
curPort.ly.value = Double.parseDouble(a("kly"));
curPort.hy.value = Double.parseDouble(a("khy"));
} else {
assert curNodeGroupHasNodeBase;
curNodeGroup.baseLX.value = Double.parseDouble(a("klx"));
curNodeGroup.baseHX.value = Double.parseDouble(a("khx"));
curNodeGroup.baseLY.value = Double.parseDouble(a("kly"));
curNodeGroup.baseHY.value = Double.parseDouble(a("khy"));
}
break;
case techPoint:
double xm = Double.parseDouble(a("xm"));
double xa = Double.parseDouble(a("xa"));
double ym = Double.parseDouble(a("ym"));
double ya = Double.parseDouble(a("ya"));
TechPoint p = new TechPoint(new EdgeH(xm, xa), new EdgeV(ym, ya));
if (curNodeLayer != null)
curNodeLayer.techPoints.add(p);
break;
case primitivePort:
curPort = new PrimitivePort();
curPort.name = a("name");
break;
case portAngle:
curPort.portAngle = Integer.parseInt(a("primary"));
curPort.portRange = Integer.parseInt(a("range"));
break;
case polygonal:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.POLYGONAL;
break;
case serpTrans:
curNodeGroup.specialType = com.sun.electric.technology.PrimitiveNode.SERPTRANS;
curNodeGroup.specialValues = new double[6];
curSpecialValueIndex = 0;
break;
case minSizeRule:
curNodeGroup.nodeSizeRule = new NodeSizeRule();
curNodeGroup.nodeSizeRule.width = Double.parseDouble(a("width"));
curNodeGroup.nodeSizeRule.height = Double.parseDouble(a("height"));
curNodeGroup.nodeSizeRule.rule = a("rule");
break;
case spiceTemplate:
curNodeGroup.spiceTemplate = a("value");
break;
case spiceHeader:
curSpiceHeader = new SpiceHeader();
curSpiceHeader.level = Integer.parseInt(a("level"));
tech.spiceHeaders.add(curSpiceHeader);
break;
case spiceLine:
curSpiceHeader.spiceLines.add(a("line"));
break;
case menuPalette:
tech.menuPalette = new MenuPalette();
tech.menuPalette.numColumns = Integer.parseInt(a("numColumns"));
break;
case menuBox:
curMenuBox = new ArrayList<Object>();
tech.menuPalette.menuBoxes.add(curMenuBox);
break;
case menuNodeInst:
curMenuNodeInst = new MenuNodeInst();
curMenuNodeInst.protoName = a("protoName");
if (tech.findNode(curMenuNodeInst.protoName) == null)
System.out.println("Warning: cannot find node '" + curMenuNodeInst.protoName + "' for component menu");
curMenuNodeInst.function = com.sun.electric.technology.PrimitiveNode.Function.valueOf(a("function"));
String techBits = a_("techBits");
if (techBits != null)
curMenuNodeInst.techBits = Integer.parseInt(techBits);
String rotField = a_("rotation");
if (rotField != null) curMenuNodeInst.rotation = Integer.parseInt(rotField);
break;
case menuNodeText:
curMenuNodeInst.text = a("text");
// curMenuNodeInst.fontSize = Double.parseDouble(a("size"));
break;
case Foundry:
curFoundry = new Foundry();
curFoundry.name = a("name");
tech.foundries.add(curFoundry);
break;
case layerGds:
curFoundry.layerGds.put(a("layer"), a("gds"));
break;
case LayerRule:
case LayersRule:
case NodeLayersRule:
case NodeRule:
DRCTemplate.parseXmlElement(curFoundry.rules, key.name(), attributes, localName);
break;
default:
assert key.hasText;
beginCharacters();
// System.out.print(">");
return;
}
assert !key.hasText;
// System.out.println(">");
if (dump) {
System.out.println("startElement uri=" + uri + " localName=" + localName + " qName=" + qName);
for (int i = 0; i < attributes.getLength(); i++) {
System.out.println("\tattribute " + i + " uri=" + attributes.getURI(i) +
" localName=" + attributes.getLocalName(i) + " QName=" + attributes.getQName(i) +
" type=" + attributes.getType(i) + " value=<" + attributes.getValue(i) + ">");
}
}
}
|
diff --git a/src/org/community/intellij/plugins/communitycase/commands/FileUtils.java b/src/org/community/intellij/plugins/communitycase/commands/FileUtils.java
index 9349124..6e1cc6e 100644
--- a/src/org/community/intellij/plugins/communitycase/commands/FileUtils.java
+++ b/src/org/community/intellij/plugins/communitycase/commands/FileUtils.java
@@ -1,296 +1,296 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.community.intellij.plugins.communitycase.commands;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import org.community.intellij.plugins.communitycase.Util;
import org.community.intellij.plugins.communitycase.i18n.Bundle;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
/**
* File utilities
*/
public class FileUtils {
/**
* If multiple paths are specified on the command line, this limit is used to split paths into chunks.
* The limit is less than OS limit to leave space to quoting, spaces, charset conversion, and commands arguments.
*/
public static final int FILE_PATH_LIMIT = 7600;
/**
* The private constructor for static utility class
*/
private FileUtils() {
// do nothing
}
/**
* Chunk paths on the command line
*
* @param files the paths to chunk
* @return the a list of list of relative paths
*/
public static List<List<String>> chunkRelativePaths(List<String> files) {
ArrayList<List<String>> rc = new ArrayList<List<String>>();
int start = 0;
int size = 0;
int i = 0;
for (; i < files.size(); i++) {
String p = files.get(i);
if (size + p.length() > FILE_PATH_LIMIT) {
if (start == i) {
rc.add(files.subList(i, i + 1));
start = i + 1;
}
else {
rc.add(files.subList(start, i));
start = i;
}
size = 0;
}
else {
size += p.length();
}
}
if (start != files.size()) {
rc.add(files.subList(start, i));
}
return rc;
}
/**
* The chunk paths
*
* @param root the vcs root
* @param files the file list
* @return chunked relative paths
*/
public static List<List<String>> chunkPaths(VirtualFile root, Collection<FilePath> files) {
return chunkRelativePaths(Util.toRelativePaths(root, files));
}
/**
* The chunk paths
*
* @param root the vcs root
* @param files the file list
* @return chunked relative paths
*/
public static List<List<String>> chunkFiles(VirtualFile root, Collection<VirtualFile> files) {
return chunkRelativePaths(Util.toRelativeFiles(root, files));
}
/**
* Delete files
*
* @param project the project
* @param root a vcs root
* @param files files to delete
* @param additionalOptions the additional options to add to the command line
* @throws VcsException in case of git problem
*/
public static void delete(Project project, VirtualFile root, Collection<FilePath> files, String... additionalOptions)
throws VcsException {
for (List<String> paths : chunkPaths(root, files)) {
SimpleHandler handler = new SimpleHandler(project, root, Command.RM);
handler.addParameters(additionalOptions);
handler.endOptions();
handler.addParameters(paths);
handler.setRemote(true);
handler.run();
}
}
public static void cherryPick(final Project project, final VirtualFile root, final String hash) throws VcsException {
SimpleHandler handler = new SimpleHandler(project, root, Command.CHERRY_PICK);
handler.addParameters("-x", "-n", hash);
handler.endOptions();
//handler.addRelativePaths(new FilePathImpl(root));
handler.setRemote(true);
handler.run();
}
/**
* Delete files
*
* @param project the project
* @param root a vcs root
* @param files files to delete
* @throws VcsException in case of git problem
*/
public static void deleteFiles(Project project, VirtualFile root, List<VirtualFile> files) throws VcsException {
for (List<String> paths : chunkFiles(root, files)) {
SimpleHandler handler = new SimpleHandler(project, root, Command.RM);
handler.endOptions();
handler.addParameters(paths);
handler.setRemote(true);
handler.run();
}
}
/**
* Delete files
*
* @param project the project
* @param root a vcs root
* @param files files to delete
* @throws VcsException in case of git problem
*/
public static void deleteFiles(Project project, VirtualFile root, VirtualFile... files) throws VcsException {
deleteFiles(project, root, Arrays.asList(files));
}
/**
* Add/index files
*
* @param project the project
* @param root a vcs root
* @param files files to add
* @throws VcsException in case of git problem
*/
public static void addFiles(Project project, VirtualFile root, Collection<VirtualFile> files) throws VcsException {
Collection<VirtualFile> dirs=new HashSet<VirtualFile>();
for(VirtualFile f:files)
dirs.add(f.getParent());
for(List<String> paths : chunkFiles(root, dirs)) {
SimpleHandler handler=new SimpleHandler(project, root, Command.CHECKOUT);
handler.addParameters("-nc");
handler.endOptions();
handler.addParameters(paths);
handler.setRemote(true);
handler.run();
}
for(List<String> paths : chunkFiles(root, files)) {
SimpleHandler handler=new SimpleHandler(project, root, Command.ADD);
handler.addParameters("-nc");
handler.endOptions();
handler.addParameters(paths);
handler.setRemote(true);
handler.run();
}
}
/**
* Add/index files
*
* @param project the project
* @param root a vcs root
* @param files files to add
* @throws VcsException in case of git problem
*/
public static void addFiles(Project project, VirtualFile root, VirtualFile... files) throws VcsException {
addFiles(project, root, Arrays.asList(files));
}
/**
* Add/index files
*
* @param project the project
* @param root a vcs root
* @param files files to add
* @throws VcsException in case of git problem
*/
public static void addPaths(Project project, VirtualFile root, Collection<FilePath> files) throws VcsException {
for (List<String> paths : chunkPaths(root, files)) {
SimpleHandler handler = new SimpleHandler(project, root, Command.ADD);
handler.addParameters("-nc");
handler.endOptions();
handler.addParameters(paths);
handler.setRemote(true);
handler.run();
}
}
/**
* Get file content for the specific revision
*
* @param project the project
* @param root the vcs root
* @param revisionOrBranch the revision to find path in or branch
* @param relativePath the relative path
* @return the content of file if file is found, null if the file is missing in the revision
* @throws VcsException if there is a problem with running git
*/
@Nullable
public static byte[] getFileContent(Project project, VirtualFile root, String revisionOrBranch, String relativePath) throws VcsException {
BinaryHandler h = new BinaryHandler(project, root, Command.SHOW);
h.setRemote(true);
h.setSilent(true);
File temp;
try {
- temp = FileUtil.createTempFile(relativePath.replaceAll("\\.","-")+revisionOrBranch.replaceAll("\\\\","-"), "tmp");
+ temp = FileUtil.createTempFile(relativePath.replaceAll("\\.","-")+revisionOrBranch.replaceAll("\\\\|/","-"), "tmp");
} catch(IOException e) {
throw new VcsException(e);
}
if(temp.exists()) {
//noinspection ResultOfMethodCallIgnored
temp.delete();
}
temp.deleteOnExit();
h.addParameters("-to "+temp.getAbsolutePath());
h.addParameters(relativePath + "@@" + revisionOrBranch);
// try {
h.run();
/* }
catch (VcsException e) {
String m = e.getMessage().trim();
if (m.startsWith("fatal: ambiguous argument ") || (m.startsWith("fatal: Path '") && m.contains("' exists on disk, but not in '"))) {
result = null;
}
else {
throw e;
}
}*/
byte[] bytes=null;
FileInputStream savedVersionInputStream=null;
try {
savedVersionInputStream=new FileInputStream(temp);
bytes=new byte[savedVersionInputStream.available()];
int readCount=savedVersionInputStream.read(bytes);
if(readCount!=bytes.length)
throw new VcsException(Bundle.message("version.tempfile.error",Bundle.getString("error.file.read")));
} catch(IOException e) {
throw new VcsException(e);
} finally {
//noinspection EmptyCatchBlock
try {
//noinspection ConstantConditions
savedVersionInputStream.close();
//noinspection ResultOfMethodCallIgnored
temp.delete();
} catch(Exception e) {} //sorry, best effort.
}
return bytes;
}
}
| true | true | public static byte[] getFileContent(Project project, VirtualFile root, String revisionOrBranch, String relativePath) throws VcsException {
BinaryHandler h = new BinaryHandler(project, root, Command.SHOW);
h.setRemote(true);
h.setSilent(true);
File temp;
try {
temp = FileUtil.createTempFile(relativePath.replaceAll("\\.","-")+revisionOrBranch.replaceAll("\\\\","-"), "tmp");
} catch(IOException e) {
throw new VcsException(e);
}
if(temp.exists()) {
//noinspection ResultOfMethodCallIgnored
temp.delete();
}
temp.deleteOnExit();
h.addParameters("-to "+temp.getAbsolutePath());
h.addParameters(relativePath + "@@" + revisionOrBranch);
// try {
h.run();
/* }
catch (VcsException e) {
String m = e.getMessage().trim();
if (m.startsWith("fatal: ambiguous argument ") || (m.startsWith("fatal: Path '") && m.contains("' exists on disk, but not in '"))) {
result = null;
}
else {
throw e;
}
}*/
byte[] bytes=null;
FileInputStream savedVersionInputStream=null;
try {
savedVersionInputStream=new FileInputStream(temp);
bytes=new byte[savedVersionInputStream.available()];
int readCount=savedVersionInputStream.read(bytes);
if(readCount!=bytes.length)
throw new VcsException(Bundle.message("version.tempfile.error",Bundle.getString("error.file.read")));
} catch(IOException e) {
throw new VcsException(e);
} finally {
//noinspection EmptyCatchBlock
try {
//noinspection ConstantConditions
savedVersionInputStream.close();
//noinspection ResultOfMethodCallIgnored
temp.delete();
} catch(Exception e) {} //sorry, best effort.
}
return bytes;
}
| public static byte[] getFileContent(Project project, VirtualFile root, String revisionOrBranch, String relativePath) throws VcsException {
BinaryHandler h = new BinaryHandler(project, root, Command.SHOW);
h.setRemote(true);
h.setSilent(true);
File temp;
try {
temp = FileUtil.createTempFile(relativePath.replaceAll("\\.","-")+revisionOrBranch.replaceAll("\\\\|/","-"), "tmp");
} catch(IOException e) {
throw new VcsException(e);
}
if(temp.exists()) {
//noinspection ResultOfMethodCallIgnored
temp.delete();
}
temp.deleteOnExit();
h.addParameters("-to "+temp.getAbsolutePath());
h.addParameters(relativePath + "@@" + revisionOrBranch);
// try {
h.run();
/* }
catch (VcsException e) {
String m = e.getMessage().trim();
if (m.startsWith("fatal: ambiguous argument ") || (m.startsWith("fatal: Path '") && m.contains("' exists on disk, but not in '"))) {
result = null;
}
else {
throw e;
}
}*/
byte[] bytes=null;
FileInputStream savedVersionInputStream=null;
try {
savedVersionInputStream=new FileInputStream(temp);
bytes=new byte[savedVersionInputStream.available()];
int readCount=savedVersionInputStream.read(bytes);
if(readCount!=bytes.length)
throw new VcsException(Bundle.message("version.tempfile.error",Bundle.getString("error.file.read")));
} catch(IOException e) {
throw new VcsException(e);
} finally {
//noinspection EmptyCatchBlock
try {
//noinspection ConstantConditions
savedVersionInputStream.close();
//noinspection ResultOfMethodCallIgnored
temp.delete();
} catch(Exception e) {} //sorry, best effort.
}
return bytes;
}
|
diff --git a/core/src/visad/trunk/data/text/TextAdapter.java b/core/src/visad/trunk/data/text/TextAdapter.java
index 109bcb6f0..0762ce830 100644
--- a/core/src/visad/trunk/data/text/TextAdapter.java
+++ b/core/src/visad/trunk/data/text/TextAdapter.java
@@ -1,1548 +1,1547 @@
//
// TextAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2007 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
*/
package visad.data.text;
import java.io.IOException;
import java.io.*;
import java.util.*;
import visad.Set;
import java.net.URL;
import visad.*;
import visad.VisADException;
import visad.data.in.ArithProg;
/** this is an VisAD file adapter for comma-, tab- and blank-separated
* ASCII text file data. It will attempt to create a FlatField from
* the data and descriptions given in the file and/or the constructor.
*
* The text files contained delimited data. The delimiter is
* determined as follows: if the file has a well-known extension
* (.csv, .tsv, .bsv) then the delimiter is implied by the extension.
* In all other cases, the delimiter for the data (and for the
* "column labels") is determined by reading the first line and
* looking, in order, for a tab, comma, or blank. Which ever one
* is found first is taken as the delimiter.
*
* Two extra pieces of information are needed: the VisAD "MathType"
* which is specified as a string (e.g., (x,y)->(temperature))
* and may either be the first line of the file or passed in through
* one of the constructors.
*
* The second item are the "column labels" which contain the names
* of each field in the data. The names of all range components
* specified in the "MathType" must appear. The names of domain
* components are optional. The values in this string are separated
* by the delimiter, as defined above.
*
* See visad.data.text.README.text for more details.
*
* @author Tom Whittaker
*
*/
public class TextAdapter {
private static final String ATTR_COLSPAN = "colspan";
private static final String ATTR_VALUE = "value";
private static final String ATTR_OFFSET = "off";
private static final String ATTR_ERROR = "err";
private static final String ATTR_SCALE = "sca";
private static final String ATTR_POSITION ="pos";
private static final String ATTR_FORMAT = "fmt";
private static final String ATTR_TIMEZONE = "tz";
private static final String ATTR_UNIT= "unit";
private static final String ATTR_MISSING = "mis";
private static final String ATTR_INTERVAL = "int";
private static final String COMMA = ",";
private static final String SEMICOLON = ";";
private static final String TAB = "\t";
private static final String BLANK = " ";
private static final String BLANK_DELIM = "\\s+";
private FlatField ff = null;
private Field field = null;
private boolean debug = false;
private String DELIM;
private boolean DOQUOTE = true;
private boolean GOTTIME = false;
HeaderInfo []infos;
double[] rangeErrorEstimates;
Unit[] rangeUnits;
Set[] rangeSets;
double[] domainErrorEstimates;
Unit[] domainUnits;
int[][] hdrColumns;
int[][] values_to_index;
private boolean onlyReadOneLine = false;
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename) throws IOException, VisADException {
this(filename, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param filename name of local file.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(String filename, String map, String params)
throws IOException, VisADException {
InputStream is = new FileInputStream(filename);
DELIM = getDelimiter(filename);
readit(is, map, params);
}
/** Create a VisAD FlatField from a remote Text (comma-, tab- or
* blank-separated values) ASCII file
*
* @param url File URL.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url) throws IOException, VisADException {
this(url, null, null);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param url File URL.
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(URL url, String map, String params)
throws IOException, VisADException {
DELIM = getDelimiter(url.getFile());
InputStream is = url.openStream();
readit(is, map, params);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params)
throws IOException, VisADException {
this(inputStream, delimiter, map,params,false);
}
/** Create a VisAD FlatField from a local Text (comma-, tab- or
* blank-separated values) ASCII file
* @param inputStream The input stream to read from
* @param delimiter the delimiter
* @param map the VisAD "MathType" as a string defining the FlatField
* @param params the list of parameters used to define what columns
* of the text file correspond to what MathType parameters.
* @param onlyReadOneLine If true then only read one line of data. This is used so client code can
* read the meta data.
* @exception IOException if there was a problem reading the file.
* @exception VisADException if an unexpected problem occurs.
*/
public TextAdapter(InputStream inputStream, String delimiter, String map, String params,boolean onlyReadOneLine)
throws IOException, VisADException {
this.onlyReadOneLine = onlyReadOneLine;
DELIM = delimiter;
readit(inputStream, map, params);
}
public static String getDelimiter(String filename) {
if(filename == null) return null;
filename = filename.trim().toLowerCase();
if (filename.endsWith(".csv")) return COMMA;
if (filename.endsWith(".tsv")) return TAB;
if (filename.endsWith(".bsv")) return BLANK;
return null;
}
/**
* Is the given text line a comment
*
* @return is it a comment line
*/
public static boolean isComment(String line) {
return (line.startsWith("#") ||
line.startsWith("!") ||
line.startsWith("%") ||
line.length() < 1);
}
public static String readLine(BufferedReader bis)
throws IOException {
while (true) {
String line = bis.readLine();
if (line == null) return null;
if (!isText(line)) return null;
if (isComment(line)) continue;
return line;
}
}
void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
- String s = stcl[l++];
+ String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
- for (int q=l; q < ncl; q++) {
+ for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
+ l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
- l++;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
- stcl[l] = vTmp.substring(pos+1);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
String[] st = s.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
- sa = ""; // need to have a missing value
+ sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
+ l++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
- l++;
} else {
sa2 = sa2+saTmp.substring(0,pos);
- st[l] = saTmp.substring(pos+1);
+ //st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
// munges a pseudo MathType string into something legal
private String makeMT(String s) {
int k = s.indexOf("->");
if (k < 0) {
// System.out.println("TextAdapter: invalid MathType form; -> required");
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i=0; i<s.length(); i++) {
String r = s.substring(i,i+1);
if (!r.equals(" ") && !r.equals("\t") && !r.equals("\n")) {
sb.append(r);
}
}
String t = sb.toString();
k = t.indexOf("->");
if (t.charAt(k-1) != ')' ) {
if (t.charAt(k+2) != '(' ) {
String t2 = "("+t.substring(0,k) + ")->("+t.substring(k+2)+")";
t = t2;
} else {
String t2 = "("+t.substring(0,k) + ")"+t.substring(k);
t = t2;
}
} else if (t.charAt(k+2) != '(' ) {
String t2 = t.substring(0,k+2)+"("+t.substring(k+2)+")";
t = t2;
}
if (!t.startsWith("((") ) {
String t2= "("+t+")";
t = t2;
}
return t;
}
private static final boolean isText(String s)
{
final int len = (s == null ? -1 : s.length());
if (len <= 0) {
// well, it's not really *binary*, so pretend it's text
return true;
}
for (int i = 0; i < len; i++) {
final char ch = s.charAt(i);
if (Character.isISOControl(ch) && !Character.isWhitespace(ch)) {
// we might want to special-case formfeed/linefeed/newline here...
return false;
}
}
return true;
}
/**
* generate a DateTime from a string
* @param string - Formatted date/time string
*
* @return - the equivalent VisAD DateTime for the string
*
* (lifted from au.gov.bom.aifs.common.ada.VisADXMLAdapter.java)
*/
private static visad.DateTime makeDateTimeFromString(String string,
String format, String tz)
throws java.text.ParseException
{
visad.DateTime dt = null;
// try to parse the string using the supplied DateTime format
try {
dt = visad.DateTime.createDateTime(string, format, TimeZone.getTimeZone(tz));
} catch (VisADException e) {}
if (dt==null) {
throw new java.text.ParseException("Couldn't parse visad.DateTime from \""
+string+"\"", -1);
} else {
return dt;
}
}
double getVal(String s, int k) {
int i = values_to_index[2][k];
if (i < 0 || s == null || s.length()<1 || s.equals(infos[i].missingString)) {
return Double.NaN;
}
// try parsing as a double first
if (infos[i].formatString == null) {
// no format provided : parse as a double
try {
double v;
try {
v = Double.parseDouble(s);
} catch (java.lang.NumberFormatException nfe1) {
//If units are degrees then try to decode this as a lat/lon
// We should probably not rely on throwing an exception to handle this but...
if(infos[i].unit !=null && Unit.canConvert(infos[i].unit, visad.CommonUnit.degree)) {
v=decodeLatLon(s);
} else {
throw nfe1;
}
if(v!=v) throw new java.lang.NumberFormatException(s);
}
if (v == infos[i].missingValue) {
return Double.NaN;
}
v = v * infos[i].scale + infos[i].offset;
return v;
} catch (java.lang.NumberFormatException ne) {
System.out.println("Invalid number format for "+s);
}
} else {
// a format was specified: only support DateTime format
// so try to parse as a DateTime
try{
visad.DateTime dt = makeDateTimeFromString(s, infos[i].formatString, infos[i].tzString);
return dt.getReal().getValue();
} catch (java.text.ParseException pe) {
System.out.println("Invalid number/time format for "+s);
}
}
return Double.NaN;
}
// get the samples from the ArrayList.
float[][] getDomSamples(int comp, int numDomValues, ArrayList domValues) {
float [][] a = new float[1][numDomValues];
for (int i=0; i<numDomValues; i++) {
double[] d = (double[])(domValues.get(i));
a[0][i] = (float)d[comp];
}
return a;
}
/** get the data
* @return a Field of the data read from the file
*
*/
public Field getData() {
return field;
}
/**
* Returns an appropriate 1D domain.
*
* @param type the math-type of the domain
* @param numSamples the number of samples in the domain
* @param domValues domain values are extracted from this array list.
*
* @return a Linear1DSet if the domain samples form an arithmetic
* progression, a Gridded1DDoubleSet if the domain samples are ordered
* but do not form an arithmetic progression, otherwise an Irregular1DSet.
*
* @throws VisADException there was a problem creating the domain set.
*/
private Set createAppropriate1DDomain(MathType type, int numSamples,
ArrayList domValues)
throws VisADException {
if (0 == numSamples) {
// Can't create a domain set with zero samples.
return null;
}
// Extract the first element from each element of the array list.
double[][] values = new double[1][numSamples];
for (int i=0; i<numSamples; ++i) {
double[] d = (double []) domValues.get(i);
values[0][i] = d[0];
}
// This implementation for testing that the values are ordered
// is based on visad.Gridded1DDoubleSet.java
boolean ordered = true;
boolean ascending = values[0][numSamples -1] > values[0][0];
if (ascending) {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] < values[0][i - 1]) {
ordered = false;
break;
}
}
} else {
for (int i=1; i<numSamples; ++i) {
if (values[0][i] > values[0][i - 1]) {
ordered = false;
break;
}
}
}
Set set = null;
if (ordered) {
ArithProg arithProg = new ArithProg();
if (arithProg.accumulate(values[0])) {
// The domain values form an arithmetic progression (ordered and
// equally spaced) so use a linear set.
set = new Linear1DSet(type, values[0][0], values[0][numSamples - 1],
numSamples);
} else {
// The samples are ordered, so use a gridded set.
set = new Gridded1DDoubleSet(type, values, numSamples);
}
} else {
set = new Irregular1DSet(type, Set.doubleToFloat(values));
}
return set;
}
private static class HeaderInfo {
String name;
Unit unit;
double missingValue = Double.NaN;
String missingString;
String formatString;
String tzString = "GMT";
int isInterval = 0;
double errorEstimate=0;
double scale=1.0;
double offset=0.0;
String fixedValue;
int colspan = 1;
public boolean isParam(String param) {
return name.equals(param) || name.equals(param+"(Text)");
}
public String toString() {
return name;
}
}
// uncomment to test
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Must supply a filename");
System.exit(1);
}
TextAdapter ta = new TextAdapter(args[0]);
System.out.println(ta.getData().getType());
new visad.jmet.DumpType().dumpMathType(ta.getData().getType(),System.out);
new visad.jmet.DumpType().dumpDataType(ta.getData(),System.out);
System.out.println("#### Data = "+ta.getData());
System.out.println("EOF... ");
}
/**
* A cut-and-paste from the IDV Misc method
* Decodes a string representation of a latitude or longitude and
* returns a double version (in degrees). Acceptible formats are:
* <pre>
* +/- ddd:mm, ddd:mm:, ddd:mm:ss, ddd::ss, ddd.fffff ===> [+/-] ddd.fffff
* +/- ddd, ddd:, ddd:: ===> [+/-] ddd
* +/- :mm, :mm:, :mm:ss, ::ss, .fffff ===> [+/-] .fffff
* +/- :, :: ===> 0.0
* Any of the above with N,S,E,W appended
* </pre>
*
* @param latlon string representation of lat or lon
* @return the decoded value in degrees
*/
public static double decodeLatLon(String latlon) {
// first check to see if there is a N,S,E,or W on this
latlon = latlon.trim();
int dirIndex = -1;
int southOrWest = 1;
double value = Double.NaN;
if (latlon.indexOf("S") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("S");
} else if (latlon.indexOf("W") > 0) {
southOrWest = -1;
dirIndex = latlon.indexOf("W");
} else if (latlon.indexOf("N") > 0) {
dirIndex = latlon.indexOf("N");
} else if (latlon.indexOf("E") > 0) {
dirIndex = latlon.indexOf("E");
}
if (dirIndex > 0) {
latlon = latlon.substring(0, dirIndex).trim();
}
// now see if this is a negative value
if (latlon.indexOf("-") == 0) {
southOrWest *= -1;
latlon = latlon.substring(latlon.indexOf("-") + 1).trim();
}
if (latlon.indexOf(":") >= 0) { //have something like DD:MM:SS, DD::, DD:MM:, etc
int firstIdx = latlon.indexOf(":");
String hours = latlon.substring(0, firstIdx);
String minutes = latlon.substring(firstIdx + 1);
String seconds = "";
if (minutes.indexOf(":") >= 0) {
firstIdx = minutes.indexOf(":");
String temp = minutes.substring(0, firstIdx);
seconds = minutes.substring(firstIdx + 1);
minutes = temp;
}
try {
value = (hours.equals("") == true)
? 0
: Double.parseDouble(hours);
if ( !minutes.equals("")) {
value += Double.parseDouble(minutes) / 60.;
}
if ( !seconds.equals("")) {
value += Double.parseDouble(seconds) / 3600.;
}
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
} else { //have something like DD.ddd
try {
value = Double.parseDouble(latlon);
} catch (NumberFormatException nfe) {
value = Double.NaN;
}
}
return value * southOrWest;
}
}
| false | true | void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l++];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
l++;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
stcl[l] = vTmp.substring(pos+1);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
String[] st = s.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
l++;
} else {
sa2 = sa2+saTmp.substring(0,pos);
st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
| void readit(InputStream is, String map, String params)
throws IOException, VisADException {
// read the ASCII file, using commas as field separators
// first line is a header line
ff = null;
field = null;
if (debug) System.out.println("#### Text Adapter v2.x running");
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
// mapping defines how the names are mapped
// for example: (x,y) => (one, two, three)
String maps = null;
if (map == null) {
maps = readLine(bis);
if(maps != null) {
maps = maps.trim();
}
} else {
maps = map;
}
if (maps != null) {
maps = makeMT(maps);
}
if (maps == null) {
throw new visad.data.BadFormException(
"TextAdapter: Invalid or missing MathType");
}
if (debug) System.out.println("Specified MathType = "+maps);
// but first, we need to get the column headers because they
// may have [units] associated with them. The column headers
// primarily define where the data are.
String hdr = null;
if (params == null) {
hdr = readLine(bis);
} else {
hdr = params;
}
String hdrDelim = DELIM;
if (DELIM == null) {
if (hdr.indexOf(BLANK) != -1) hdrDelim = BLANK_DELIM;
if (hdr.indexOf(COMMA) != -1) hdrDelim = COMMA;
if (hdr.indexOf(SEMICOLON) != -1) hdrDelim = SEMICOLON;
if (hdr.indexOf(TAB) != -1) hdrDelim = TAB;
if (debug) System.out.println("Using header delimiter = "+
(hdrDelim.getBytes())[0]);
}
String[] sthdr = hdr.split(hdrDelim);
int nhdr = sthdr.length;
infos = new HeaderInfo[nhdr];
for(int i=0;i<infos.length;i++) {
infos[i] = new HeaderInfo();
}
Real[] prototypeReals = new Real[nhdr];
hdrColumns = new int[2][nhdr];
int numHdrValues=0;
// pre-scan of the header names to seek out Units
// since we cannot change a RealType once it's defined!!
for (int i=0; i<nhdr; i++) {
String name = sthdr[i].trim();
String hdrUnitString = null;
hdrColumns[0][i] = -1; // indicating no fixed columns
int m = name.indexOf("[");
if (m == -1) {
infos[i].name = name;
hdrUnitString = null;
} else {
int m2 = name.indexOf("]");
if (m2 == -1) {
throw new VisADException("TextAdapter: Bad [descriptor] named in:"+name);
}
// now parse items: unit=xxx miss=xxx interval=xxx error=xxx
// 1. tokenize on " "
// 2. scan each token, retokenizing on "="
// 3. if (has no "=") && (is first one) then treat as Unit
// 4. otherwise, look for keys "unit" "miss" "inter" "err" "scale" "offset" "pos"
// and fill in the values in array[i]
if (m2 >= name.length()) {
infos[i].name = name.substring(0,m).trim();
} else {
infos[i].name = (name.substring(0,m)+name.substring(m2+1)).trim();
}
String cl = name.substring(m+1,m2).trim();
String[] stcl = cl.split(BLANK_DELIM);
int ncl = stcl.length;
if (ncl == 1 && cl.indexOf("=") == -1) {
hdrUnitString = cl; // backward compatible...
} else {
for (int l = 0; l < ncl; l++) {
String s = stcl[l];
String[] sts = s.split("=");
if (sts.length != 2) {
throw new VisADException("TextAdapter: Invalid clause in: "+s);
}
String tok = sts[0];
String val = sts[1];
// check for quoted strings
if (val.startsWith("\"")) {
// see if ending quote also fetched
if (val.endsWith("\"")) {
String v2 = val.substring(1,val.length()-1);
val = v2;
} else {
// if not, then reparse stcl to suck up spaces...
try {
String v2="";
for (int q=l+1; q < ncl; q++) {
String vTmp = stcl[q];
// find next token that has a " in it
int pos = vTmp.indexOf("\"");
l++;
if (pos < 0) { // no "
v2 = v2+" "+vTmp;
} else {
v2 = v2+" "+vTmp.substring(0,pos);
break;
}
}
String v3 = val.substring(1)+v2;
val = v3;
//} catch (NoSuchElementException nse2) {
} catch (ArrayIndexOutOfBoundsException nse2) {
val="";
}
}
}
if (debug) System.out.println("#### tok = "+tok+ " val = '"+val+"'");
if (tok.toLowerCase().startsWith(ATTR_UNIT)) {
hdrUnitString = val;
} else if (tok.toLowerCase().startsWith(ATTR_MISSING)) {
infos[i].missingString = val.trim();
try {
infos[i].missingValue = Double.parseDouble(val);
} catch (java.lang.NumberFormatException me) {
infos[i].missingValue = Double.NaN;
}
} else if (tok.toLowerCase().startsWith(ATTR_INTERVAL)) {
infos[i].isInterval = -1;
if (val.toLowerCase().startsWith("t")) infos[i].isInterval = 1;
if (val.toLowerCase().startsWith("f")) infos[i].isInterval = 0;
if (infos[i].isInterval == -1) {
throw new VisADException("TextAdapter: Value of \'interval\' must be \'true\' or \'false\'");
}
} else if (tok.toLowerCase().startsWith(ATTR_ERROR)) {
infos[i].errorEstimate = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_SCALE)) {
infos[i].scale = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_OFFSET)) {
infos[i].offset = Double.parseDouble(val);
} else if (tok.toLowerCase().startsWith(ATTR_VALUE)) {
infos[i].fixedValue = val.trim();
numHdrValues++;
} else if (tok.toLowerCase().startsWith(ATTR_COLSPAN)) {
infos[i].colspan = (int)Double.parseDouble(val.trim());
} else if (tok.toLowerCase().startsWith(ATTR_POSITION)) {
String[] stp = val.split(":");
if (stp.length != 2) {
throw new VisADException("TextAdapter: invalid Position parameter in:"+s);
}
hdrColumns[0][i] = Integer.parseInt(stp[0].trim());
hdrColumns[1][i] = Integer.parseInt(stp[1].trim());
} else if (tok.toLowerCase().startsWith(ATTR_FORMAT)) {
infos[i].formatString = val.trim();
} else if (tok.toLowerCase().startsWith(ATTR_TIMEZONE)) {
infos[i].tzString = val.trim();
} else {
throw new VisADException("TextAdapter: invalid token name: "+s);
}
}
}
}
if (debug)
System.out.println("hdr name = "+infos[i]+" units="+
hdrUnitString+
" miss="+infos[i].missingValue+" interval="+infos[i].isInterval+
" errorest="+infos[i].errorEstimate+" scale="+infos[i].scale+
" offset="+infos[i].offset+" pos="+hdrColumns[0][i]+":"+
hdrColumns[1][i]);
Unit u = null;
if (hdrUnitString != null &&
!hdrUnitString.trim().equalsIgnoreCase("null") ) {
try {
u = visad.data.units.Parser.parse(hdrUnitString.trim());
} catch (Exception ue) {
try {
u = visad.data.units.Parser.parse(
hdrUnitString.trim().replace(' ','_'));
} catch (Exception ue2) {
System.out.println("Unit name problem:"+ue+" with: "+hdrUnitString);
u = null;
}
}
}
if (debug) System.out.println("#### assigned Unit as u="+u);
String rttemp = infos[i].name.trim();
if (rttemp.indexOf("(Text)") == -1) {
int parenIndex = rttemp.indexOf("(");
if (parenIndex < 0) parenIndex = rttemp.indexOf("[");
if (parenIndex < 0) parenIndex = rttemp.indexOf("{");
if (parenIndex < 0) parenIndex = rttemp.indexOf(" ");
String rtname = parenIndex < 0 ? rttemp.trim() : rttemp.substring(0,parenIndex);
RealType rt = RealType.getRealType(rtname, u, null, infos[i].isInterval);
if (rt == null) { // tried to re-use with different units
if (debug) System.out.println("#### rt was returned as null");
if (u != null) System.out.println("#### Could not make RealType using specified Unit ("+hdrUnitString+") for parameter name: "+rtname);
rt = RealType.getRealType(rtname);
}
// get a compatible unit, if necessary
if (rt.equals(visad.RealType.Time)) {
GOTTIME = true;
if (debug) System.out.println("#### found a visad.RealType.Time component");
} else {
GOTTIME = false;
}
if (u == null) u = rt.getDefaultUnit();
if(debug) System.out.println("#### retrieve units from RealType = "+u);
}
infos[i].unit = u;
}
// get the MathType of the function
MathType mt = null;
try {
mt = MathType.stringToType(maps);
} catch (Exception mte) {
System.out.println("#### Exception: "+mte);
throw new VisADException("TextAdapter: MathType badly formed or missing: "+maps);
}
if (debug) {
System.out.println(mt);
new visad.jmet.DumpType().dumpMathType(mt,System.out);
}
// now get the names of the domain variables and range variables.
String[] domainNames = null;
String[] rangeNames = null;
int numDom = 0;
int numRng = 0;
RealTupleType domType;
TupleType rngType;
if (mt instanceof FunctionType) {
domType = ((FunctionType)mt).getDomain();
numDom = domType.getDimension();
domainNames = new String[numDom];
for (int i=0; i<numDom; i++) {
MathType comp = domType.getComponent(i);
domainNames[i] = ((RealType)comp).toString().trim();
if (debug) System.out.println("dom "+i+" = "+domainNames[i]);
}
rngType = (TupleType) ((FunctionType)mt).getRange();
numRng = rngType.getDimension();
rangeNames = new String[numRng];
rangeSets = new Set[numRng];
for (int i=0; i<numRng; i++) {
MathType comp = rngType.getComponent(i);
rangeNames[i] = (comp).toString().trim();
if (debug) System.out.println("range "+i+" = "+rangeNames[i]);
if (comp instanceof RealType) {
rangeSets[i] = ((RealType) comp).getDefaultSet();
if (rangeSets[i] == null) {
if (comp.equals(RealType.Time)) {
rangeSets[i] = new DoubleSet(new SetType(comp));
} else {
rangeSets[i] = new FloatSet(new SetType(comp));
}
}
} else {
rangeSets[i] = null; // something else is wrong here...
}
if (debug) System.out.println("#### rangeSet = "+rangeSets[i]);
;
}
} else {
throw new visad.VisADException("TextAdapter: Math Type is not a simple FunctionType");
}
// now for each header label, determine if it's a domain or
// range component -- and if so, which one.
// also, if it's a domain component, allow for name(first:last[:number])
//
// and if none of the domain components appear in the list, then
// they are computed as name(0:N-1)
int[] domainPointer = new int[numDom];
double[][] domainRanges = new double[3][numDom]; // min, max, numb
boolean[] gotDomainRanges = new boolean[numDom];
domainErrorEstimates = new double[numDom];
domainUnits = new Unit[numDom];
rangeErrorEstimates = new double[numRng];
rangeUnits = new Unit[numRng];
int countDomain = 0;
for (int i=0; i<numDom; i++) {
domainPointer[i] = -1;
gotDomainRanges[i] = false;
domainErrorEstimates[i] = Double.NaN;
domainUnits[i] = null;
}
int[] rangePointer = new int[numRng];
int countRange = 0;
for (int i=0; i<numRng; i++) {
rangePointer[i] = -1;
rangeErrorEstimates[i] = Double.NaN;
rangeUnits[i] = null;
}
int countValues = -1;
values_to_index = new int[3][nhdr];
for (int i=0; i<nhdr; i++) {
values_to_index[0][i] = -1; // points to domains
values_to_index[1][i] = -1; // points to ranges
values_to_index[2][i] = -1; // points to names/units/etc
countValues ++;
String name = infos[i].name;
// see if it's a domain name
boolean gotName = false;
// is there a "min:max" clause?
String test_name = name;
int n = test_name.indexOf("(");
if (n != -1) {
// but allow for "(Text)"
if ((test_name.indexOf("(Text)")) == -1) {
test_name = name.substring(0,n).trim();
countValues --; // this value wont appear in data!
countDomain --; // and is a pre-defined, linear set
}
}
// try to find the column header name in the domain name list
for (int k=0; k<numDom; k++) {
if (test_name.equals(domainNames[k]) ) {
domainPointer[k] = countValues;
domainErrorEstimates[k] = infos[i].errorEstimate;
domainUnits[k] = infos[i].unit;
gotName = true;
countDomain ++;
// now see if a list is given...
if (n != -1) {
try {
String ss = name.substring(n+1,name.length()-1);
String[] sct = ss.split(":");
String first = sct[0].trim();
String second = sct[1].trim();
String third = "1";
if (sct.length == 3) third = sct[2].trim();
domainRanges[0][k] = Double.parseDouble(first);
domainRanges[1][k] = Double.parseDouble(second);
domainRanges[2][k] = Double.parseDouble(third);
gotDomainRanges[k] = true;
} catch (Exception ef) {
throw new VisADException(
"TextAdapter: Error while interpreting min:max values for domain "+name);
}
} else if (countValues > -1) { // if no list, get from file
values_to_index[0][countValues] = k;
values_to_index[2][countValues] = i;
}
break;
}
}
if (gotName) continue;
// or see if its a range name...
for (int k=0; k<numRng; k++) {
if (name.equals(rangeNames[k]) ) {
rangePointer[k] = countValues;
rangeErrorEstimates[k] = infos[i].errorEstimate;
rangeUnits[k] = infos[i].unit;
countRange ++;
values_to_index[1][countValues] = k;
values_to_index[2][countValues] = i;
gotName = true;
}
}
}
// huge debug printout...
// *****************************************************************
if (debug) {
System.out.println("countDom/numDom="+countDomain+" "+numDom);
System.out.println("countRange/numRng="+countRange+" "+numRng);
System.out.println("Domain info:");
for (int i=0; i<numDom; i++) {
System.out.println("Dom name / index = "+domainNames[i]+" "+
domainPointer[i]);
if (gotDomainRanges[i]) {
System.out.println(" ..."+domainRanges[0][i]+" "+
domainRanges[1][i]+" "+domainRanges[2][i]);
}
}
System.out.println("Range info:");
for (int i=0; i<numRng; i++) {
System.out.println("Rng name / index / error est = "+rangeNames[i]+" "+
rangePointer[i]+ " " + rangeErrorEstimates[i] +" "+
rangeUnits[i]);
}
System.out.println("values_to_index pointers = ");
for (int i=0; i<nhdr; i++) {
System.out.println(" inx / value = "+i+
" "+values_to_index[0][i]+" "+values_to_index[1][i]+
" "+values_to_index[2][i]);
}
}
// ***************************************************************
// for each line of text, put the values into the ArrayList
ArrayList domainValues = new ArrayList();
ArrayList rangeValues = new ArrayList();
ArrayList tupleValues = new ArrayList();
boolean tryToMakeTuple = true;
Tuple tuple = null;
String dataDelim = DELIM;
boolean isRaster = false;
int numElements = 1;
// in the 'raster array' case, the numRng value will be 1,
// along with the countRange. numDomain must be 2.
// if the domain is 2D, then get values from the first
// matching column to the end...
if (countRange == 1 && numRng == 1 &&
numDom == 2 && countDomain < 2) isRaster = true;
int index;
while (true) {
String s = bis.readLine();
if (debug) System.out.println("read:"+s);
if (s == null) break;
if (!isText(s)) return;
if (isComment(s)) continue;
if (dataDelim == null) {
if (s.indexOf(BLANK) != -1) dataDelim = BLANK_DELIM;
if (s.indexOf(COMMA) != -1) dataDelim = COMMA;
if (s.indexOf(SEMICOLON) != -1) dataDelim = SEMICOLON;
if (s.indexOf(TAB) != -1) dataDelim = TAB;
if (debug) System.out.println("Using data delimiter = "+
(dataDelim.getBytes())[0]);
}
if((index=s.indexOf("="))>=0) {
String name = s.substring(0,index).trim();
String value = s.substring(index+1).trim();
boolean foundIt = false;
for(int paramIdx=0;paramIdx<infos.length;paramIdx++) {
if(infos[paramIdx].isParam(name)) {
if(infos[paramIdx].fixedValue==null) {
numHdrValues++;
}
infos[paramIdx].fixedValue = value;
foundIt = true;
break;
}
}
if(!foundIt) {
throw new VisADException(
"TextAdapter: Cannot find field with name:" +name +" from line:" + s);
}
continue;
}
String[] st = s.split(dataDelim);
int n = st.length;
if (n < 1) continue; // something is wrong if this happens!
double [] dValues = new double[numDom];
double [] rValues = null;
Data [] tValues = null;
if (isRaster) {
if (debug) System.out.println("probably a raster...");
boolean gotFirst = false;
int rvaluePointer = 0;
int irange = 0;
for (int i=0; i<n; i++) {
String sa = st[i];
if (i >= nhdr) { // are we past where domain would be found?
if (!gotFirst) {
throw new VisADException(
"TextAdapter: Cannot find first raster value");
}
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else { // or are we still looking for domain?
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
}
if (gotFirst) { // already gathering data
rvaluePointer ++;
rValues[rvaluePointer] = getVal(sa, irange);
} else {
if (values_to_index[1][i] != -1) {
// cannot dimension the array until we have found
// the first set of range values!!
rValues = new double[n - i];
irange = i;
rValues[rvaluePointer] = getVal(sa, irange);
gotFirst = true;
}
}
}
}
} else { // is probably NOT a raster
tValues = new Data[numRng];
if (debug) System.out.println("probably not a raster...");
rValues = new double[numRng];
double thisDouble;
MathType thisMT;
if (n > nhdr) n = nhdr; // in case the # tokens > # parameters
n +=numHdrValues;
int l = 0; // token counter
for (int i=0; i<nhdr; i++) { // loop over the columns
String sa;
if(infos[i].fixedValue!=null) {
sa = infos[i].fixedValue;
} else if (l >= st.length) { // more params than tokens
sa = ""; // need to have a missing value
} else {
sa = st[l++].trim();
int moreColumns = infos[i].colspan-1;
while (moreColumns>0) {
sa = sa + " " + st[l++].trim();
moreColumns--;
}
}
String sThisText;
if (values_to_index[0][i] != -1) {
dValues[values_to_index[0][i]] = getVal(sa, i);
} else if (values_to_index[1][i] != -1) {
thisMT = rngType.getComponent(values_to_index[1][i]);
if (thisMT instanceof TextType) {
// if Text, then check for quoted string
if (sa.startsWith("\"")) {
if (sa.endsWith("\"")) { // if single token ends with quote
String sa2 = sa.substring(1,sa.length()-1);
sThisText = sa2;
} else {
// TODO: work on this
try {
String delim =
dataDelim.equals(BLANK_DELIM) ? BLANK : dataDelim;
String sa2="";
for (int q=l; q < st.length; q++) {
String saTmp = st[q];
// find next token that has a " in it
int pos = saTmp.indexOf("\"");
l++;
if (pos < 0) { // no dataDelim
sa2 = sa2+delim+saTmp;
} else {
sa2 = sa2+saTmp.substring(0,pos);
//st[l] = saTmp.substring(pos+1);
break;
}
}
//sThisText = sa.substring(1)+sa2;
sThisText = sa.substring(1)+delim+sa2;
//} catch (NoSuchElementException nse) {
} catch (ArrayIndexOutOfBoundsException nse) {
sThisText = "";
}
}
if (debug) System.out.println("#### Text value='"+sThisText+"'");
// if not quoted, then take "as is"
} else {
sThisText = sa;
}
// now make the VisAD Data
try {
tValues[values_to_index[1][i]] =
new Text((TextType) thisMT, sThisText);
if (debug) System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " +
thisMT + " to TextType " + e);
}
// if not Text, then treat as numeric
} else {
double value = getVal(sa,i);
rValues[values_to_index[1][i]] = value;
try {
if(prototypeReals[i]==null) {
prototypeReals[i] = new Real((RealType) thisMT, getVal(sa,i), infos[i].unit);
}
tValues[values_to_index[1][i]] =
prototypeReals[i].cloneButValue(value);
if(debug)System.out.println("tValues[" +
values_to_index[1][i] + "] = " +
tValues[values_to_index[1][i]]);
} catch (Exception e) {
System.out.println(" Exception converting " + thisMT + " " + e);
}
}
}
}
}
if(tryToMakeTuple) {
try {
if (tValues != null) tuple = new Tuple(tValues);
} catch (visad.TypeException te) {
// do nothing: it means they are all reals
// tuple = new RealTuple(tValues);
tuple = null;
tryToMakeTuple = false;
}
}
domainValues.add(dValues);
rangeValues.add(rValues);
if (tuple != null) tupleValues.add(tuple);
if (isRaster) numElements = rValues.length;
if(onlyReadOneLine) break;
}
int numSamples = rangeValues.size(); // # lines of data
// ***********************************************************
if (debug) {
try {
System.out.println("domain size = "+domainValues.size());
double[] dt = (double[]) domainValues.get(1);
System.out.println("domain.array[0] = "+dt[0]);
System.out.println("range size = "+rangeValues.size());
System.out.println("# samples = "+numSamples);
} catch (Exception er) {System.out.println("out range");}
}
// ***********************************************************
// make Linear1DSets for each possible domain component
Linear1DSet[] lset = new Linear1DSet[numDom];
boolean keepConstant = false;
int numVal = numRng;
if (numDom == 1) numVal = numSamples;
if (numDom == 2 && numRng == 1 && numElements > 1) numVal = numElements;
if (numDom > 2 && numRng == 1 && numElements == 1) {
numVal = numSamples / (2 * numDom);
keepConstant = true;
}
for (int i=0; i<numDom; i++) {
if (gotDomainRanges[i]) {
// if domain was given with a count, use it for 'raster'-type
if (numDom == 2 && numRng == 1 && numElements == 1)
numVal = (int) domainRanges[2][i];
lset[i] = new Linear1DSet(domType.getComponent(i), domainRanges[0][i],
domainRanges[1][i], numVal);
if (debug) System.out.println("lset from domain = "+lset[i]);
} else if (domainPointer[i] == -1 ) {
lset[i] = new Linear1DSet(0., (double)(numVal-1), numVal);
if (debug) System.out.println("lset from range = "+lset[i]);
} else {
lset[i] = null;
}
if (!keepConstant) numVal = numSamples;
}
// now make up the actual domain sets for the function
Set domain = null;
if (numDom == 1) { // for 1-D domains
if (lset[0] == null) {
domain = createAppropriate1DDomain(domType, numSamples, domainValues);
} else {
domain = lset[0];
}
} else if (numDom == 2) { // for 2-D domains
if (lset[0] != null && lset[1] != null) {
domain = new Linear2DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular2DSet(domType, samples);
}
} else if (numDom == 3) { // for 3-D domains
if (lset[0] != null && lset[1] != null && lset[2] != null) {
domain = new Linear3DSet(domType, lset);
} else {
float[][] samples = new float[numDom][numSamples];
for (int k = 0; k < numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = (Set) new Irregular3DSet(domType, samples);
}
} else { // N-D domains (can only use LinearSets!!
boolean allLinear = true;
for (int k = 0; k<numDom; k++) {
if (lset[k] == null) allLinear = false;
}
if (allLinear) {
if (debug) System.out.println("#### Making LinearNDset");
domain = new LinearNDSet(domType, lset);
} else {
if (debug) System.out.println("#### Making IrregularSet");
float[][] samples = new float[numDom][numSamples];
for (int k=0; k<numDom; k++) {
if (lset[k] == null) {
samples[k] = (getDomSamples(k, numSamples, domainValues))[0];
} else {
samples[k] = (lset[k].getSamples())[0];
}
}
domain = new IrregularSet(domType, samples);
}
}
try {
ff = new FlatField((FunctionType) mt, domain,
null, null, rangeSets, rangeUnits);
} catch (FieldException fe) {
field = new FieldImpl((FunctionType) mt, domain);
} catch (UnitException fe) {
System.out.println("#### Problem with Units; attempting to make Field anyway");
field = new FieldImpl((FunctionType) mt, domain);
}
//*************************************************
if (debug) {
if (ff != null) {
System.out.println("ff.Length "+ff.getLength());
System.out.println("ff.getType "+ff.getType());
}
if (field != null) {
System.out.println("field.Length "+field.getLength());
System.out.println("field.getType "+field.getType());
}
System.out.println("domain = "+domain);
System.out.println("size of a = "+numRng+" x "+(numSamples*numElements));
}
//*************************************************
double[][]a = new double[numRng][numSamples * numElements];
Tuple[] at = new Tuple[numSamples];
// if this is a raster then the samples are in a slightly
// difielderent form ...
if (isRaster) {
int samPointer = 0;
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numElements; j++) {
a[0][samPointer] = rs[j];
samPointer ++;
}
}
} else {
for (int i=0; i<numSamples; i++) {
double[] rs = (double[])(rangeValues.get(i));
for (int j=0; j<numRng; j++) {
a[j][i] = rs[j];
}
if (!tupleValues.isEmpty()) {
at[i] = (Tuple) tupleValues.get(i);
}
}
}
// set samples
if (debug) System.out.println("about to field.setSamples");
try {
if (ff != null) {
if (debug) System.out.println("#### ff is not null");
ff.setSamples(a, false);
field = (Field) ff;
} else {
if (debug) System.out.println("#### ff is null..use FieldImpl");
field.setSamples(at, false);
}
} catch (Exception ffe) {ffe.printStackTrace(); }
// make up error estimates and set them
ErrorEstimate[] es = new ErrorEstimate[numRng];
for (int i=0; i<numRng; i++) {
es[i] = new ErrorEstimate(a[i], rangeErrorEstimates[i], rangeUnits[i]);
}
try {
((FlatField) field).setRangeErrors(es);
} catch (FieldException fe) {
if (debug) System.out.println("caught "+fe);
// not a flatfield
// don't setRangeErrors
} catch (ClassCastException cce) {
if (debug) System.out.println("caught "+cce);
// not a flatfield
// don't setRangeErrors
}
if (debug) {
new visad.jmet.DumpType().dumpDataType(field,System.out);
System.out.println("field = "+field);
}
bis.close();
}
|
diff --git a/chrisHaughton/src/com/osgo/plugin/portfolio/servlet/Upload.java b/chrisHaughton/src/com/osgo/plugin/portfolio/servlet/Upload.java
index 10953ec..a884e13 100644
--- a/chrisHaughton/src/com/osgo/plugin/portfolio/servlet/Upload.java
+++ b/chrisHaughton/src/com/osgo/plugin/portfolio/servlet/Upload.java
@@ -1,177 +1,179 @@
package com.osgo.plugin.portfolio.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import java.nio.ByteBuffer;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import com.osgo.plugin.portfolio.api.PortfolioService;
import com.osgo.plugin.portfolio.api.PortfolioServiceFactory;
import com.osgo.plugin.portfolio.model.objectify.Picture;
import com.osgo.plugin.portfolio.model.objectify.Project;
public class Upload extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
private boolean cloudStorage = true;
private boolean blobStore = false;
public static final String BUCKETNAME = "osgo/dealImages";
public static final String DIR = "dealImages/";
private static final Logger log =
Logger.getLogger(Upload.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
/**
* Set up properties of your new object
* After finalizing objects, they are accessible
* through Cloud Storage with the URL:
* http://commondatastorage.googleapis.com/my_bucket/my_object
*/
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
PortfolioService portfolioService = PortfolioServiceFactory.getPortfolioService();
Project project = null;
List<String> info = new ArrayList<String>();
List<String> links = new ArrayList<String>();
List<String> linkTexts = new ArrayList<String>();
Map<String, BlobKey> images = new HashMap<String, BlobKey>();
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// get Project to add image to
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer);
String theString = writer.toString();
if(item.getFieldName().equals("project_id")){
String projId = URLDecoder.decode(theString);
Long id = Long.parseLong(projId);
project = portfolioService.getProject(id);
} else {
- if(item.getFieldName().contains("display_text")){
- info.add(theString);
- } else if(item.getFieldName().contains("link")){
- links.add(theString);
- } else if(item.getFieldName().contains("link_text")){
- linkTexts.add(theString);
+ if(theString!=null){
+ if(item.getFieldName().contains("display_text")){
+ info.add(theString);
+ } else if(item.getFieldName().contains("link")){
+ links.add(theString);
+ } else if(item.getFieldName().contains("link_text")){
+ linkTexts.add(theString);
+ }
}
}
} else {
if(project==null){
res.getWriter().println("Error: Project not saved in DB.");
res.setStatus(500);
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
byte[] data = IOUtils.toByteArray(item.openStream());
BlobKey blobKey = createBlob(data, res);
images.put(item.getFieldName(), blobKey);
}
}
}
} catch (IllegalStateException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
} catch (FileUploadException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
}
Picture picture = new Picture();
BlobKey imageKey = images.get("main");
picture.setKey(imageKey);
BlobKey thumbKey = images.get("thumb");
picture.setThumbKey(thumbKey);
picture.intUrl();
picture.setInfo(info);
picture.setLinks(links);
picture.setLinksText(linkTexts);
portfolioService.addImage(picture, project);
}
private BlobKey createBlob(byte[] data, HttpServletResponse response) throws IOException{
// Get a file service
FileService fileService = FileServiceFactory.getFileService();
// Create a new Blob file with mime-type "text/plain"
AppEngineFile file = fileService.createNewBlobFile("image/jpeg");
// Open a channel to write to it
boolean lock = false;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
String path = file.getFullPath();
// Write more to the file in a separate request:
file = new AppEngineFile(path);
// This time lock because we intend to finalize
lock = true;
writeChannel = fileService.openWriteChannel(file, lock);
// This time we write to the channel directly
writeChannel.write(ByteBuffer.wrap(data));
// Now finalize
writeChannel.closeFinally();
// Now read from the file using the Blobstore API
BlobKey blobKey = fileService.getBlobKey(file);
return blobKey;
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
/**
* Set up properties of your new object
* After finalizing objects, they are accessible
* through Cloud Storage with the URL:
* http://commondatastorage.googleapis.com/my_bucket/my_object
*/
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
PortfolioService portfolioService = PortfolioServiceFactory.getPortfolioService();
Project project = null;
List<String> info = new ArrayList<String>();
List<String> links = new ArrayList<String>();
List<String> linkTexts = new ArrayList<String>();
Map<String, BlobKey> images = new HashMap<String, BlobKey>();
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// get Project to add image to
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer);
String theString = writer.toString();
if(item.getFieldName().equals("project_id")){
String projId = URLDecoder.decode(theString);
Long id = Long.parseLong(projId);
project = portfolioService.getProject(id);
} else {
if(item.getFieldName().contains("display_text")){
info.add(theString);
} else if(item.getFieldName().contains("link")){
links.add(theString);
} else if(item.getFieldName().contains("link_text")){
linkTexts.add(theString);
}
}
} else {
if(project==null){
res.getWriter().println("Error: Project not saved in DB.");
res.setStatus(500);
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
byte[] data = IOUtils.toByteArray(item.openStream());
BlobKey blobKey = createBlob(data, res);
images.put(item.getFieldName(), blobKey);
}
}
}
} catch (IllegalStateException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
} catch (FileUploadException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
}
Picture picture = new Picture();
BlobKey imageKey = images.get("main");
picture.setKey(imageKey);
BlobKey thumbKey = images.get("thumb");
picture.setThumbKey(thumbKey);
picture.intUrl();
picture.setInfo(info);
picture.setLinks(links);
picture.setLinksText(linkTexts);
portfolioService.addImage(picture, project);
}
| public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
/**
* Set up properties of your new object
* After finalizing objects, they are accessible
* through Cloud Storage with the URL:
* http://commondatastorage.googleapis.com/my_bucket/my_object
*/
ServletFileUpload upload = new ServletFileUpload();
res.setContentType("text/plain");
PortfolioService portfolioService = PortfolioServiceFactory.getPortfolioService();
Project project = null;
List<String> info = new ArrayList<String>();
List<String> links = new ArrayList<String>();
List<String> linkTexts = new ArrayList<String>();
Map<String, BlobKey> images = new HashMap<String, BlobKey>();
FileItemIterator iterator = null;
try {
iterator = upload.getItemIterator(req);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// get Project to add image to
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if (item.isFormField()) {
log.warning("Got a form field: " + item.getFieldName());
StringWriter writer = new StringWriter();
IOUtils.copy(stream, writer);
String theString = writer.toString();
if(item.getFieldName().equals("project_id")){
String projId = URLDecoder.decode(theString);
Long id = Long.parseLong(projId);
project = portfolioService.getProject(id);
} else {
if(theString!=null){
if(item.getFieldName().contains("display_text")){
info.add(theString);
} else if(item.getFieldName().contains("link")){
links.add(theString);
} else if(item.getFieldName().contains("link_text")){
linkTexts.add(theString);
}
}
}
} else {
if(project==null){
res.getWriter().println("Error: Project not saved in DB.");
res.setStatus(500);
} else {
log.warning("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
byte[] data = IOUtils.toByteArray(item.openStream());
BlobKey blobKey = createBlob(data, res);
images.put(item.getFieldName(), blobKey);
}
}
}
} catch (IllegalStateException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
} catch (FileUploadException e) {
res.getWriter().println("Error: Occurred during upload: "+e.getMessage());
res.setStatus(500);
}
Picture picture = new Picture();
BlobKey imageKey = images.get("main");
picture.setKey(imageKey);
BlobKey thumbKey = images.get("thumb");
picture.setThumbKey(thumbKey);
picture.intUrl();
picture.setInfo(info);
picture.setLinks(links);
picture.setLinksText(linkTexts);
portfolioService.addImage(picture, project);
}
|
diff --git a/src/ca/liquidlabs/android/speedtestvisualizer/MainActivity.java b/src/ca/liquidlabs/android/speedtestvisualizer/MainActivity.java
index db7e87e..692cd62 100644
--- a/src/ca/liquidlabs/android/speedtestvisualizer/MainActivity.java
+++ b/src/ca/liquidlabs/android/speedtestvisualizer/MainActivity.java
@@ -1,376 +1,376 @@
/*
* Copyright 2013 Liquid Labs Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ca.liquidlabs.android.speedtestvisualizer;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import ca.liquidlabs.android.speedtestvisualizer.activities.AboutAppActivity;
import ca.liquidlabs.android.speedtestvisualizer.activities.DataStatsActivity;
import ca.liquidlabs.android.speedtestvisualizer.activities.MapperActivity;
import ca.liquidlabs.android.speedtestvisualizer.fragments.InputDialogFragment;
import ca.liquidlabs.android.speedtestvisualizer.fragments.InputDialogFragment.InputDialogListener;
import ca.liquidlabs.android.speedtestvisualizer.util.AppConstants;
import ca.liquidlabs.android.speedtestvisualizer.util.AppPackageUtils;
import ca.liquidlabs.android.speedtestvisualizer.util.CsvDataParser;
import ca.liquidlabs.android.speedtestvisualizer.util.Tracer;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.common.GooglePlayServicesUtil;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* Main entry point launcher activity. Data is loaded here and verified before
* loading maps view.
*/
public class MainActivity extends Activity implements InputDialogListener {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
//
// UI Views Used for this activity
//
private ImageView mIconFeedback;
private TextView mMessageTextView;
private Button mSpeedtestLinkButton;
private Button mRelaunchMapButton;
private Button mLaunchStatsButton;
private LinearLayout mButtonContainer;
// Share action provider for menu item
private ShareActionProvider mShareActionProvider;
/**
* Validated CSV data saved in memory
*/
private static String mLastSessionValidData = null;
private static boolean mIsSharedIntent = false;
/**
* Part of CSV header text, used for data validation
*/
private String mCsvHeaderValidationText = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tracer.debug(LOG_TAG, "onCreate");
/*
* Get reference to views
*/
mIconFeedback = (ImageView) findViewById(R.id.ic_user_feedback);
mMessageTextView = (TextView) findViewById(R.id.txt_user_feedback_guide);
mSpeedtestLinkButton = (Button) findViewById(R.id.btn_speedtest_app_link);
mRelaunchMapButton = (Button) findViewById(R.id.btn_relaunch_map);
mLaunchStatsButton = (Button) findViewById(R.id.btn_launch_stats);
mButtonContainer = (LinearLayout) findViewById(R.id.button_container);
// Also load the CSV record header text, which is needed to validate
mCsvHeaderValidationText = this.getString(R.string.speedtest_csv_header_validation);
/*
* Get intent, action and MIME type More info/guide:
* http://developer.android.com/training/sharing/receive.html
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
- Bundle bundle = intent.getExtras();
+ // URI is only available in 3.0
+ Uri exportFileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (Intent.ACTION_SEND.equals(action) && type != null) {
mIsSharedIntent = true;
if ("text/plain".equals(type)) {
/*
* Check if this is coming from Speedtest v3.0 app (which has
- * attachment file)
+ * attachment file in URI)
*/
- if (bundle != null) {
- Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
+ if (exportFileUri != null) {
try {
- InputStream inputStream = getContentResolver().openInputStream(uri);
+ InputStream inputStream = getContentResolver().openInputStream(exportFileUri);
handleIntentText(AppPackageUtils.convertStreamToString(inputStream));
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, "Unable to find file from URI", e);
// unsupported mimetype/data
this.handleInvalidText();
} catch (Exception e) {
Log.e(LOG_TAG, "Unable to handle data.", e);
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
/*
* Fall back to old version implementation
*/
// Handle text being sent
handleIntentText(intent.getStringExtra(Intent.EXTRA_TEXT));
}
} else {
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
// Handle other intents, such as being started from the home screen
}
}
@Override
protected void onStart() {
super.onStart();
Tracer.debug(LOG_TAG, "onStart");
// Tracks activity view using analytics.
EasyTracker.getInstance().activityStart(this);
// Prepare session UI data - based on user input
this.prepareSessionDataUi();
// Prepare button to proper speedtest link
this.prepareSpeedTestLink();
}
@Override
public void onStop() {
super.onStop();
// Tracks activity view using analytics.
EasyTracker.getInstance().activityStop(this);
}
/**
* Handle intent data when shared from speedtest or other app
*
* @param intent Intent received by this activity
*/
private void handleIntentText(String sharedText) {
Tracer.debug(LOG_TAG, "handleIntentText() " + sharedText);
if (CsvDataParser.isValidCsvData(mCsvHeaderValidationText, sharedText)) {
// save the valid data in for current session
mLastSessionValidData = sharedText;
mIsSharedIntent = false;
this.launchDataVisualizerActivity(sharedText, MapperActivity.class);
} else {
this.handleInvalidText();
}
}
/**
* Handle text provided by user from clipboard
*
* @param data User data
*/
private void handleLocalText(String data) {
Tracer.debug(LOG_TAG, "handleLocalText()");
if (CsvDataParser.isValidCsvData(mCsvHeaderValidationText, data)) {
// save the valid data in for current session
mLastSessionValidData = data;
this.launchDataVisualizerActivity(data, MapperActivity.class);
} else {
this.handleInvalidText();
}
}
/**
* Unexpected text is shared/input. Show user feedback.
*/
private void handleInvalidText() {
Tracer.debug(LOG_TAG, "handleInvalidText()");
// give ui feedback with error
mIconFeedback.setImageResource(R.drawable.ic_disappoint);
mMessageTextView.setText(R.string.msg_invalid_data);
mButtonContainer.setVisibility(View.GONE);
}
/**
* Shows input dialog fragment to take input from user
*/
private void showInputDialog() {
FragmentManager fm = getFragmentManager();
InputDialogFragment editNameDialog = InputDialogFragment.newInstance();
editNameDialog.show(fm, "fragment_input_data");
}
/**
* Launches mapping activity when valid CSV data is found.
*
* @param csvData Valid speedtest data
* @param clazz Class activity to launch.
*/
private void launchDataVisualizerActivity(String csvData, Class<?> clazz) {
// Test data ready - go to maps view
Intent intent = new Intent(this, clazz);
intent.putExtra(AppConstants.KEY_SPEEDTEST_CSV_HEADER, mCsvHeaderValidationText);
intent.putExtra(AppConstants.KEY_SPEEDTEST_CSV_DATA, csvData);
startActivity(intent);
// apply slide-in animation
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
/**
* Prepares UI for current session - if user has already imported some data
*/
private void prepareSessionDataUi() {
// if shared intent, UI has been already populated
if (mIsSharedIntent) {
return;
}
if (mLastSessionValidData != null) {
// valid data exist, user already used some data to see maps
mIconFeedback.setImageResource(R.drawable.ic_smile_success);
mMessageTextView.setText(R.string.msg_valid_data_session_available);
mRelaunchMapButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
launchDataVisualizerActivity(mLastSessionValidData, MapperActivity.class);
}
});
mLaunchStatsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
launchDataVisualizerActivity(mLastSessionValidData, DataStatsActivity.class);
}
});
mButtonContainer.setVisibility(View.VISIBLE);
} else {
// Welcome user and show instructions UI
mIconFeedback.setImageResource(R.drawable.ic_dialog_bubble);
mMessageTextView.setText(R.string.msg_welcome_instructions);
// TODO: Show button with YouTube demo link
mButtonContainer.setVisibility(View.GONE);
}
}
/**
* Prepares speedtest app link button to help user to easily install or
* launch app.
*/
private void prepareSpeedTestLink() {
Tracer.debug(LOG_TAG, "prepareSpeedTestLink()");
if (AppPackageUtils.isSpeedTestAppInstalled(getApplicationContext())) {
// Prepare link to SpeedTest app
mSpeedtestLinkButton.setText(R.string.lbl_launch_speedtest_app);
mSpeedtestLinkButton.setCompoundDrawablesWithIntrinsicBounds(AppPackageUtils
.getAppIcon(getApplicationContext(), AppConstants.PACKAGE_SPEEDTEST_APP), null,
null, null);
// Also setup click listener
mSpeedtestLinkButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(AppPackageUtils.getSpeedTestAppIntent(getApplicationContext()));
}
});
} else {
// Prepare link to SpeedTest app in Google Play
mSpeedtestLinkButton.setText(R.string.lbl_get_app_googleplay);
mSpeedtestLinkButton.setCompoundDrawablesWithIntrinsicBounds(
AppPackageUtils.getAppIcon(getApplicationContext(),
GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE),
null, null, null);
// Setup play store intent
mSpeedtestLinkButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(AppConstants.PLAY_STORE_BASE_NATIVE_URI
+ AppConstants.PACKAGE_SPEEDTEST_APP)));
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// Locate MenuItem with ShareActionProvider
MenuItem item = menu.findItem(R.id.action_share_app);
// Fetch and store ShareActionProvider. More info @
// http://developer.android.com/training/sharing/shareaction.html
mShareActionProvider = (ShareActionProvider) item.getActionProvider();
// Share app using share action provider
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(AppPackageUtils.getShareAppIntent(
getApplicationContext()));
}
// Return true to display menu
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_paste_data:
showInputDialog();
return true;
case R.id.action_report_issue:
// Prepare email content and send intent
startActivity(Intent.createChooser(
AppPackageUtils.getReportIssueIntent(getApplicationContext()),
getString(R.string.title_dialog_choose_email)));
return true;
case R.id.action_about_app:
startActivity(new Intent(getApplicationContext(), AboutAppActivity.class));
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//
// InputDialogListener implementation
//
/**
* Callback from input dialog fragment with data
*/
@Override
public void onFinishEditDialog(String inputText) {
Tracer.debug(LOG_TAG, "onFinishEditDialog: " + inputText);
this.handleLocalText(inputText);
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tracer.debug(LOG_TAG, "onCreate");
/*
* Get reference to views
*/
mIconFeedback = (ImageView) findViewById(R.id.ic_user_feedback);
mMessageTextView = (TextView) findViewById(R.id.txt_user_feedback_guide);
mSpeedtestLinkButton = (Button) findViewById(R.id.btn_speedtest_app_link);
mRelaunchMapButton = (Button) findViewById(R.id.btn_relaunch_map);
mLaunchStatsButton = (Button) findViewById(R.id.btn_launch_stats);
mButtonContainer = (LinearLayout) findViewById(R.id.button_container);
// Also load the CSV record header text, which is needed to validate
mCsvHeaderValidationText = this.getString(R.string.speedtest_csv_header_validation);
/*
* Get intent, action and MIME type More info/guide:
* http://developer.android.com/training/sharing/receive.html
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Bundle bundle = intent.getExtras();
if (Intent.ACTION_SEND.equals(action) && type != null) {
mIsSharedIntent = true;
if ("text/plain".equals(type)) {
/*
* Check if this is coming from Speedtest v3.0 app (which has
* attachment file)
*/
if (bundle != null) {
Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
try {
InputStream inputStream = getContentResolver().openInputStream(uri);
handleIntentText(AppPackageUtils.convertStreamToString(inputStream));
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, "Unable to find file from URI", e);
// unsupported mimetype/data
this.handleInvalidText();
} catch (Exception e) {
Log.e(LOG_TAG, "Unable to handle data.", e);
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
/*
* Fall back to old version implementation
*/
// Handle text being sent
handleIntentText(intent.getStringExtra(Intent.EXTRA_TEXT));
}
} else {
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
// Handle other intents, such as being started from the home screen
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Tracer.debug(LOG_TAG, "onCreate");
/*
* Get reference to views
*/
mIconFeedback = (ImageView) findViewById(R.id.ic_user_feedback);
mMessageTextView = (TextView) findViewById(R.id.txt_user_feedback_guide);
mSpeedtestLinkButton = (Button) findViewById(R.id.btn_speedtest_app_link);
mRelaunchMapButton = (Button) findViewById(R.id.btn_relaunch_map);
mLaunchStatsButton = (Button) findViewById(R.id.btn_launch_stats);
mButtonContainer = (LinearLayout) findViewById(R.id.button_container);
// Also load the CSV record header text, which is needed to validate
mCsvHeaderValidationText = this.getString(R.string.speedtest_csv_header_validation);
/*
* Get intent, action and MIME type More info/guide:
* http://developer.android.com/training/sharing/receive.html
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
// URI is only available in 3.0
Uri exportFileUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (Intent.ACTION_SEND.equals(action) && type != null) {
mIsSharedIntent = true;
if ("text/plain".equals(type)) {
/*
* Check if this is coming from Speedtest v3.0 app (which has
* attachment file in URI)
*/
if (exportFileUri != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(exportFileUri);
handleIntentText(AppPackageUtils.convertStreamToString(inputStream));
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, "Unable to find file from URI", e);
// unsupported mimetype/data
this.handleInvalidText();
} catch (Exception e) {
Log.e(LOG_TAG, "Unable to handle data.", e);
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
/*
* Fall back to old version implementation
*/
// Handle text being sent
handleIntentText(intent.getStringExtra(Intent.EXTRA_TEXT));
}
} else {
// unsupported mimetype/data
this.handleInvalidText();
}
} else {
// Handle other intents, such as being started from the home screen
}
}
|
diff --git a/src/main/java/net/benas/jpopulator/impl/DefaultRandomizer.java b/src/main/java/net/benas/jpopulator/impl/DefaultRandomizer.java
index 46d6a321..12457404 100644
--- a/src/main/java/net/benas/jpopulator/impl/DefaultRandomizer.java
+++ b/src/main/java/net/benas/jpopulator/impl/DefaultRandomizer.java
@@ -1,138 +1,138 @@
/*
* The MIT License
*
* Copyright (c) 2013, benas (md.benhassine@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.benas.jpopulator.impl;
import org.apache.commons.lang.RandomStringUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* This class is used to generate random value for java built-in types.
*
* @author benas (md.benhassine@gmail.com)
*/
final class DefaultRandomizer {
private static final Random random = new Random();
/**
* Generate a random value for the given type.
*
* @param type the type for which a random value will be generated
* @return a random value for the given type or null if the type is not supported
*/
public static Object getRandomValue(Class type) {
/*
* String and Character types
*/
if (type.equals(String.class)) {
return RandomStringUtils.randomAlphabetic(10);
}
if (type.equals(Character.TYPE) || type.equals(Character.class)) {
return RandomStringUtils.randomAlphabetic(1).charAt(0);
}
/*
* Boolean type
*/
if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
return random.nextBoolean();
}
/*
* Numeric types
*/
if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
return (byte) (random.nextInt());
}
if (type.equals(Short.TYPE) || type.equals(Short.class)) {
return (short) (random.nextInt());
}
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
return random.nextInt();
}
if (type.equals(Long.TYPE) || type.equals(Long.class)) {
return random.nextLong();
}
if (type.equals(Double.TYPE) || type.equals(Double.class)) {
return random.nextDouble();
}
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
return random.nextFloat();
}
if (type.equals(BigInteger.class)) {
- return new BigInteger(random.nextInt(), random);
+ return new BigInteger(Math.abs(random.nextInt()), random);
}
if (type.equals(BigDecimal.class)) {
return new BigDecimal(random.nextDouble());
}
if (type.equals(AtomicLong.class)) {
return new AtomicLong(random.nextLong());
}
if (type.equals(AtomicInteger.class)) {
return new AtomicInteger(random.nextInt());
}
/*
* Date and time types
*/
if (type.equals(java.util.Date.class)) {
return new java.util.Date(random.nextLong());
}
if (type.equals(java.sql.Date.class)) {
return new java.sql.Date(random.nextLong());
}
if (type.equals(java.sql.Time.class)) {
return new java.sql.Time(random.nextLong());
}
if (type.equals(java.sql.Timestamp.class)) {
return new java.sql.Timestamp(random.nextLong());
}
if (type.equals(Calendar.class)) {
return Calendar.getInstance();
}
/*
* Enum type
*/
if (type.isEnum() && type.getEnumConstants().length > 0) {
Object[] enumConstants = type.getEnumConstants();
return enumConstants[random.nextInt(enumConstants.length)];
}
/*
* Return null for any unsupported type
*/
return null;
}
}
| true | true | public static Object getRandomValue(Class type) {
/*
* String and Character types
*/
if (type.equals(String.class)) {
return RandomStringUtils.randomAlphabetic(10);
}
if (type.equals(Character.TYPE) || type.equals(Character.class)) {
return RandomStringUtils.randomAlphabetic(1).charAt(0);
}
/*
* Boolean type
*/
if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
return random.nextBoolean();
}
/*
* Numeric types
*/
if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
return (byte) (random.nextInt());
}
if (type.equals(Short.TYPE) || type.equals(Short.class)) {
return (short) (random.nextInt());
}
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
return random.nextInt();
}
if (type.equals(Long.TYPE) || type.equals(Long.class)) {
return random.nextLong();
}
if (type.equals(Double.TYPE) || type.equals(Double.class)) {
return random.nextDouble();
}
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
return random.nextFloat();
}
if (type.equals(BigInteger.class)) {
return new BigInteger(random.nextInt(), random);
}
if (type.equals(BigDecimal.class)) {
return new BigDecimal(random.nextDouble());
}
if (type.equals(AtomicLong.class)) {
return new AtomicLong(random.nextLong());
}
if (type.equals(AtomicInteger.class)) {
return new AtomicInteger(random.nextInt());
}
/*
* Date and time types
*/
if (type.equals(java.util.Date.class)) {
return new java.util.Date(random.nextLong());
}
if (type.equals(java.sql.Date.class)) {
return new java.sql.Date(random.nextLong());
}
if (type.equals(java.sql.Time.class)) {
return new java.sql.Time(random.nextLong());
}
if (type.equals(java.sql.Timestamp.class)) {
return new java.sql.Timestamp(random.nextLong());
}
if (type.equals(Calendar.class)) {
return Calendar.getInstance();
}
/*
* Enum type
*/
if (type.isEnum() && type.getEnumConstants().length > 0) {
Object[] enumConstants = type.getEnumConstants();
return enumConstants[random.nextInt(enumConstants.length)];
}
/*
* Return null for any unsupported type
*/
return null;
}
| public static Object getRandomValue(Class type) {
/*
* String and Character types
*/
if (type.equals(String.class)) {
return RandomStringUtils.randomAlphabetic(10);
}
if (type.equals(Character.TYPE) || type.equals(Character.class)) {
return RandomStringUtils.randomAlphabetic(1).charAt(0);
}
/*
* Boolean type
*/
if (type.equals(Boolean.TYPE) || type.equals(Boolean.class)) {
return random.nextBoolean();
}
/*
* Numeric types
*/
if (type.equals(Byte.TYPE) || type.equals(Byte.class)) {
return (byte) (random.nextInt());
}
if (type.equals(Short.TYPE) || type.equals(Short.class)) {
return (short) (random.nextInt());
}
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
return random.nextInt();
}
if (type.equals(Long.TYPE) || type.equals(Long.class)) {
return random.nextLong();
}
if (type.equals(Double.TYPE) || type.equals(Double.class)) {
return random.nextDouble();
}
if (type.equals(Float.TYPE) || type.equals(Float.class)) {
return random.nextFloat();
}
if (type.equals(BigInteger.class)) {
return new BigInteger(Math.abs(random.nextInt()), random);
}
if (type.equals(BigDecimal.class)) {
return new BigDecimal(random.nextDouble());
}
if (type.equals(AtomicLong.class)) {
return new AtomicLong(random.nextLong());
}
if (type.equals(AtomicInteger.class)) {
return new AtomicInteger(random.nextInt());
}
/*
* Date and time types
*/
if (type.equals(java.util.Date.class)) {
return new java.util.Date(random.nextLong());
}
if (type.equals(java.sql.Date.class)) {
return new java.sql.Date(random.nextLong());
}
if (type.equals(java.sql.Time.class)) {
return new java.sql.Time(random.nextLong());
}
if (type.equals(java.sql.Timestamp.class)) {
return new java.sql.Timestamp(random.nextLong());
}
if (type.equals(Calendar.class)) {
return Calendar.getInstance();
}
/*
* Enum type
*/
if (type.isEnum() && type.getEnumConstants().length > 0) {
Object[] enumConstants = type.getEnumConstants();
return enumConstants[random.nextInt(enumConstants.length)];
}
/*
* Return null for any unsupported type
*/
return null;
}
|
diff --git a/src/com/jme/scene/model/XMLparser/Converters/ObjToJme.java b/src/com/jme/scene/model/XMLparser/Converters/ObjToJme.java
index b2764059a..5807a258d 100755
--- a/src/com/jme/scene/model/XMLparser/Converters/ObjToJme.java
+++ b/src/com/jme/scene/model/XMLparser/Converters/ObjToJme.java
@@ -1,359 +1,361 @@
package com.jme.scene.model.XMLparser.Converters;
import com.jme.math.Vector3f;
import com.jme.math.Vector2f;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.model.XMLparser.JmeBinaryWriter;
import com.jme.scene.Node;
import com.jme.scene.TriMesh;
import com.jme.scene.Spatial;
import com.jme.system.DisplaySystem;
import com.jme.renderer.ColorRGBA;
import com.jme.image.Texture;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.net.URL;
/**
* Started Date: Jul 17, 2004<br><br>
*
* Converts .obj files into .jme binary format. In order for ObjToJme to find the .mtl library, you must specify the
* "mtllib" tag to the baseURL where the mtl libraries are to be found. Somewhat similar to this.setProperty("mtllib",objFile);
*
* @author Jack Lindamood
*/
public class ObjToJme extends FormatConverter{
private BufferedReader inFile;
/** Every vertex in the file*/
private ArrayList vertexList=new ArrayList();
/** Every texture coordinate in the file*/
private ArrayList textureList=new ArrayList();
/** Every normal in the file*/
private ArrayList normalList=new ArrayList();
/** Last 'material' flag in the file*/
private MaterialGrouping curGroup;
/** Default material group for groups without a material*/
private final MaterialGrouping DEFAULT_GROUP=new MaterialGrouping();
/** Maps material names to the actual material object **/
private HashMap materialNames=new HashMap();
/** Maps Materials to their vertex usage **/
private HashMap materialSets=new HashMap();
/**
* Converts an Obj file to jME format. The syntax is: "ObjToJme file.obj outfile.jme".
* @param args The array of parameters
*/
public static void main(String[] args){
new DummyDisplaySystem();
new ObjToJme().attemptFileConvert(args);
}
/**
* Converts an .obj file to .jme format. If you wish to use a .mtl to load the obj's material information please specify
* the base url where the .mtl is located with setProperty("mtllib",new URL(baseURL))
* @param format The .obj file's stream.
* @param jMEFormat The .jme file's stream.
* @throws IOException If anything bad happens.
*/
public void convert(InputStream format, OutputStream jMEFormat) throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
materialSets.clear();
materialNames.clear();
inFile=new BufferedReader(new InputStreamReader(format));
String in;
curGroup=DEFAULT_GROUP;
materialSets.put(DEFAULT_GROUP,new ArraySet());
while ((in=inFile.readLine())!=null){
processLine(in);
}
new JmeBinaryWriter().writeScene(buildStructure(),jMEFormat);
nullAll();
}
/**
* Nulls all to let the gc do its job.
* @throws IOException
*/
private void nullAll() throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
curGroup=null;
materialSets.clear();
materialNames.clear();
inFile.close();
inFile=null;
}
/**
* Converts the structures of the .obj file to a scene to write
* @return The TriMesh or Node that represents the .obj file.
*/
private Spatial buildStructure() {
Node toReturn=new Node("obj file");
Object[] o=materialSets.keySet().toArray();
for (int i=0;i<o.length;i++){
MaterialGrouping thisGroup=(MaterialGrouping) o[i];
ArraySet thisSet=(ArraySet) materialSets.get(thisGroup);
if (thisSet.indexes.size()<3) continue;
TriMesh thisMesh=new TriMesh("temp"+i);
Vector3f[] vert=new Vector3f[thisSet.vertexes.size()];
Vector3f[] norm=new Vector3f[thisSet.vertexes.size()];
Vector2f[] text=new Vector2f[thisSet.vertexes.size()];
for (int j=0;j<thisSet.vertexes.size();j++){
vert[j]=(Vector3f) thisSet.vertexes.get(j);
norm[j]=(Vector3f) thisSet.normals.get(j);
text[j]=(Vector2f) thisSet.textures.get(j);
}
int[] indexes=new int[thisSet.indexes.size()];
for (int j=0;j<thisSet.indexes.size();j++)
indexes[j]=((Integer)thisSet.indexes.get(j)).intValue();
thisMesh.reconstruct(vert, norm,null,text, indexes);
if (properties.get("sillycolors")!=null)
thisMesh.setRandomColors();
if (thisGroup.ts.isEnabled()) thisMesh.setRenderState(thisGroup.ts);
thisMesh.setRenderState(thisGroup.m);
toReturn.attachChild(thisMesh);
}
if (toReturn.getQuantity()==1)
return toReturn.getChild(0);
else
return toReturn;
}
/**
* Processes a line of text in the .obj file.
* @param s The line of text in the file.
* @throws IOException
*/
private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
- if (materialNames.get(parts[1])!=null && materialNames.get(parts[1])!=null)
- curGroup=(MaterialGrouping) materialNames.get(parts[1]);
- else
+ //see what the material name is if there isn't a name, assume its the default group
+ if (parts.length >= 2 && materialNames.get(parts[1]) != null
+ && materialNames.get(parts[1]) != null)
+ curGroup = (MaterialGrouping) materialNames.get(parts[1]);
+ else
setDefaultGroup();
- return;
+ return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
private String[] removeEmpty(String[] parts) {
int cnt=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals(""))
cnt++;
}
String[] toReturn=new String[cnt];
int index=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals("")){
toReturn[index++]=parts[i];
}
}
return toReturn;
}
private void addMaterial(String[] parts) {
MaterialGrouping newMat=new MaterialGrouping();
materialNames.put(parts[1],newMat);
materialSets.put(newMat,new ArraySet());
curGroup=newMat;
}
private void loadMaterials(String[] fileNames) throws IOException {
URL matURL=(URL) properties.get("mtllib");
if (matURL==null) return;
for (int i=1;i<fileNames.length;i++){
processMaterialFile(new URL(matURL,fileNames[i]).openStream());
}
}
private void processMaterialFile(InputStream inputStream) throws IOException {
BufferedReader matFile=new BufferedReader(new InputStreamReader(inputStream));
String in;
while ((in=matFile.readLine())!=null){
processLine(in);
}
}
private void addFaces(String[] parts) {
ArraySet thisMat=(ArraySet) materialSets.get(curGroup);
IndexSet first=new IndexSet(parts[1]);
int firstIndex=thisMat.findSet(first);
IndexSet second=new IndexSet(parts[2]);
int secondIndex=thisMat.findSet(second);
IndexSet third=new IndexSet();
for (int i=3;i<parts.length;i++){
third.parseStringArray(parts[i]);
thisMat.indexes.add(new Integer(firstIndex));
thisMat.indexes.add(new Integer(secondIndex));
int thirdIndex=thisMat.findSet(third);
thisMat.indexes.add(new Integer(thirdIndex));
}
}
private void setDefaultGroup() {
curGroup=DEFAULT_GROUP;
}
private void addNormalToList(String[] parts) {
normalList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private void addTextoList(String[] parts) {
if (parts.length==2)
textureList.add(new Vector2f(Float.parseFloat(parts[1]),0));
else
textureList.add(new Vector2f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2])));
}
private void addVertextoList(String[] parts) {
vertexList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private class MaterialGrouping{
public MaterialGrouping(){
m=DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
m.setAmbient(new ColorRGBA(.2f,.2f,.2f,1));
m.setDiffuse(new ColorRGBA(.8f,.8f,.8f,1));
m.setSpecular(ColorRGBA.white);
m.setEnabled(true);
ts=DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
}
MaterialState m;
TextureState ts;
}
/**
* Stores a complete set of vertex/texture/normal triplet set that is to be indexed by the TriMesh.
*/
private class IndexSet{
public IndexSet(){}
public IndexSet(String parts){
parseStringArray(parts);
}
public void parseStringArray(String parts){
int vIndex,nIndex,tIndex;
String[] triplet=parts.split("/");
vIndex=Integer.parseInt(triplet[0]);
if (vIndex<0){
vertex=(Vector3f) vertexList.get(vertexList.size()+vIndex);
} else{
vertex=(Vector3f) vertexList.get(vIndex-1); // obj is 1 indexed
}
if (triplet[1]==null || triplet[1].equals("")){
texture=null;
} else{
tIndex=Integer.parseInt(triplet[1]);
if (tIndex<0){
texture=(Vector2f) textureList.get(textureList.size()+tIndex);
} else{
texture=(Vector2f) textureList.get(tIndex-1); // obj is 1 indexed
}
}
if (triplet.length!=3 || triplet[2]==null || triplet[2].equals("")){
normal=null;
} else{
nIndex=Integer.parseInt(triplet[2]);
if (nIndex<0){
normal=(Vector3f) normalList.get(normalList.size()+nIndex);
} else{
normal=(Vector3f) normalList.get(nIndex-1); // obj is 1 indexed
}
}
}
Vector3f vertex;
Vector2f texture;
Vector3f normal;
}
/**
* An array of information that will become a renderable trimesh. Each material has it's own trimesh.
*/
private class ArraySet{
private ArrayList vertexes=new ArrayList();
private ArrayList normals=new ArrayList();
private ArrayList textures=new ArrayList();
private ArrayList indexes=new ArrayList();
public int findSet(IndexSet v) {
int i=0;
for (i=0;i<normals.size();i++){
if (compareObjects(v.normal,normals.get(i)) &&
compareObjects(v.texture,textures.get(i)) &&
compareObjects(v.vertex,vertexes.get(i)))
return i;
}
normals.add(v.normal);
textures.add(v.texture);
vertexes.add(v.vertex);
return i;
}
private boolean compareObjects(Object o1, Object o2) {
if (o1==null) return (o2==null);
if (o2==null) return false;
return o1.equals(o2);
}
}
}
| false | true | private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
if (materialNames.get(parts[1])!=null && materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
| private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
//see what the material name is if there isn't a name, assume its the default group
if (parts.length >= 2 && materialNames.get(parts[1]) != null
&& materialNames.get(parts[1]) != null)
curGroup = (MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.substring(6).trim());
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
|
diff --git a/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java b/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java
index cf46c5f..709b64a 100644
--- a/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java
+++ b/src/com/webkonsept/bukkit/simplechestlock/listener/SCLPlayerListener.java
@@ -1,285 +1,301 @@
package com.webkonsept.bukkit.simplechestlock.listener;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.webkonsept.bukkit.simplechestlock.SCL;
import com.webkonsept.bukkit.simplechestlock.locks.SCLItem;
public class SCLPlayerListener implements Listener {
final SCL plugin;
public SCLPlayerListener(SCL instance) {
plugin = instance;
}
private String ucfirst(String string){
return string.substring(0,1).toUpperCase() + string.substring(1);
}
// TODO: Break up this monster method, plx!
@EventHandler
public void onPlayerInteract (final PlayerInteractEvent event){
if (! plugin.isEnabled() ) return;
if ( event.isCancelled() ) return;
Block block = event.getClickedBlock();
ItemStack toolUsed = null;
if (event.getItem() != null){
toolUsed = event.getItem().clone();
toolUsed.setAmount(1);
}
Player player = event.getPlayer();
if (block == null) return; // We don't care about non-block (air) interactions.
if (plugin.canLock(block)){
String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase();
if(
event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
|| (
event.getAction().equals(Action.LEFT_CLICK_BLOCK)
&& plugin.leftLocked.contains(block.getType())
&& !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey()))
)
|| event.getAction().equals(Action.PHYSICAL)
){
if (plugin.chests.isLocked(block)){
SCLItem lockedItem = plugin.chests.getItem(block);
String owner = lockedItem.getOwner();
SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName);
boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner");
boolean comboLocked = lockedItem.isComboLocked();
if (comboLocked){
SCL.verbose("This block is locked with a combination lock!");
}
else {
SCL.verbose("This block is locked with a normal key");
}
if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
Inventory inv = player.getInventory();
if (
- inv.getItem(0).getType().equals(Material.WOOL)
- && inv.getItem(1).getType().equals(Material.WOOL)
- && inv.getItem(2).getType().equals(Material.WOOL)
+ (
+ inv.getItem(0) != null
+ && inv.getItem(1) != null
+ && inv.getItem(2) != null
+ )
+ && // For readability, I didn't bunch up all the &&s.
+ (
+ inv.getItem(0).getType().equals(Material.WOOL)
+ && inv.getItem(1).getType().equals(Material.WOOL)
+ && inv.getItem(2).getType().equals(Material.WOOL)
+ )
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
if (!lockedItem.correctCombo(combo)){
SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination...");
event.setCancelled(true);
}
}
else {
SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock.");
event.setCancelled(true);
}
}
else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){
player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
event.setCancelled(true);
plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){
SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner.");
if (plugin.cfg.openMessage()){
player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName);
}
}
else {
SCL.verbose(player.getName() + " was let into the " + typeName);
if (plugin.cfg.openMessage()){
if (comboLocked){
String comboString = plugin.chests.getComboString(block);
player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString);
}
else {
player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName);
}
String trustedNames = lockedItem.trustedNames();
if (trustedNames != null && trustedNames.length() > 0){
player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames);
}
}
}
}
else {
SCL.verbose("Access granted to unlocked " + typeName);
}
}
else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
ItemStack inHand = event.getItem();
if (inHand == null) return;
ItemStack tool = inHand.clone();
tool.setAmount(1);
if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){
event.setCancelled(true);
if (SCL.permit(player,"simplechestlock.lock")){
if (plugin.chests.isLocked(block)){
String owner = plugin.chests.getOwner(block);
if (owner.equalsIgnoreCase(player.getName())){
Integer unlockedChests = plugin.chests.unlock(block);
if (unlockedChests == 1){
player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked");
}
else if (unlockedChests > 1){
player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked");
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName);
}
}
else if (SCL.permit(player, "simplechestlock.ignoreowner")){
Integer unlockedChests = plugin.chests.unlock(block);
Player ownerObject = Bukkit.getServer().getPlayer(owner);
if (unlockedChests == 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!");
}
else {
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified.");
}
}
else if (unlockedChests > 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!");
}
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName);
}
}
else {
player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!");
}
}
else {
if (
!(plugin.cfg.usePermissionsWhitelist())
|| (
plugin.cfg.usePermissionsWhitelist()
// Just checking for the indevidual block now, as the parent .* permission will grant them all.
&& SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase())
)
){
boolean lockForSomeone = false;
String locksFor = player.getName();
if (plugin.locksAs.containsKey(player.getName())){
locksFor = plugin.locksAs.get(player.getName());
lockForSomeone = true;
}
if (plugin.toolMatch(tool,plugin.cfg.comboKey())){
if (SCL.permit(player, "simplechestlock.usecombo")){
Inventory inv = player.getInventory();
if (
- inv.getItem(0).getType().equals(Material.WOOL)
- && inv.getItem(1).getType().equals(Material.WOOL)
- && inv.getItem(2).getType().equals(Material.WOOL)
+ (
+ inv.getItem(0) != null
+ && inv.getItem(1) != null
+ && inv.getItem(2) != null
+ )
+ && // For readability, I didn't bunch up all the &&s.
+ (
+ inv.getItem(0).getType().equals(Material.WOOL)
+ && inv.getItem(1).getType().equals(Material.WOOL)
+ && inv.getItem(2).getType().equals(Material.WOOL)
+ )
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString();
Integer itemsLocked = plugin.chests.lock(player,block,combo);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString);
}
else {
- player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+"s locked! Combo is "+comboString);
+ player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked! Combo is "+comboString);
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!");
}
}
else {
player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!");
}
}
else {
player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!");
}
}
else {
Integer itemsLocked = plugin.chests.lock(player, block);
String trustReminder = plugin.trustHandler.trustList(locksFor);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
else {
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!");
}
}
}
else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){
player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString());
}
}
}
else {
player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!");
}
}
}
}
}
}
| false | true | public void onPlayerInteract (final PlayerInteractEvent event){
if (! plugin.isEnabled() ) return;
if ( event.isCancelled() ) return;
Block block = event.getClickedBlock();
ItemStack toolUsed = null;
if (event.getItem() != null){
toolUsed = event.getItem().clone();
toolUsed.setAmount(1);
}
Player player = event.getPlayer();
if (block == null) return; // We don't care about non-block (air) interactions.
if (plugin.canLock(block)){
String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase();
if(
event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
|| (
event.getAction().equals(Action.LEFT_CLICK_BLOCK)
&& plugin.leftLocked.contains(block.getType())
&& !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey()))
)
|| event.getAction().equals(Action.PHYSICAL)
){
if (plugin.chests.isLocked(block)){
SCLItem lockedItem = plugin.chests.getItem(block);
String owner = lockedItem.getOwner();
SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName);
boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner");
boolean comboLocked = lockedItem.isComboLocked();
if (comboLocked){
SCL.verbose("This block is locked with a combination lock!");
}
else {
SCL.verbose("This block is locked with a normal key");
}
if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
Inventory inv = player.getInventory();
if (
inv.getItem(0).getType().equals(Material.WOOL)
&& inv.getItem(1).getType().equals(Material.WOOL)
&& inv.getItem(2).getType().equals(Material.WOOL)
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
if (!lockedItem.correctCombo(combo)){
SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination...");
event.setCancelled(true);
}
}
else {
SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock.");
event.setCancelled(true);
}
}
else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){
player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
event.setCancelled(true);
plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){
SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner.");
if (plugin.cfg.openMessage()){
player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName);
}
}
else {
SCL.verbose(player.getName() + " was let into the " + typeName);
if (plugin.cfg.openMessage()){
if (comboLocked){
String comboString = plugin.chests.getComboString(block);
player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString);
}
else {
player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName);
}
String trustedNames = lockedItem.trustedNames();
if (trustedNames != null && trustedNames.length() > 0){
player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames);
}
}
}
}
else {
SCL.verbose("Access granted to unlocked " + typeName);
}
}
else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
ItemStack inHand = event.getItem();
if (inHand == null) return;
ItemStack tool = inHand.clone();
tool.setAmount(1);
if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){
event.setCancelled(true);
if (SCL.permit(player,"simplechestlock.lock")){
if (plugin.chests.isLocked(block)){
String owner = plugin.chests.getOwner(block);
if (owner.equalsIgnoreCase(player.getName())){
Integer unlockedChests = plugin.chests.unlock(block);
if (unlockedChests == 1){
player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked");
}
else if (unlockedChests > 1){
player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked");
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName);
}
}
else if (SCL.permit(player, "simplechestlock.ignoreowner")){
Integer unlockedChests = plugin.chests.unlock(block);
Player ownerObject = Bukkit.getServer().getPlayer(owner);
if (unlockedChests == 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!");
}
else {
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified.");
}
}
else if (unlockedChests > 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!");
}
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName);
}
}
else {
player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!");
}
}
else {
if (
!(plugin.cfg.usePermissionsWhitelist())
|| (
plugin.cfg.usePermissionsWhitelist()
// Just checking for the indevidual block now, as the parent .* permission will grant them all.
&& SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase())
)
){
boolean lockForSomeone = false;
String locksFor = player.getName();
if (plugin.locksAs.containsKey(player.getName())){
locksFor = plugin.locksAs.get(player.getName());
lockForSomeone = true;
}
if (plugin.toolMatch(tool,plugin.cfg.comboKey())){
if (SCL.permit(player, "simplechestlock.usecombo")){
Inventory inv = player.getInventory();
if (
inv.getItem(0).getType().equals(Material.WOOL)
&& inv.getItem(1).getType().equals(Material.WOOL)
&& inv.getItem(2).getType().equals(Material.WOOL)
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString();
Integer itemsLocked = plugin.chests.lock(player,block,combo);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString);
}
else {
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+"s locked! Combo is "+comboString);
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!");
}
}
else {
player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!");
}
}
else {
player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!");
}
}
else {
Integer itemsLocked = plugin.chests.lock(player, block);
String trustReminder = plugin.trustHandler.trustList(locksFor);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
else {
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!");
}
}
}
else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){
player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString());
}
}
}
else {
player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!");
}
}
}
}
}
| public void onPlayerInteract (final PlayerInteractEvent event){
if (! plugin.isEnabled() ) return;
if ( event.isCancelled() ) return;
Block block = event.getClickedBlock();
ItemStack toolUsed = null;
if (event.getItem() != null){
toolUsed = event.getItem().clone();
toolUsed.setAmount(1);
}
Player player = event.getPlayer();
if (block == null) return; // We don't care about non-block (air) interactions.
if (plugin.canLock(block)){
String typeName = block.getType().toString().replaceAll("_", " ").toLowerCase();
if(
event.getAction().equals(Action.RIGHT_CLICK_BLOCK)
|| (
event.getAction().equals(Action.LEFT_CLICK_BLOCK)
&& plugin.leftLocked.contains(block.getType())
&& !(plugin.toolMatch(toolUsed,plugin.cfg.key()) || plugin.toolMatch(toolUsed,plugin.cfg.comboKey()))
)
|| event.getAction().equals(Action.PHYSICAL)
){
if (plugin.chests.isLocked(block)){
SCLItem lockedItem = plugin.chests.getItem(block);
String owner = lockedItem.getOwner();
SCL.verbose(player.getName() + " wants to use " + owner + "'s " + typeName);
boolean ignoreOwner = SCL.permit(player, "simplechestlock.ignoreowner");
boolean comboLocked = lockedItem.isComboLocked();
if (comboLocked){
SCL.verbose("This block is locked with a combination lock!");
}
else {
SCL.verbose("This block is locked with a normal key");
}
if ( comboLocked && ! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
Inventory inv = player.getInventory();
if (
(
inv.getItem(0) != null
&& inv.getItem(1) != null
&& inv.getItem(2) != null
)
&& // For readability, I didn't bunch up all the &&s.
(
inv.getItem(0).getType().equals(Material.WOOL)
&& inv.getItem(1).getType().equals(Material.WOOL)
&& inv.getItem(2).getType().equals(Material.WOOL)
)
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
if (!lockedItem.correctCombo(combo)){
SCL.verbose(player.getName() + " provided the wrong combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" has a different combination...");
event.setCancelled(true);
}
}
else {
SCL.verbose(player.getName() + " provided no combo for " + owner + "'s " + typeName);
plugin.messaging.throttledMessage(player,ChatColor.RED+owner+"'s "+typeName+" is locked with a combination lock.");
event.setCancelled(true);
}
}
else if (! owner.equalsIgnoreCase(player.getName()) && lockedItem.trusts(player)){
player.sendMessage(ChatColor.GREEN+owner+" trusts you with access to this "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ! ignoreOwner){
event.setCancelled(true);
plugin.messaging.throttledMessage(player,ChatColor.RED+"Access denied to "+owner+"'s "+typeName);
}
else if (! owner.equalsIgnoreCase(player.getName()) && ignoreOwner){
SCL.verbose(player.getName() + " was let into " + owner + "'s " + typeName + ", ignoring owner.");
if (plugin.cfg.openMessage()){
player.sendMessage(ChatColor.GREEN+"Access granted to "+owner+"'s "+typeName);
}
}
else {
SCL.verbose(player.getName() + " was let into the " + typeName);
if (plugin.cfg.openMessage()){
if (comboLocked){
String comboString = plugin.chests.getComboString(block);
player.sendMessage(ChatColor.GREEN+"Lock combination is "+comboString);
}
else {
player.sendMessage(ChatColor.GREEN+"Access granted to "+typeName);
}
String trustedNames = lockedItem.trustedNames();
if (trustedNames != null && trustedNames.length() > 0){
player.sendMessage(ChatColor.GREEN+"Trusted for access: "+trustedNames);
}
}
}
}
else {
SCL.verbose("Access granted to unlocked " + typeName);
}
}
else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)){
ItemStack inHand = event.getItem();
if (inHand == null) return;
ItemStack tool = inHand.clone();
tool.setAmount(1);
if (plugin.toolMatch(tool,plugin.cfg.key()) || plugin.toolMatch(tool,plugin.cfg.comboKey())){
event.setCancelled(true);
if (SCL.permit(player,"simplechestlock.lock")){
if (plugin.chests.isLocked(block)){
String owner = plugin.chests.getOwner(block);
if (owner.equalsIgnoreCase(player.getName())){
Integer unlockedChests = plugin.chests.unlock(block);
if (unlockedChests == 1){
player.sendMessage(ChatColor.GREEN+ucfirst(typeName)+" unlocked");
}
else if (unlockedChests > 1){
player.sendMessage(ChatColor.GREEN+unlockedChests.toString()+" "+typeName+"s unlocked");
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking your "+typeName);
}
}
else if (SCL.permit(player, "simplechestlock.ignoreowner")){
Integer unlockedChests = plugin.chests.unlock(block);
Player ownerObject = Bukkit.getServer().getPlayer(owner);
if (unlockedChests == 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked your "+typeName+" using mystic powers!");
}
else {
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+typeName+", but that user is offline, and was not notified.");
}
}
else if (unlockedChests > 1){
if (ownerObject != null){
player.sendMessage(ChatColor.YELLOW+"Unlocked "+owner+"'s "+unlockedChests.toString()+" "+typeName+"s, and taddle-taled on you for it.");
ownerObject.sendMessage(ChatColor.YELLOW+player.getName()+" unlocked "+unlockedChests.toString()+" of your "+typeName+"s using mystic powers!");
}
}
else {
player.sendMessage(ChatColor.RED+"Error while unlocking "+owner+"'s "+typeName);
}
}
else {
player.sendMessage(ChatColor.RED+"Locked by "+owner+": You can't use it!");
}
}
else {
if (
!(plugin.cfg.usePermissionsWhitelist())
|| (
plugin.cfg.usePermissionsWhitelist()
// Just checking for the indevidual block now, as the parent .* permission will grant them all.
&& SCL.permit(player,"simplechestlock.locktype."+block.getType().toString().toLowerCase())
)
){
boolean lockForSomeone = false;
String locksFor = player.getName();
if (plugin.locksAs.containsKey(player.getName())){
locksFor = plugin.locksAs.get(player.getName());
lockForSomeone = true;
}
if (plugin.toolMatch(tool,plugin.cfg.comboKey())){
if (SCL.permit(player, "simplechestlock.usecombo")){
Inventory inv = player.getInventory();
if (
(
inv.getItem(0) != null
&& inv.getItem(1) != null
&& inv.getItem(2) != null
)
&& // For readability, I didn't bunch up all the &&s.
(
inv.getItem(0).getType().equals(Material.WOOL)
&& inv.getItem(1).getType().equals(Material.WOOL)
&& inv.getItem(2).getType().equals(Material.WOOL)
)
){
DyeColor tumbler1 = DyeColor.getByData(inv.getItem(0).getData().getData());
DyeColor tumbler2 = DyeColor.getByData(inv.getItem(1).getData().getData());
DyeColor tumbler3 = DyeColor.getByData(inv.getItem(2).getData().getData());
DyeColor[] combo = {tumbler1,tumbler2,tumbler3};
String comboString = tumbler1.toString()+","+tumbler2.toString()+","+tumbler3.toString();
Integer itemsLocked = plugin.chests.lock(player,block,combo);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"! Combo is "+comboString);
}
else {
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked! Combo is "+comboString);
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Something horrible happened while trying to lock!");
}
}
else {
player.sendMessage(ChatColor.RED+"First three hotbar slots must be wool for the combo!");
}
}
else {
player.sendMessage(ChatColor.RED+"Sorry, permission denied for combination locking!");
}
}
else {
Integer itemsLocked = plugin.chests.lock(player, block);
String trustReminder = plugin.trustHandler.trustList(locksFor);
if (itemsLocked >= 1){
if (lockForSomeone){
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked for "+locksFor+"!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
else {
player.sendMessage(ChatColor.GREEN+itemsLocked.toString()+" "+typeName+SCL.plural(itemsLocked)+" locked!");
if (trustReminder != null){
player.sendMessage(ChatColor.GREEN+trustReminder);
}
}
if (plugin.cfg.consumeKey() && !SCL.permit(player,"simplechestlock.forfree")){
if (inHand.getAmount() > 1){
inHand.setAmount(inHand.getAmount()-1);
}
else if (inHand.getAmount() == 1){
player.setItemInHand(new ItemStack(Material.AIR));
}
else {
SCL.crap(player.getName()+" is locking stuff without being charged for it!");
}
}
}
else if (itemsLocked < 0){
player.sendMessage(ChatColor.RED+"Strange and horrible error encountered while locking!");
}
}
}
else if (plugin.cfg.usePermissionsWhitelist() && plugin.cfg.whitelistMessage()){
player.sendMessage(ChatColor.RED+"Sorry, you are not allowed to lock "+block.getType().toString());
}
}
}
else {
player.sendMessage(ChatColor.RED+"You can't lock or unlock blocks! Permission denied!");
}
}
}
}
}
|
diff --git a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java
index 3c08cc1a..900af07b 100644
--- a/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java
+++ b/software/ncimbrowser/src/java/gov/nih/nci/evs/browser/utils/DataUtils.java
@@ -1,2523 +1,2521 @@
package gov.nih.nci.evs.browser.utils;
import java.io.*;
import java.util.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.HashSet;
import java.util.Arrays;
import javax.faces.model.SelectItem;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms;
import org.LexGrid.concepts.Concept;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeRenderingList;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.CodingSchemeRendering;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ModuleDescriptionList;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.ModuleDescription;
import org.LexGrid.LexBIG.Utility.Iterators.ResolvedConceptReferencesIterator;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph;
import org.LexGrid.LexBIG.DataModel.Collections.NameAndValueList;
import org.LexGrid.LexBIG.DataModel.Core.NameAndValue;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.codingSchemes.CodingScheme;
import org.LexGrid.concepts.Definition;
import org.LexGrid.concepts.Comment;
import org.LexGrid.concepts.Presentation;
import org.apache.log4j.Logger;
import org.LexGrid.LexBIG.Exceptions.LBResourceUnavailableException;
import org.LexGrid.LexBIG.Exceptions.LBInvocationException;
import org.LexGrid.LexBIG.Utility.ConvenienceMethods;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.commonTypes.Property;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Collections.ConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.ActiveOption;
import org.LexGrid.LexBIG.Utility.ConvenienceMethods;
import org.LexGrid.commonTypes.EntityDescription;
import org.LexGrid.commonTypes.Property;
import org.LexGrid.concepts.Concept;
import org.LexGrid.relations.Relations;
import org.LexGrid.commonTypes.PropertyQualifier;
import org.LexGrid.commonTypes.Source;
import org.LexGrid.naming.SupportedSource;
import org.LexGrid.naming.SupportedPropertyQualifier;
import org.LexGrid.LexBIG.DataModel.Core.types.CodingSchemeVersionStatus;
import org.LexGrid.naming.SupportedAssociation;
import org.LexGrid.naming.SupportedAssociationQualifier;
import org.LexGrid.naming.SupportedProperty;
import org.LexGrid.naming.SupportedPropertyQualifier;
import org.LexGrid.naming.SupportedRepresentationalForm;
import org.LexGrid.naming.SupportedSource;
import org.LexGrid.LexBIG.DataModel.Collections.AssociatedConceptList;
import org.LexGrid.LexBIG.DataModel.Collections.AssociationList;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.naming.Mappings;
import org.LexGrid.naming.SupportedHierarchy;
import org.LexGrid.LexBIG.DataModel.InterfaceElements.RenderingDetail;
import org.LexGrid.LexBIG.DataModel.Collections.CodingSchemeTagList;
import gov.nih.nci.evs.browser.properties.NCImBrowserProperties;
import gov.nih.nci.evs.browser.utils.test.DBG;
import org.LexGrid.LexBIG.Exceptions.LBParameterException;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeSummary;
import org.LexGrid.LexBIG.DataModel.Core.CodingSchemeVersionOrTag;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBException;
import org.LexGrid.LexBIG.Impl.LexBIGServiceImpl;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.SearchDesignationOption;
import org.LexGrid.LexBIG.Utility.Constructors;
import org.LexGrid.LexBIG.Utility.LBConstants.MatchAlgorithms;
import org.LexGrid.concepts.Entity;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2008,2009 NGIT. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions
* in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by NGIT and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "NGIT" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or NGIT
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE,
* NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* @author EVS Team
* @version 1.0
*
* Modification history
* Initial implementation kim.ong@ngc.com
*
*/
public class DataUtils {
private static Vector<String> sourceListData = null;
LocalNameList noopList_ = Constructors.createLocalNameList("_noop_");
static SortOptionList sortByCode_ = Constructors.createSortOptionList(new String[] {"code"});
int maxReturn = 5000;
Connection con;
Statement stmt;
ResultSet rs;
private List supportedStandardReportList = new ArrayList();
private static List standardReportTemplateList = null;
private static List adminTaskList = null;
private static List userTaskList = null;
private static List propertyTypeList = null;
private static List _ontologies = null;
private static org.LexGrid.LexBIG.LexBIGService.LexBIGService lbSvc = null;
public org.LexGrid.LexBIG.Utility.ConvenienceMethods lbConvMethods = null;
public CodingSchemeRenderingList csrl = null;
private Vector supportedCodingSchemes = null;
private static HashMap codingSchemeMap = null;
private Vector codingSchemes = null;
private static HashMap csnv2codingSchemeNameMap = null;
private static HashMap csnv2VersionMap = null;
private static List directionList = null;
//==================================================================================
// For customized query use
public static int ALL = 0;
public static int PREFERRED_ONLY = 1;
public static int NON_PREFERRED_ONLY = 2;
static int RESOLVE_SOURCE = 1;
static int RESOLVE_TARGET = -1;
static int RESTRICT_SOURCE = -1;
static int RESTRICT_TARGET = 1;
public static final int SEARCH_NAME_CODE = 1;
public static final int SEARCH_DEFINITION = 2;
public static final int SEARCH_PROPERTY_VALUE = 3;
public static final int SEARCH_ROLE_VALUE = 6;
public static final int SEARCH_ASSOCIATION_VALUE = 7;
static final List<String> STOP_WORDS = Arrays.asList(new String[] {
"a", "an", "and", "by", "for", "of", "on", "in", "nos", "the", "to", "with"});
public static String TYPE_ROLE = "type_role";
public static String TYPE_ASSOCIATION = "type_association";
public static String TYPE_SUPERCONCEPT = "type_superconcept";
public static String TYPE_SUBCONCEPT = "type_subconcept";
public static String TYPE_SIBLINGCONCEPT = "type_siblingconcept";
public static String TYPE_BROADERCONCEPT = "type_broaderconcept";
public static String TYPE_NARROWERCONCEPT = "type_narrowerconcept";
public String NCICBContactURL = null;
public String terminologySubsetDownloadURL = null;
public String NCIMBuildInfo = null;
static String[] hierAssocToParentNodes_ = new String[] { "PAR", "isa", "branch_of", "part_of", "tributary_of" };
static String[] hierAssocToChildNodes_ = new String[] { "CHD", "hasSubtype" };
static String[] assocToSiblingNodes_ = new String[] { "SIB" };
static String[] assocToBTNodes_ = new String[] { "RB", "BT" };
static String[] assocToNTNodes_ = new String[] { "RN", "NT" };
static String[] relationshipCategories_ = new String[] { "Parent", "Child", "Broader", "Narrower", "Sibling", "Other"};
//==================================================================================
public DataUtils()
{
}
/*
public static List getOntologyList() {
if(_ontologies == null) setCodingSchemeMap();
return _ontologies;
}
*/
/*
private static void setCodingSchemeMap()
{
//if (_ontologies != null) return;
_ontologies = new ArrayList();
codingSchemeMap = new HashMap();
csnv2codingSchemeNameMap = new HashMap();
csnv2VersionMap = new HashMap();
try {
RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
String representsVersion = css.getRepresentsVersion();
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
vt.setVersion(representsVersion);
CodingScheme scheme = null;
try {
try {
scheme = lbSvc.resolveCodingScheme(formalname, vt);
} catch (Exception ex) {
}
if (scheme != null)
{
codingSchemeMap.put((Object) formalname, (Object) scheme);
String value = formalname + " (version: " + representsVersion + ")";
_ontologies.add(new SelectItem(value, value));
csnv2codingSchemeNameMap.put(value, formalname);
csnv2VersionMap.put(value, representsVersion);
}
} catch (Exception e) {
String urn = css.getCodingSchemeURI();
try {
scheme = lbSvc.resolveCodingScheme(urn, vt);
if (scheme != null)
{
codingSchemeMap.put((Object) formalname, (Object) scheme);
String value = formalname + " (version: " + representsVersion + ")";
_ontologies.add(new SelectItem(value, value));
csnv2codingSchemeNameMap.put(value, formalname);
csnv2VersionMap.put(value, representsVersion);
}
} catch (Exception ex) {
String localname = css.getLocalName();
try {
scheme = lbSvc.resolveCodingScheme(localname, vt);
if (scheme != null)
{
codingSchemeMap.put((Object) formalname, (Object) scheme);
String value = formalname + " (version: " + representsVersion + ")";
_ontologies.add(new SelectItem(value, value));
csnv2codingSchemeNameMap.put(value, formalname);
csnv2VersionMap.put(value, representsVersion);
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
*/
/*
public static Vector<String> getSupportedAssociationNames(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
return getSupportedAssociationNames(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getSupportedAssociationNames(codingSchemeName, version);
}
*/
public static Vector<String> getSupportedAssociationNames(String codingSchemeName, String version)
{
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null)
{
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) {
System.out.println("scheme is NULL");
return null;
}
Vector<String> v = new Vector<String>();
SupportedAssociation[] assos = scheme.getMappings().getSupportedAssociation();
for (int i=0; i<assos.length; i++)
{
SupportedAssociation sa = (SupportedAssociation) assos[i];
v.add(sa.getLocalId());
}
return v;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/*
public static Vector<String> getPropertyNameListData(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null)
{
return null;
}
String version = (String) csnv2VersionMap.get(key);
if(version == null)
{
return null;
}
return getPropertyNameListData(codingSchemeName, version);
}
*/
public static Vector<String> getPropertyNameListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedProperty[] properties = scheme.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty property = properties[i];
propertyNameListData.add(property.getLocalId());
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String getCodingSchemeName(String key)
{
return (String) csnv2codingSchemeNameMap.get(key);
}
public static String getCodingSchemeVersion(String key)
{
return (String) csnv2VersionMap.get(key);
}
public static Vector<String> getRepresentationalFormListData(String key)
{
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getRepresentationalFormListData(codingSchemeName, version);
}
public static Vector<String> getRepresentationalFormListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyNameListData = new Vector<String>();
SupportedRepresentationalForm[] forms = scheme.getMappings().getSupportedRepresentationalForm();
if (forms != null)
{
for (int i=0; i<forms.length; i++)
{
SupportedRepresentationalForm form = forms[i];
propertyNameListData.add(form.getLocalId());
}
}
return propertyNameListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static Vector<String> getPropertyQualifierListData(String key)
{
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getPropertyQualifierListData(codingSchemeName, version);
}
public static Vector<String> getPropertyQualifierListData(String codingSchemeName, String version) {
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
Vector<String> propertyQualifierListData = new Vector<String>();
SupportedPropertyQualifier[] qualifiers = scheme.getMappings().getSupportedPropertyQualifier();
for (int i=0; i<qualifiers.length; i++)
{
SupportedPropertyQualifier qualifier = qualifiers[i];
propertyQualifierListData.add(qualifier.getLocalId());
}
return propertyQualifierListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/*
public static Vector<String> getSourceListData(String key)
{
if (csnv2codingSchemeNameMap == null)
{
setCodingSchemeMap();
return getSourceListData(key);
}
String codingSchemeName = (String) csnv2codingSchemeNameMap.get(key);
if(codingSchemeName == null) return null;
String version = (String) csnv2VersionMap.get(key);
if(version == null) return null;
return getSourceListData(codingSchemeName, version);
}
*/
public static Vector<String> getSourceListData(String codingSchemeName, String version) {
if (sourceListData != null) return sourceListData;
CodingSchemeVersionOrTag vt = new CodingSchemeVersionOrTag();
if (version != null) {
vt.setVersion(version);
}
CodingScheme scheme = null;
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
scheme = lbSvc.resolveCodingScheme(codingSchemeName, vt);
if (scheme == null) return null;
sourceListData = new Vector<String>();
sourceListData.add("ALL");
//Insert your code here
SupportedSource[] sources = scheme.getMappings().getSupportedSource();
for (int i=0; i<sources.length; i++)
{
SupportedSource source = sources[i];
sourceListData.add(source.getLocalId());
}
return sourceListData;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String int2String(Integer int_obj) {
if (int_obj == null)
{
return null;
}
String retstr = Integer.toString(int_obj);
return retstr;
}
//==================================================================================================================================
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
cns = cns.restrictToCodes(crefs);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
int count = matches.getResolvedConceptReferenceCount();
// Analyze the result ...
if (count == 0) return null;
if (count > 0) {
try {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
} catch (Exception ex1) {
System.out.println("Exception entry == null");
return null;
}
}
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
public static CodedNodeSet restrictToSource(CodedNodeSet cns, String source) {
if (cns == null) return cns;
if (source == null || source.compareTo("*") == 0 || source.compareTo("") == 0 || source.compareTo("ALL") == 0) return cns;
LocalNameList contextList = null;
LocalNameList sourceLnL = null;
NameAndValueList qualifierList = null;
Vector<String> w2 = new Vector<String>();
w2.add(source);
sourceLnL = vector2LocalNameList(w2);
LocalNameList propertyLnL = null;
CodedNodeSet.PropertyType[] types = new PropertyType[] {PropertyType.PRESENTATION};
try {
cns = cns.restrictToProperties(propertyLnL, types, sourceLnL, contextList, qualifierList);
} catch (Exception ex) {
System.out.println("restrictToSource throws exceptions.");
return null;
}
return cns;
}
public static Concept getConceptByCode(String codingSchemeName, String vers, String ltag, String code, String source)
{
try {
LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
if (lbSvc == null)
{
System.out.println("lbSvc == null???");
return null;
}
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (vers != null) versionOrTag.setVersion(vers);
ConceptReferenceList crefs =
createConceptReferenceList(
new String[] {code}, codingSchemeName);
CodedNodeSet cns = null;
try {
cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag);
} catch (Exception e1) {
//e1.printStackTrace();
}
cns = cns.restrictToCodes(crefs);
cns = restrictToSource(cns, source);
ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1);
if (matches == null)
{
System.out.println("Concep not found.");
return null;
}
// Analyze the result ...
if (matches.getResolvedConceptReferenceCount() > 0) {
ResolvedConceptReference ref =
(ResolvedConceptReference) matches.enumerateResolvedConceptReference().nextElement();
Concept entry = ref.getReferencedEntry();
return entry;
}
} catch (Exception e) {
//e.printStackTrace();
return null;
}
return null;
}
public static NameAndValueList createNameAndValueList(String[] names, String[] values)
{
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.length; i++)
{
NameAndValue nv = new NameAndValue();
nv.setName(names[i]);
if (values != null)
{
nv.setContent(values[i]);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
public ResolvedConceptReferenceList getNext(ResolvedConceptReferencesIterator iterator)
{
return iterator.getNext();
}
public Vector getParentCodes(String scheme, String version, String code) {
Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version);
if (hierarchicalAssoName_vec == null || hierarchicalAssoName_vec.size() == 0)
{
return null;
}
String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0);
//KLO, 01/23/2009
//Vector<Concept> superconcept_vec = util.getAssociationSources(scheme, version, code, hierarchicalAssoName);
Vector superconcept_vec = getAssociationSourceCodes(scheme, version, code, hierarchicalAssoName);
if (superconcept_vec == null) return null;
//SortUtils.quickSort(superconcept_vec, SortUtils.SORT_BY_CODE);
return superconcept_vec;
}
public Vector getAssociationSourceCodes(String scheme, String version, String code, String assocName)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList =
createNameAndValueList(
new String[] {assocName}, null);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
false, true, 1, 1, new LocalNameList(), null, null, maxReturn);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList targetof = ref.getTargetOf();
Association[] associations = targetof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
//KLO
assoc = processForAnonomousNodes(assoc);
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
v.add(ac.getReferencedEntry().getEntityCode());
}
}
}
SortUtils.quickSort(v);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public static ConceptReferenceList createConceptReferenceList(String[] codes, String codingSchemeName)
{
if (codes == null)
{
return null;
}
ConceptReferenceList list = new ConceptReferenceList();
for (int i = 0; i < codes.length; i++)
{
ConceptReference cr = new ConceptReference();
cr.setCodingSchemeName(codingSchemeName);
cr.setConceptCode(codes[i]);
list.addConceptReference(cr);
}
return list;
}
public Vector getSubconceptCodes(String scheme, String version, String code) { //throws LBException{
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = null;
associations = null;
try {
associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null);
} catch (Exception e) {
System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext ");
return v;
}
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
//ex.printStackTrace();
}
return v;
}
public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationNames();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
public static String getFileName(String pathname) {
File file = new File(pathname);
String filename = file.getName();
return filename;
}
protected static Association processForAnonomousNodes(Association assoc){
//clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
//Conditionals to deal with anonymous nodes and UMLS top nodes "V-X"
//The first three allow UMLS traversal to top node.
//The last two are specific to owl anonymous nodes which can act like false
//top nodes.
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
//do nothing
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected static CodingScheme getCodingScheme(String codingScheme,
CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static Vector<SupportedProperty> getSupportedProperties(CodingScheme cs)
{
if (cs == null) return null;
Vector<SupportedProperty> v = new Vector<SupportedProperty>();
SupportedProperty[] properties = cs.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty sp = (SupportedProperty) properties[i];
v.add(sp);
}
return v;
}
public static Vector<String> getSupportedPropertyNames(CodingScheme cs)
{
Vector w = getSupportedProperties(cs);
if (w == null) return null;
Vector<String> v = new Vector<String>();
for (int i=0; i<w.size(); i++)
{
SupportedProperty sp = (SupportedProperty) w.elementAt(i);
v.add(sp.getLocalId());
}
return v;
}
public static Vector<String> getSupportedPropertyNames(String codingScheme, String version)
{
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
CodingScheme cs = getCodingScheme(codingScheme, versionOrTag);
return getSupportedPropertyNames(cs);
} catch (Exception ex) {
}
return null;
}
public static Vector getPropertyNamesByType(Concept concept, String property_type) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
//v.add(p.getValue().getContent());
v.add(p.getPropertyName());
}
return v;
}
public static Vector getPropertyValues(Concept concept, String property_type, String property_name) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
else
{
System.out.println("WARNING: property_type not found -- " + property_type);
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
if (property_name.compareTo(p.getPropertyName()) == 0)
{
String t = p.getValue().getContent();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
t = t + "|" + src.getContent();
}
v.add(t);
}
}
return v;
}
//=====================================================================================
public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
List list = new ArrayList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i=0; i<relations.length; i++)
{
Relations relation = relations[i];
if (relation.getContainerName().compareToIgnoreCase("roles") == 0)
{
org.LexGrid.relations.Association[] asso_array = relation.getAssociation();
for (int j=0; j<asso_array.length; j++)
{
org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j];
list.add(association.getAssociationName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public static void sortArray(ArrayList list) {
String tmp;
if (list.size() <= 1) return;
for (int i = 0; i < list.size(); i++) {
String s1 = (String) list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String s2 = (String) list.get(j);
if(s1.compareToIgnoreCase(s2 ) > 0 ) {
tmp = s1;
list.set(i, s2);
list.set(j, tmp);
}
}
}
}
public static void sortArray(String[] strArray) {
String tmp;
if (strArray.length <= 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if(strArray[i].compareToIgnoreCase(strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public String[] getSortedKeys(HashMap map)
{
if (map == null) return null;
Set keyset = map.keySet();
String[] names = new String[keyset.size()];
Iterator it = keyset.iterator();
int i = 0;
while (it.hasNext())
{
String s = (String) it.next();
names[i] = s;
i++;
}
sortArray(names);
return names;
}
public String getPreferredName(Concept c) {
Presentation[] presentations = c.getPresentation();
for (int i=0; i<presentations.length; i++)
{
Presentation p = presentations[i];
if (p.getPropertyName().compareTo("Preferred_Name") == 0)
{
return p.getValue().getContent();
}
}
return null;
}
public HashMap getRelationshipHashMap(String scheme, String version, String code)
{
return getRelationshipHashMap(scheme, version, code, null);
}
public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab)
{
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
ArrayList roleList = new ArrayList();
ArrayList associationList = new ArrayList();
ArrayList superconceptList = new ArrayList();
ArrayList siblingList = new ArrayList();
ArrayList subconceptList = new ArrayList();
ArrayList btList = new ArrayList();
ArrayList ntList = new ArrayList();
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd,
// !associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
if (sab != null) {
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, noopList_, null, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
//System.out.println("\t" + assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName))
{
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null) name = ed.getContent();
String pt = name;
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
String s = associationName + "|" + pt + "|" + ac.getConceptCode();
if (!parent_asso_vec.contains(associationName) &&
!child_asso_vec.contains(associationName)) {
if (sibling_asso_vec.contains(associationName)) {
siblingList.add(s);
} else if (bt_vec.contains(associationName)) {
btList.add(s);
} else if (nt_vec.contains(associationName)) {
ntList.add(s);
} else {
associationList.add(s);
}
}
}
}
}
}
}
if (roleList.size() > 0) {
SortUtils.quickSort(roleList);
}
if (associationList.size() > 0) {
//KLO, 052909
associationList = removeRedundantRelationships(associationList, "RO");
SortUtils.quickSort(associationList);
}
if (siblingList.size() > 0) {
SortUtils.quickSort(siblingList);
}
if (btList.size() > 0) {
SortUtils.quickSort(btList);
}
if (ntList.size() > 0) {
SortUtils.quickSort(ntList);
}
map.put(TYPE_ROLE, roleList);
map.put(TYPE_ASSOCIATION, associationList);
map.put(TYPE_SIBLINGCONCEPT, siblingList);
map.put(TYPE_BROADERCONCEPT, btList);
map.put(TYPE_NARROWERCONCEPT, ntList);
Vector superconcept_vec = getSuperconcepts(scheme, version, code);
for (int i=0; i<superconcept_vec.size(); i++)
{
Concept c = (Concept) superconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
superconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(superconceptList);
map.put(TYPE_SUPERCONCEPT, superconceptList);
Vector subconcept_vec = getSubconcepts(scheme, version, code);
for (int i=0; i<subconcept_vec.size(); i++)
{
Concept c = (Concept) subconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
subconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(subconceptList);
map.put(TYPE_SUBCONCEPT, subconceptList);
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
return getAssociationSources(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
return getAssociationTargets(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
//Constructors.createSortOptionList(new String[]{"matchToQuery", "code"});
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry();
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getEntityCode().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static Vector<String> parseData(String line, String tab)
{
Vector data_vec = new Vector();
StringTokenizer st = new StringTokenizer(line, tab);
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (value.compareTo("null") == 0) value = " ";
data_vec.add(value);
}
return data_vec;
}
public static String getHyperlink(String url, String codingScheme, String code)
{
codingScheme = codingScheme.replace(" ", "%20");
String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code;
return link;
}
public List getHierarchyRoots(
String scheme,
String version,
String hierarchyID) throws LBException
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
return getHierarchyRoots(scheme, csvt, hierarchyID);
}
public List getHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException
{
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
}
public List getSourceHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String sab) throws LBException
{
/*
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
*/
ResolvedConceptReferenceList roots = null;
try {
roots = new MetaTreeUtils().getSourceRoots(sab);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
} catch (Exception ex) {
}
return new ArrayList();
}
public List ResolvedConceptReferenceList2List(ResolvedConceptReferenceList rcrl)
{
ArrayList list = new ArrayList();
for (int i=0; i<rcrl.getResolvedConceptReferenceCount(); i++)
{
ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i);
list.add(rcr);
}
return list;
}
public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, sab);
}
public static Vector getSynonyms(String scheme, String version, String tag, String code) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept) {
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept, String sab) {
if (concept == null) return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
for (int i=0; i<properties.length; i++)
{
Presentation p = properties[i];
// name
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
// source-code
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null)
{
for (int j=0; j<qualifiers.length; j++)
{
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0)
{
term_source_code = qualifier_value;
break;
}
}
}
// term type
term_type = p.getRepresentationalForm();
// source
Source[] sources = p.getSource();
if (sources != null && sources.length > 0)
{
Source src = sources[0];
term_source = src.getContent();
}
String t = null;
if (sab == null) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
} else if (term_source != null && sab.compareTo(term_source) == 0) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
}
}
SortUtils.quickSort(v);
return v;
}
public String getNCICBContactURL()
{
if (NCICBContactURL != null)
{
return NCICBContactURL;
}
String default_url = "ncicb@pop.nci.nih.gov";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCICBContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL);
if (NCICBContactURL == null)
{
NCICBContactURL = default_url;
}
} catch (Exception ex) {
}
System.out.println("getNCICBContactURL returns " + NCICBContactURL);
return NCICBContactURL;
}
public String getTerminologySubsetDownloadURL()
{
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
terminologySubsetDownloadURL = properties.getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL);
} catch (Exception ex) {
}
return terminologySubsetDownloadURL;
}
public String getNCIMBuildInfo()
{
if (NCIMBuildInfo != null)
{
return NCIMBuildInfo;
}
String default_info = "N/A";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCIMBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO);
if (NCIMBuildInfo == null)
{
NCIMBuildInfo = default_info;
}
} catch (Exception ex) {
}
System.out.println("getNCIMBuildInfo returns " + NCIMBuildInfo);
return NCIMBuildInfo;
}
public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) {
Vector<String> v = new Vector<String>();
v.add("String");
v.add("Code");
v.add("CUI");
return v;
}
public static Vector getSources(String scheme, String version, String tag, String code) {
Vector sources = getSynonyms(scheme, version, tag, code);
//GLIOBLASTOMA MULTIFORME|DI|DXP|U000721
HashSet hset = new HashSet();
Vector source_vec = new Vector();
for (int i=0; i<sources.size(); i++)
{
String s = (String) sources.elementAt(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String name = (String) ret_vec.elementAt(0);
String type = (String) ret_vec.elementAt(1);
String src = (String) ret_vec.elementAt(2);
String srccode = (String) ret_vec.elementAt(3);
if (!hset.contains(src)) {
hset.add(src);
source_vec.add(src);
}
}
SortUtils.quickSort(source_vec);
return source_vec;
}
public static boolean containSource(Vector sources, String source) {
if (sources == null || sources.size() == 0) return false;
String s = null;
for (int i=0; i<sources.size(); i++) {
s = (String) sources.elementAt(i);
if (s.compareTo(source) == 0) return true;
}
return false;
}
public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
SortUtils.quickSort(v);
return v;
}
protected boolean isValidForSAB(AssociatedConcept ac, String sab) {
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue())
if ("Source".equalsIgnoreCase(qualifier.getContent())
&& sab.equalsIgnoreCase(qualifier.getName()))
return true;
return false;
}
public Vector sortSynonyms(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String key = term_name + delim + term_source + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code;
if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
/*
public Vector sortSynonymDataByRel(Vector synonyms) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String key = null;
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String category = "0";
if (parent_asso_vec.contains(rel)) category = "1";
else if (child_asso_vec.contains(rel)) category = "2";
else if (bt_vec.contains(rel)) category = "3";
else if (nt_vec.contains(rel)) category = "4";
else if (sibling_asso_vec.contains(rel)) category = "5";
else category = "6";
key = category + rel + term_name + term_source_code;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
*/
public HashMap getAssociatedConceptsHashMap(String scheme, String version, String code, String sab)
{
HashMap hmap = new HashMap();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
if (sab != null) {
- stopWatch.start();
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
/*
ResolvedConceptReferenceList resolveAsList(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveCodedEntryDepth,
int resolveAssociationDepth, LocalNameList propertyNames, CodedNodeSet.PropertyType[] propertyTypes,
SortOptionList sortOptions, LocalNameList filterOptions, int maxToReturn) */
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = PropertyType.PRESENTATION;
- stopWatch.start();
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, null, propertyTypes, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
Vector v = new Vector();
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
v.add(ac);
}
}
hmap.put(associationName, v);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hmap;
}
private String findRepresentativeTerm(Concept c, String sab) {
Vector synonyms = getSynonyms(c, sab);
if(synonyms == null || synonyms.size() == 0) return null;
return NCImBrowserProperties.getHighestTermGroupRank(synonyms);
}
// Method for populating By Source tab relationships table
public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector w = new Vector();
HashSet hset = new HashSet();
long ms = System.currentTimeMillis();
String action = "Retrieving distance-one relationships from the server";
Utils.StopWatch stopWatch = new Utils.StopWatch();
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, sab);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
HashSet rel_hset = new HashSet();
long ms_categorization_delay = 0;
long ms_categorization;
long ms_find_highest_rank_atom_delay = 0;
long ms_find_highest_rank_atom;
long ms_remove_RO_delay = 0;
long ms_remove_RO;
long ms_all_delay = 0;
long ms_all;
ms_all = System.currentTimeMillis();
while (it.hasNext())
{
ms_categorization = System.currentTimeMillis();
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization);
Vector v = (Vector) hmap.get(rel);
// For each related concept:
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
if (!hset.contains(c.getEntityCode())) {
hset.add(c.getEntityCode());
// Find the highest ranked atom data
ms_find_highest_rank_atom = System.currentTimeMillis();
String t = findRepresentativeTerm(c, sab);
ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom);
t = t + "|" + c.getEntityCode() + "|" + rel + "|" + category;
w.add(t);
// Temporarily save non-RO other relationships
if(category.compareTo("Other") == 0 && category.compareTo("RO") != 0) {
if (rel_hset.contains(c.getEntityCode())) {
rel_hset.add(c.getEntityCode());
}
}
}
}
}
Vector u = new Vector();
// Remove redundant RO relationships
for (int i=0; i<w.size(); i++) {
String s = (String) w.elementAt(i);
Vector<String> v = parseData(s, "|");
if (v.size() >=5) {
String associationName = v.elementAt(5);
if (associationName.compareTo("RO") != 0) {
u.add(s);
} else {
String associationTargetCode = v.elementAt(4);
if (!rel_hset.contains(associationTargetCode)) {
u.add(s);
}
}
}
}
ms_all_delay = System.currentTimeMillis() - ms_all;
action = "categorizing relationships into six categories";
Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay);
action = "finding highest ranked atoms";
Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay);
ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay;
action = "removing redundant RO relationships";
Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay);
// Initial sort (refer to sortSynonymData method for sorting by a specific column)
long ms_sort_delay = System.currentTimeMillis();
SortUtils.quickSort(u);
action = "initial sorting";
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms_sort_delay));
return u;
}
public static String getRelationshipCode(String id) {
if (id.compareTo("Parent") == 0) return "1";
else if (id.compareTo("Child") == 0) return "2";
else if (id.compareTo("Broader") == 0) return "3";
else if (id.compareTo("Narrower") == 0) return "4";
else if (id.compareTo("Sibling") == 0) return "5";
else return "6";
}
public static boolean containsAllUpperCaseChars(String s) {
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if (ch < 65 || ch > 90) return false;
}
return true;
}
public static Vector sortSynonymData(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String rel_type = (String) synonym_data.elementAt(6);
String rel_type_str = getRelationshipCode(rel_type);
String key = term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("type") == 0) key = term_type +delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("source") == 0) key = term_source +delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel") == 0) {
String rel_key = rel;
if (containsAllUpperCaseChars(rel)) rel_key = "|";
key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel_type_str;
}
if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
//KLO, 052909
private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) {
ArrayList a = new ArrayList();
HashSet target_set = new HashSet();
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
String associationTargetCode = w.elementAt(2);
target_set.add(associationTargetCode);
}
}
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
a.add(s);
} else {
String associationTargetCode = w.elementAt(2);
if (!target_set.contains(associationTargetCode)) {
a.add(s);
}
}
}
return a;
}
public static Vector sortRelationshipData(Vector relationships, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<relationships.size(); n++)
{
String s = (String) relationships.elementAt(n);
Vector ret_vec = DataUtils.parseData(s, "|");
String relationship_name = (String) ret_vec.elementAt(0);
String target_concept_name = (String) ret_vec.elementAt(1);
String target_concept_code = (String) ret_vec.elementAt(2);
String rel_sab = (String) ret_vec.elementAt(3);
String key = target_concept_name + delim
+ relationship_name + delim
+ target_concept_code + delim
+ rel_sab;
if (sortBy.compareTo("source") == 0) {
key = rel_sab + delim
+ target_concept_name + delim
+ relationship_name + delim
+ target_concept_code;
} else if (sortBy.compareTo("rela") == 0) {
key = relationship_name + delim
+ target_concept_name + delim
+ target_concept_code + delim
+ rel_sab;
} else if (sortBy.compareTo("code") == 0) {
key = target_concept_code + delim
+ target_concept_name + delim
+ relationship_name + delim
+ rel_sab;
}
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code, Vector sort_option) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector category_vec = new Vector(Arrays.asList(relationshipCategories_));
HashMap rel_hmap = new HashMap();
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
Vector vec = new Vector();
rel_hmap.put(category, vec);
}
Vector w = new Vector();
HashSet hset = new HashSet();
Utils.StopWatch stopWatch = new Utils.StopWatch();
long ms = System.currentTimeMillis();
String action = "Retrieving all relationships from the server";
// Retrieve all relationships from the server (a HashMap with key: associationName, value: vector<AssociatedConcept>)
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, null);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
// Categorize relationships into six categories and find association source data
stopWatch.start();
ms = System.currentTimeMillis();
action = "Categorizing relationships into six categories; finding source data for each relationship";
while (it.hasNext())
{
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
Vector v = (Vector) hmap.get(rel);
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
String source = "unspecified";
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue()) {
if ("Source".equalsIgnoreCase(qualifier.getContent())) {
source = qualifier.getName();
w = (Vector) rel_hmap.get(category);
if (w == null) {
w = new Vector();
}
String str = rel + "|" + c.getEntityDescription().getContent() + "|" + c.getEntityCode() + "|" + source;
if (!w.contains(str)) {
w.add(str);
rel_hmap.put(category, w);
}
}
}
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
// Remove redundant RO relationships
stopWatch.start();
ms = System.currentTimeMillis();
action = "Removing redundant RO relationships";
HashSet other_hset = new HashSet();
Vector w2 = (Vector) rel_hmap.get("Other");
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
String t = name + "|" + target_code + "|" + src;
if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) {
other_hset.add(t);
}
}
Vector w3 = new Vector();
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
if (rel.compareTo("RO") != 0) {
w3.add(s);
} else { //RO
String t = name + "|" + target_code + "|" + src;
if (!other_hset.contains(t)) {
w3.add(s);
}
}
}
rel_hmap.put("Other", w3);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
stopWatch.start();
ms = System.currentTimeMillis();
action = "Sorting relationships by sort options (columns)";
// Sort relationships by sort options (columns)
if (sort_option == null) {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
SortUtils.quickSort(w);
rel_hmap.put(category, w);
}
} else {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
String sortOption = (String) sort_option.elementAt(k);
//SortUtils.quickSort(w);
w = sortRelationshipData(w, sortOption);
rel_hmap.put(category, w);
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
return rel_hmap;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code) {
return getAssociationTargetHashMap(scheme, version, code, null);
}
}
| false | true | public Vector getSubconceptCodes(String scheme, String version, String code) { //throws LBException{
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = null;
associations = null;
try {
associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null);
} catch (Exception e) {
System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext ");
return v;
}
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
//ex.printStackTrace();
}
return v;
}
public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationNames();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
public static String getFileName(String pathname) {
File file = new File(pathname);
String filename = file.getName();
return filename;
}
protected static Association processForAnonomousNodes(Association assoc){
//clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
//Conditionals to deal with anonymous nodes and UMLS top nodes "V-X"
//The first three allow UMLS traversal to top node.
//The last two are specific to owl anonymous nodes which can act like false
//top nodes.
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
//do nothing
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected static CodingScheme getCodingScheme(String codingScheme,
CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static Vector<SupportedProperty> getSupportedProperties(CodingScheme cs)
{
if (cs == null) return null;
Vector<SupportedProperty> v = new Vector<SupportedProperty>();
SupportedProperty[] properties = cs.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty sp = (SupportedProperty) properties[i];
v.add(sp);
}
return v;
}
public static Vector<String> getSupportedPropertyNames(CodingScheme cs)
{
Vector w = getSupportedProperties(cs);
if (w == null) return null;
Vector<String> v = new Vector<String>();
for (int i=0; i<w.size(); i++)
{
SupportedProperty sp = (SupportedProperty) w.elementAt(i);
v.add(sp.getLocalId());
}
return v;
}
public static Vector<String> getSupportedPropertyNames(String codingScheme, String version)
{
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
CodingScheme cs = getCodingScheme(codingScheme, versionOrTag);
return getSupportedPropertyNames(cs);
} catch (Exception ex) {
}
return null;
}
public static Vector getPropertyNamesByType(Concept concept, String property_type) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
//v.add(p.getValue().getContent());
v.add(p.getPropertyName());
}
return v;
}
public static Vector getPropertyValues(Concept concept, String property_type, String property_name) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
else
{
System.out.println("WARNING: property_type not found -- " + property_type);
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
if (property_name.compareTo(p.getPropertyName()) == 0)
{
String t = p.getValue().getContent();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
t = t + "|" + src.getContent();
}
v.add(t);
}
}
return v;
}
//=====================================================================================
public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
List list = new ArrayList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i=0; i<relations.length; i++)
{
Relations relation = relations[i];
if (relation.getContainerName().compareToIgnoreCase("roles") == 0)
{
org.LexGrid.relations.Association[] asso_array = relation.getAssociation();
for (int j=0; j<asso_array.length; j++)
{
org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j];
list.add(association.getAssociationName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public static void sortArray(ArrayList list) {
String tmp;
if (list.size() <= 1) return;
for (int i = 0; i < list.size(); i++) {
String s1 = (String) list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String s2 = (String) list.get(j);
if(s1.compareToIgnoreCase(s2 ) > 0 ) {
tmp = s1;
list.set(i, s2);
list.set(j, tmp);
}
}
}
}
public static void sortArray(String[] strArray) {
String tmp;
if (strArray.length <= 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if(strArray[i].compareToIgnoreCase(strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public String[] getSortedKeys(HashMap map)
{
if (map == null) return null;
Set keyset = map.keySet();
String[] names = new String[keyset.size()];
Iterator it = keyset.iterator();
int i = 0;
while (it.hasNext())
{
String s = (String) it.next();
names[i] = s;
i++;
}
sortArray(names);
return names;
}
public String getPreferredName(Concept c) {
Presentation[] presentations = c.getPresentation();
for (int i=0; i<presentations.length; i++)
{
Presentation p = presentations[i];
if (p.getPropertyName().compareTo("Preferred_Name") == 0)
{
return p.getValue().getContent();
}
}
return null;
}
public HashMap getRelationshipHashMap(String scheme, String version, String code)
{
return getRelationshipHashMap(scheme, version, code, null);
}
public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab)
{
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
ArrayList roleList = new ArrayList();
ArrayList associationList = new ArrayList();
ArrayList superconceptList = new ArrayList();
ArrayList siblingList = new ArrayList();
ArrayList subconceptList = new ArrayList();
ArrayList btList = new ArrayList();
ArrayList ntList = new ArrayList();
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd,
// !associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
if (sab != null) {
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, noopList_, null, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
//System.out.println("\t" + assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName))
{
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null) name = ed.getContent();
String pt = name;
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
String s = associationName + "|" + pt + "|" + ac.getConceptCode();
if (!parent_asso_vec.contains(associationName) &&
!child_asso_vec.contains(associationName)) {
if (sibling_asso_vec.contains(associationName)) {
siblingList.add(s);
} else if (bt_vec.contains(associationName)) {
btList.add(s);
} else if (nt_vec.contains(associationName)) {
ntList.add(s);
} else {
associationList.add(s);
}
}
}
}
}
}
}
if (roleList.size() > 0) {
SortUtils.quickSort(roleList);
}
if (associationList.size() > 0) {
//KLO, 052909
associationList = removeRedundantRelationships(associationList, "RO");
SortUtils.quickSort(associationList);
}
if (siblingList.size() > 0) {
SortUtils.quickSort(siblingList);
}
if (btList.size() > 0) {
SortUtils.quickSort(btList);
}
if (ntList.size() > 0) {
SortUtils.quickSort(ntList);
}
map.put(TYPE_ROLE, roleList);
map.put(TYPE_ASSOCIATION, associationList);
map.put(TYPE_SIBLINGCONCEPT, siblingList);
map.put(TYPE_BROADERCONCEPT, btList);
map.put(TYPE_NARROWERCONCEPT, ntList);
Vector superconcept_vec = getSuperconcepts(scheme, version, code);
for (int i=0; i<superconcept_vec.size(); i++)
{
Concept c = (Concept) superconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
superconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(superconceptList);
map.put(TYPE_SUPERCONCEPT, superconceptList);
Vector subconcept_vec = getSubconcepts(scheme, version, code);
for (int i=0; i<subconcept_vec.size(); i++)
{
Concept c = (Concept) subconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
subconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(subconceptList);
map.put(TYPE_SUBCONCEPT, subconceptList);
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
return getAssociationSources(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
return getAssociationTargets(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
//Constructors.createSortOptionList(new String[]{"matchToQuery", "code"});
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry();
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getEntityCode().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static Vector<String> parseData(String line, String tab)
{
Vector data_vec = new Vector();
StringTokenizer st = new StringTokenizer(line, tab);
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (value.compareTo("null") == 0) value = " ";
data_vec.add(value);
}
return data_vec;
}
public static String getHyperlink(String url, String codingScheme, String code)
{
codingScheme = codingScheme.replace(" ", "%20");
String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code;
return link;
}
public List getHierarchyRoots(
String scheme,
String version,
String hierarchyID) throws LBException
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
return getHierarchyRoots(scheme, csvt, hierarchyID);
}
public List getHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException
{
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
}
public List getSourceHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String sab) throws LBException
{
/*
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
*/
ResolvedConceptReferenceList roots = null;
try {
roots = new MetaTreeUtils().getSourceRoots(sab);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
} catch (Exception ex) {
}
return new ArrayList();
}
public List ResolvedConceptReferenceList2List(ResolvedConceptReferenceList rcrl)
{
ArrayList list = new ArrayList();
for (int i=0; i<rcrl.getResolvedConceptReferenceCount(); i++)
{
ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i);
list.add(rcr);
}
return list;
}
public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, sab);
}
public static Vector getSynonyms(String scheme, String version, String tag, String code) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept) {
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept, String sab) {
if (concept == null) return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
for (int i=0; i<properties.length; i++)
{
Presentation p = properties[i];
// name
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
// source-code
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null)
{
for (int j=0; j<qualifiers.length; j++)
{
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0)
{
term_source_code = qualifier_value;
break;
}
}
}
// term type
term_type = p.getRepresentationalForm();
// source
Source[] sources = p.getSource();
if (sources != null && sources.length > 0)
{
Source src = sources[0];
term_source = src.getContent();
}
String t = null;
if (sab == null) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
} else if (term_source != null && sab.compareTo(term_source) == 0) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
}
}
SortUtils.quickSort(v);
return v;
}
public String getNCICBContactURL()
{
if (NCICBContactURL != null)
{
return NCICBContactURL;
}
String default_url = "ncicb@pop.nci.nih.gov";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCICBContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL);
if (NCICBContactURL == null)
{
NCICBContactURL = default_url;
}
} catch (Exception ex) {
}
System.out.println("getNCICBContactURL returns " + NCICBContactURL);
return NCICBContactURL;
}
public String getTerminologySubsetDownloadURL()
{
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
terminologySubsetDownloadURL = properties.getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL);
} catch (Exception ex) {
}
return terminologySubsetDownloadURL;
}
public String getNCIMBuildInfo()
{
if (NCIMBuildInfo != null)
{
return NCIMBuildInfo;
}
String default_info = "N/A";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCIMBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO);
if (NCIMBuildInfo == null)
{
NCIMBuildInfo = default_info;
}
} catch (Exception ex) {
}
System.out.println("getNCIMBuildInfo returns " + NCIMBuildInfo);
return NCIMBuildInfo;
}
public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) {
Vector<String> v = new Vector<String>();
v.add("String");
v.add("Code");
v.add("CUI");
return v;
}
public static Vector getSources(String scheme, String version, String tag, String code) {
Vector sources = getSynonyms(scheme, version, tag, code);
//GLIOBLASTOMA MULTIFORME|DI|DXP|U000721
HashSet hset = new HashSet();
Vector source_vec = new Vector();
for (int i=0; i<sources.size(); i++)
{
String s = (String) sources.elementAt(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String name = (String) ret_vec.elementAt(0);
String type = (String) ret_vec.elementAt(1);
String src = (String) ret_vec.elementAt(2);
String srccode = (String) ret_vec.elementAt(3);
if (!hset.contains(src)) {
hset.add(src);
source_vec.add(src);
}
}
SortUtils.quickSort(source_vec);
return source_vec;
}
public static boolean containSource(Vector sources, String source) {
if (sources == null || sources.size() == 0) return false;
String s = null;
for (int i=0; i<sources.size(); i++) {
s = (String) sources.elementAt(i);
if (s.compareTo(source) == 0) return true;
}
return false;
}
public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
SortUtils.quickSort(v);
return v;
}
protected boolean isValidForSAB(AssociatedConcept ac, String sab) {
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue())
if ("Source".equalsIgnoreCase(qualifier.getContent())
&& sab.equalsIgnoreCase(qualifier.getName()))
return true;
return false;
}
public Vector sortSynonyms(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String key = term_name + delim + term_source + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code;
if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
/*
public Vector sortSynonymDataByRel(Vector synonyms) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String key = null;
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String category = "0";
if (parent_asso_vec.contains(rel)) category = "1";
else if (child_asso_vec.contains(rel)) category = "2";
else if (bt_vec.contains(rel)) category = "3";
else if (nt_vec.contains(rel)) category = "4";
else if (sibling_asso_vec.contains(rel)) category = "5";
else category = "6";
key = category + rel + term_name + term_source_code;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
*/
public HashMap getAssociatedConceptsHashMap(String scheme, String version, String code, String sab)
{
HashMap hmap = new HashMap();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
if (sab != null) {
stopWatch.start();
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
/*
ResolvedConceptReferenceList resolveAsList(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveCodedEntryDepth,
int resolveAssociationDepth, LocalNameList propertyNames, CodedNodeSet.PropertyType[] propertyTypes,
SortOptionList sortOptions, LocalNameList filterOptions, int maxToReturn) */
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = PropertyType.PRESENTATION;
stopWatch.start();
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, null, propertyTypes, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
Vector v = new Vector();
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
v.add(ac);
}
}
hmap.put(associationName, v);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hmap;
}
private String findRepresentativeTerm(Concept c, String sab) {
Vector synonyms = getSynonyms(c, sab);
if(synonyms == null || synonyms.size() == 0) return null;
return NCImBrowserProperties.getHighestTermGroupRank(synonyms);
}
// Method for populating By Source tab relationships table
public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector w = new Vector();
HashSet hset = new HashSet();
long ms = System.currentTimeMillis();
String action = "Retrieving distance-one relationships from the server";
Utils.StopWatch stopWatch = new Utils.StopWatch();
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, sab);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
HashSet rel_hset = new HashSet();
long ms_categorization_delay = 0;
long ms_categorization;
long ms_find_highest_rank_atom_delay = 0;
long ms_find_highest_rank_atom;
long ms_remove_RO_delay = 0;
long ms_remove_RO;
long ms_all_delay = 0;
long ms_all;
ms_all = System.currentTimeMillis();
while (it.hasNext())
{
ms_categorization = System.currentTimeMillis();
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization);
Vector v = (Vector) hmap.get(rel);
// For each related concept:
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
if (!hset.contains(c.getEntityCode())) {
hset.add(c.getEntityCode());
// Find the highest ranked atom data
ms_find_highest_rank_atom = System.currentTimeMillis();
String t = findRepresentativeTerm(c, sab);
ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom);
t = t + "|" + c.getEntityCode() + "|" + rel + "|" + category;
w.add(t);
// Temporarily save non-RO other relationships
if(category.compareTo("Other") == 0 && category.compareTo("RO") != 0) {
if (rel_hset.contains(c.getEntityCode())) {
rel_hset.add(c.getEntityCode());
}
}
}
}
}
Vector u = new Vector();
// Remove redundant RO relationships
for (int i=0; i<w.size(); i++) {
String s = (String) w.elementAt(i);
Vector<String> v = parseData(s, "|");
if (v.size() >=5) {
String associationName = v.elementAt(5);
if (associationName.compareTo("RO") != 0) {
u.add(s);
} else {
String associationTargetCode = v.elementAt(4);
if (!rel_hset.contains(associationTargetCode)) {
u.add(s);
}
}
}
}
ms_all_delay = System.currentTimeMillis() - ms_all;
action = "categorizing relationships into six categories";
Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay);
action = "finding highest ranked atoms";
Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay);
ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay;
action = "removing redundant RO relationships";
Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay);
// Initial sort (refer to sortSynonymData method for sorting by a specific column)
long ms_sort_delay = System.currentTimeMillis();
SortUtils.quickSort(u);
action = "initial sorting";
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms_sort_delay));
return u;
}
public static String getRelationshipCode(String id) {
if (id.compareTo("Parent") == 0) return "1";
else if (id.compareTo("Child") == 0) return "2";
else if (id.compareTo("Broader") == 0) return "3";
else if (id.compareTo("Narrower") == 0) return "4";
else if (id.compareTo("Sibling") == 0) return "5";
else return "6";
}
public static boolean containsAllUpperCaseChars(String s) {
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if (ch < 65 || ch > 90) return false;
}
return true;
}
public static Vector sortSynonymData(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String rel_type = (String) synonym_data.elementAt(6);
String rel_type_str = getRelationshipCode(rel_type);
String key = term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("type") == 0) key = term_type +delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("source") == 0) key = term_source +delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel") == 0) {
String rel_key = rel;
if (containsAllUpperCaseChars(rel)) rel_key = "|";
key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel_type_str;
}
if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
//KLO, 052909
private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) {
ArrayList a = new ArrayList();
HashSet target_set = new HashSet();
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
String associationTargetCode = w.elementAt(2);
target_set.add(associationTargetCode);
}
}
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
a.add(s);
} else {
String associationTargetCode = w.elementAt(2);
if (!target_set.contains(associationTargetCode)) {
a.add(s);
}
}
}
return a;
}
public static Vector sortRelationshipData(Vector relationships, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<relationships.size(); n++)
{
String s = (String) relationships.elementAt(n);
Vector ret_vec = DataUtils.parseData(s, "|");
String relationship_name = (String) ret_vec.elementAt(0);
String target_concept_name = (String) ret_vec.elementAt(1);
String target_concept_code = (String) ret_vec.elementAt(2);
String rel_sab = (String) ret_vec.elementAt(3);
String key = target_concept_name + delim
+ relationship_name + delim
+ target_concept_code + delim
+ rel_sab;
if (sortBy.compareTo("source") == 0) {
key = rel_sab + delim
+ target_concept_name + delim
+ relationship_name + delim
+ target_concept_code;
} else if (sortBy.compareTo("rela") == 0) {
key = relationship_name + delim
+ target_concept_name + delim
+ target_concept_code + delim
+ rel_sab;
} else if (sortBy.compareTo("code") == 0) {
key = target_concept_code + delim
+ target_concept_name + delim
+ relationship_name + delim
+ rel_sab;
}
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code, Vector sort_option) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector category_vec = new Vector(Arrays.asList(relationshipCategories_));
HashMap rel_hmap = new HashMap();
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
Vector vec = new Vector();
rel_hmap.put(category, vec);
}
Vector w = new Vector();
HashSet hset = new HashSet();
Utils.StopWatch stopWatch = new Utils.StopWatch();
long ms = System.currentTimeMillis();
String action = "Retrieving all relationships from the server";
// Retrieve all relationships from the server (a HashMap with key: associationName, value: vector<AssociatedConcept>)
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, null);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
// Categorize relationships into six categories and find association source data
stopWatch.start();
ms = System.currentTimeMillis();
action = "Categorizing relationships into six categories; finding source data for each relationship";
while (it.hasNext())
{
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
Vector v = (Vector) hmap.get(rel);
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
String source = "unspecified";
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue()) {
if ("Source".equalsIgnoreCase(qualifier.getContent())) {
source = qualifier.getName();
w = (Vector) rel_hmap.get(category);
if (w == null) {
w = new Vector();
}
String str = rel + "|" + c.getEntityDescription().getContent() + "|" + c.getEntityCode() + "|" + source;
if (!w.contains(str)) {
w.add(str);
rel_hmap.put(category, w);
}
}
}
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
// Remove redundant RO relationships
stopWatch.start();
ms = System.currentTimeMillis();
action = "Removing redundant RO relationships";
HashSet other_hset = new HashSet();
Vector w2 = (Vector) rel_hmap.get("Other");
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
String t = name + "|" + target_code + "|" + src;
if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) {
other_hset.add(t);
}
}
Vector w3 = new Vector();
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
if (rel.compareTo("RO") != 0) {
w3.add(s);
} else { //RO
String t = name + "|" + target_code + "|" + src;
if (!other_hset.contains(t)) {
w3.add(s);
}
}
}
rel_hmap.put("Other", w3);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
stopWatch.start();
ms = System.currentTimeMillis();
action = "Sorting relationships by sort options (columns)";
// Sort relationships by sort options (columns)
if (sort_option == null) {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
SortUtils.quickSort(w);
rel_hmap.put(category, w);
}
} else {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
String sortOption = (String) sort_option.elementAt(k);
//SortUtils.quickSort(w);
w = sortRelationshipData(w, sortOption);
rel_hmap.put(category, w);
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
return rel_hmap;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code) {
return getAssociationTargetHashMap(scheme, version, code, null);
}
}
| public Vector getSubconceptCodes(String scheme, String version, String code) { //throws LBException{
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = null;
associations = null;
try {
associations = lbscm.getHierarchyLevelNext(scheme, csvt, hierarchyID, code, false, null);
} catch (Exception e) {
System.out.println("getSubconceptCodes - Exception lbscm.getHierarchyLevelNext ");
return v;
}
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
//ex.printStackTrace();
}
return v;
}
public Vector getSuperconceptCodes(String scheme, String version, String code) { //throws LBException{
long ms = System.currentTimeMillis();
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
csvt.setVersion(version);
String desc = null;
try {
desc = lbscm.createCodeNodeSet(new String[] {code}, scheme, csvt)
.resolveToList(null, null, null, 1)
.getResolvedConceptReference(0)
.getEntityDescription().getContent();
} catch (Exception e) {
desc = "<not found>";
}
// Iterate through all hierarchies and levels ...
String[] hierarchyIDs = lbscm.getHierarchyIDs(scheme, csvt);
for (int k = 0; k < hierarchyIDs.length; k++) {
String hierarchyID = hierarchyIDs[k];
AssociationList associations = lbscm.getHierarchyLevelPrev(scheme, csvt, hierarchyID, code, false, null);
for (int i = 0; i < associations.getAssociationCount(); i++) {
Association assoc = associations.getAssociation(i);
AssociatedConceptList concepts = assoc.getAssociatedConcepts();
for (int j = 0; j < concepts.getAssociatedConceptCount(); j++) {
AssociatedConcept concept = concepts.getAssociatedConcept(j);
String nextCode = concept.getConceptCode();
v.add(nextCode);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println("Run time (ms): " + (System.currentTimeMillis() - ms));
}
return v;
}
public Vector getHierarchyAssociationId(String scheme, String version) {
Vector association_vec = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
// Will handle secured ontologies later.
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
versionOrTag.setVersion(version);
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag);
Mappings mappings = cs.getMappings();
SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy();
java.lang.String[] ids = hierarchies[0].getAssociationNames();
for (int i=0; i<ids.length; i++)
{
if (!association_vec.contains(ids[i])) {
association_vec.add(ids[i]);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return association_vec;
}
public static String getVocabularyVersionByTag(String codingSchemeName, String ltag)
{
if (codingSchemeName == null) return null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList lcsrl = lbSvc.getSupportedCodingSchemes();
CodingSchemeRendering[] csra = lcsrl.getCodingSchemeRendering();
for (int i=0; i<csra.length; i++)
{
CodingSchemeRendering csr = csra[i];
CodingSchemeSummary css = csr.getCodingSchemeSummary();
if (css.getFormalName().compareTo(codingSchemeName) == 0 || css.getLocalName().compareTo(codingSchemeName) == 0)
{
if (ltag == null) return css.getRepresentsVersion();
RenderingDetail rd = csr.getRenderingDetail();
CodingSchemeTagList cstl = rd.getVersionTags();
java.lang.String[] tags = cstl.getTag();
for (int j=0; j<tags.length; j++)
{
String version_tag = (String) tags[j];
if (version_tag.compareToIgnoreCase(ltag) == 0)
{
return css.getRepresentsVersion();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Version corresponding to tag " + ltag + " is not found " + " in " + codingSchemeName);
return null;
}
public static Vector<String> getVersionListData(String codingSchemeName) {
Vector<String> v = new Vector();
try {
//RemoteServerUtil rsu = new RemoteServerUtil();
//EVSApplicationService lbSvc = rsu.createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeRenderingList csrl = lbSvc.getSupportedCodingSchemes();
if(csrl == null) System.out.println("csrl is NULL");
CodingSchemeRendering[] csrs = csrl.getCodingSchemeRendering();
for (int i=0; i<csrs.length; i++)
{
CodingSchemeRendering csr = csrs[i];
Boolean isActive = csr.getRenderingDetail().getVersionStatus().equals(CodingSchemeVersionStatus.ACTIVE);
if (isActive != null && isActive.equals(Boolean.TRUE))
{
CodingSchemeSummary css = csr.getCodingSchemeSummary();
String formalname = css.getFormalName();
if (formalname.compareTo(codingSchemeName) == 0)
{
String representsVersion = css.getRepresentsVersion();
v.add(representsVersion);
}
}
}
} catch (Exception ex) {
}
return v;
}
public static String getFileName(String pathname) {
File file = new File(pathname);
String filename = file.getName();
return filename;
}
protected static Association processForAnonomousNodes(Association assoc){
//clone Association except associatedConcepts
Association temp = new Association();
temp.setAssociatedData(assoc.getAssociatedData());
temp.setAssociationName(assoc.getAssociationName());
temp.setAssociationReference(assoc.getAssociationReference());
temp.setDirectionalName(assoc.getDirectionalName());
temp.setAssociatedConcepts(new AssociatedConceptList());
for(int i = 0; i < assoc.getAssociatedConcepts().getAssociatedConceptCount(); i++)
{
//Conditionals to deal with anonymous nodes and UMLS top nodes "V-X"
//The first three allow UMLS traversal to top node.
//The last two are specific to owl anonymous nodes which can act like false
//top nodes.
if(
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != null &&
assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry().getIsAnonymous() != false &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@") &&
!assoc.getAssociatedConcepts().getAssociatedConcept(i).getConceptCode().equals("@@")
)
{
//do nothing
}
else{
temp.getAssociatedConcepts().addAssociatedConcept(assoc.getAssociatedConcepts().getAssociatedConcept(i));
}
}
return temp;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static LocalNameList vector2LocalNameList(Vector<String> v)
{
if (v == null) return null;
LocalNameList list = new LocalNameList();
for (int i=0; i<v.size(); i++)
{
String vEntry = (String) v.elementAt(i);
list.addEntry(vEntry);
}
return list;
}
protected static NameAndValueList createNameAndValueList(Vector names, Vector values)
{
if (names == null) return null;
NameAndValueList nvList = new NameAndValueList();
for (int i=0; i<names.size(); i++)
{
String name = (String) names.elementAt(i);
String value = (String) values.elementAt(i);
NameAndValue nv = new NameAndValue();
nv.setName(name);
if (value != null)
{
nv.setContent(value);
}
nvList.addNameAndValue(nv);
}
return nvList;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected static CodingScheme getCodingScheme(String codingScheme,
CodingSchemeVersionOrTag versionOrTag) throws LBException {
CodingScheme cs = null;
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag);
} catch (Exception ex) {
ex.printStackTrace();
}
return cs;
}
public static Vector<SupportedProperty> getSupportedProperties(CodingScheme cs)
{
if (cs == null) return null;
Vector<SupportedProperty> v = new Vector<SupportedProperty>();
SupportedProperty[] properties = cs.getMappings().getSupportedProperty();
for (int i=0; i<properties.length; i++)
{
SupportedProperty sp = (SupportedProperty) properties[i];
v.add(sp);
}
return v;
}
public static Vector<String> getSupportedPropertyNames(CodingScheme cs)
{
Vector w = getSupportedProperties(cs);
if (w == null) return null;
Vector<String> v = new Vector<String>();
for (int i=0; i<w.size(); i++)
{
SupportedProperty sp = (SupportedProperty) w.elementAt(i);
v.add(sp.getLocalId());
}
return v;
}
public static Vector<String> getSupportedPropertyNames(String codingScheme, String version)
{
CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
if (version != null) versionOrTag.setVersion(version);
try {
CodingScheme cs = getCodingScheme(codingScheme, versionOrTag);
return getSupportedPropertyNames(cs);
} catch (Exception ex) {
}
return null;
}
public static Vector getPropertyNamesByType(Concept concept, String property_type) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
//v.add(p.getValue().getContent());
v.add(p.getPropertyName());
}
return v;
}
public static Vector getPropertyValues(Concept concept, String property_type, String property_name) {
Vector v = new Vector();
org.LexGrid.commonTypes.Property[] properties = null;
if (property_type.compareToIgnoreCase("GENERIC")== 0)
{
properties = concept.getProperty();
}
else if (property_type.compareToIgnoreCase("PRESENTATION")== 0)
{
properties = concept.getPresentation();
}
/*
else if (property_type.compareToIgnoreCase("INSTRUCTION")== 0)
{
properties = concept.getInstruction();
}
*/
else if (property_type.compareToIgnoreCase("COMMENT")== 0)
{
properties = concept.getComment();
}
else if (property_type.compareToIgnoreCase("DEFINITION")== 0)
{
properties = concept.getDefinition();
}
else
{
System.out.println("WARNING: property_type not found -- " + property_type);
}
if (properties == null || properties.length == 0) return v;
for (int i=0; i<properties.length; i++) {
Property p = (Property) properties[i];
if (property_name.compareTo(p.getPropertyName()) == 0)
{
String t = p.getValue().getContent();
Source[] sources = p.getSource();
if (sources != null && sources.length > 0) {
Source src = sources[0];
t = t + "|" + src.getContent();
}
v.add(t);
}
}
return v;
}
//=====================================================================================
public List getSupportedRoleNames(LexBIGService lbSvc, String scheme, String version)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
List list = new ArrayList();
try {
CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt);
Relations[] relations = cs.getRelations();
for (int i=0; i<relations.length; i++)
{
Relations relation = relations[i];
if (relation.getContainerName().compareToIgnoreCase("roles") == 0)
{
org.LexGrid.relations.Association[] asso_array = relation.getAssociation();
for (int j=0; j<asso_array.length; j++)
{
org.LexGrid.relations.Association association = (org.LexGrid.relations.Association) asso_array[j];
list.add(association.getAssociationName());
}
}
}
} catch (Exception ex) {
}
return list;
}
public static void sortArray(ArrayList list) {
String tmp;
if (list.size() <= 1) return;
for (int i = 0; i < list.size(); i++) {
String s1 = (String) list.get(i);
for (int j = i + 1; j < list.size(); j++) {
String s2 = (String) list.get(j);
if(s1.compareToIgnoreCase(s2 ) > 0 ) {
tmp = s1;
list.set(i, s2);
list.set(j, tmp);
}
}
}
}
public static void sortArray(String[] strArray) {
String tmp;
if (strArray.length <= 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if(strArray[i].compareToIgnoreCase(strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public String[] getSortedKeys(HashMap map)
{
if (map == null) return null;
Set keyset = map.keySet();
String[] names = new String[keyset.size()];
Iterator it = keyset.iterator();
int i = 0;
while (it.hasNext())
{
String s = (String) it.next();
names[i] = s;
i++;
}
sortArray(names);
return names;
}
public String getPreferredName(Concept c) {
Presentation[] presentations = c.getPresentation();
for (int i=0; i<presentations.length; i++)
{
Presentation p = presentations[i];
if (p.getPropertyName().compareTo("Preferred_Name") == 0)
{
return p.getValue().getContent();
}
}
return null;
}
public HashMap getRelationshipHashMap(String scheme, String version, String code)
{
return getRelationshipHashMap(scheme, version, code, null);
}
public HashMap getRelationshipHashMap(String scheme, String version, String code, String sab)
{
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
ArrayList roleList = new ArrayList();
ArrayList associationList = new ArrayList();
ArrayList superconceptList = new ArrayList();
ArrayList siblingList = new ArrayList();
ArrayList subconceptList = new ArrayList();
ArrayList btList = new ArrayList();
ArrayList ntList = new ArrayList();
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd,
// !associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, false);
if (sab != null) {
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, noopList_, null, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
//System.out.println("\t" + assoc.getAssociationName());
boolean isRole = false;
if (list.contains(associationName))
{
isRole = true;
}
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
EntityDescription ed = ac.getEntityDescription();
String name = "No Description";
if (ed != null) name = ed.getContent();
String pt = name;
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
String s = associationName + "|" + pt + "|" + ac.getConceptCode();
if (!parent_asso_vec.contains(associationName) &&
!child_asso_vec.contains(associationName)) {
if (sibling_asso_vec.contains(associationName)) {
siblingList.add(s);
} else if (bt_vec.contains(associationName)) {
btList.add(s);
} else if (nt_vec.contains(associationName)) {
ntList.add(s);
} else {
associationList.add(s);
}
}
}
}
}
}
}
if (roleList.size() > 0) {
SortUtils.quickSort(roleList);
}
if (associationList.size() > 0) {
//KLO, 052909
associationList = removeRedundantRelationships(associationList, "RO");
SortUtils.quickSort(associationList);
}
if (siblingList.size() > 0) {
SortUtils.quickSort(siblingList);
}
if (btList.size() > 0) {
SortUtils.quickSort(btList);
}
if (ntList.size() > 0) {
SortUtils.quickSort(ntList);
}
map.put(TYPE_ROLE, roleList);
map.put(TYPE_ASSOCIATION, associationList);
map.put(TYPE_SIBLINGCONCEPT, siblingList);
map.put(TYPE_BROADERCONCEPT, btList);
map.put(TYPE_NARROWERCONCEPT, ntList);
Vector superconcept_vec = getSuperconcepts(scheme, version, code);
for (int i=0; i<superconcept_vec.size(); i++)
{
Concept c = (Concept) superconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
superconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(superconceptList);
map.put(TYPE_SUPERCONCEPT, superconceptList);
Vector subconcept_vec = getSubconcepts(scheme, version, code);
for (int i=0; i<subconcept_vec.size(); i++)
{
Concept c = (Concept) subconcept_vec.elementAt(i);
//String pt = getPreferredName(c);
String pt = c.getEntityDescription().getContent();
subconceptList.add(pt + "|" + c.getEntityCode());
}
SortUtils.quickSort(subconceptList);
map.put(TYPE_SUBCONCEPT, subconceptList);
} catch (Exception ex) {
ex.printStackTrace();
}
return map;
}
public Vector getSuperconcepts(String scheme, String version, String code)
{
return getAssociationSources(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationSources(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = false;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public Vector getSubconcepts(String scheme, String version, String code)
{
return getAssociationTargets(scheme, version, code, hierAssocToChildNodes_);
}
public Vector getAssociationTargets(String scheme, String version, String code, String[] assocNames)
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
//EVSApplicationService lbSvc = new RemoteServerUtil().createLexBIGService();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier);
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = false;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
return v;
}
public ResolvedConceptReferencesIterator codedNodeGraph2CodedNodeSetIterator(
CodedNodeGraph cng,
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveAssociationDepth,
int maxToReturn) {
CodedNodeSet cns = null;
try {
cns = cng.toNodeList(graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
if (cns == null)
{
System.out.println("cng.toNodeList returns null???");
return null;
}
SortOptionList sortCriteria = null;
//Constructors.createSortOptionList(new String[]{"matchToQuery", "code"});
LocalNameList propertyNames = null;
CodedNodeSet.PropertyType[] propertyTypes = null;
ResolvedConceptReferencesIterator iterator = null;
try {
iterator = cns.resolve(sortCriteria, propertyNames, propertyTypes);
} catch (Exception e) {
e.printStackTrace();
}
if(iterator == null)
{
System.out.println("cns.resolve returns null???");
}
return iterator;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn)
{
return resolveIterator(iterator, maxToReturn, null);
}
public Vector resolveIterator(ResolvedConceptReferencesIterator iterator, int maxToReturn, String code)
{
Vector v = new Vector();
if (iterator == null)
{
System.out.println("No match.");
return v;
}
try {
int iteration = 0;
while (iterator.hasNext())
{
iteration++;
iterator = iterator.scroll(maxToReturn);
ResolvedConceptReferenceList rcrl = iterator.getNext();
ResolvedConceptReference[] rcra = rcrl.getResolvedConceptReference();
for (int i=0; i<rcra.length; i++)
{
ResolvedConceptReference rcr = rcra[i];
org.LexGrid.concepts.Concept ce = rcr.getReferencedEntry();
if (code == null)
{
v.add(ce);
}
else
{
if (ce.getEntityCode().compareTo(code) != 0) v.add(ce);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
public static Vector<String> parseData(String line, String tab)
{
Vector data_vec = new Vector();
StringTokenizer st = new StringTokenizer(line, tab);
while (st.hasMoreTokens()) {
String value = st.nextToken();
if (value.compareTo("null") == 0) value = " ";
data_vec.add(value);
}
return data_vec;
}
public static String getHyperlink(String url, String codingScheme, String code)
{
codingScheme = codingScheme.replace(" ", "%20");
String link = url + "/ConceptReport.jsp?dictionary=" + codingScheme + "&code=" + code;
return link;
}
public List getHierarchyRoots(
String scheme,
String version,
String hierarchyID) throws LBException
{
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
return getHierarchyRoots(scheme, csvt, hierarchyID);
}
public List getHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String hierarchyID) throws LBException
{
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
}
public List getSourceHierarchyRoots(
String scheme,
CodingSchemeVersionOrTag csvt,
String sab) throws LBException
{
/*
int maxDepth = 1;
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc.getGenericExtension("LexBIGServiceConvenienceMethods");
lbscm.setLexBIGService(lbSvc);
ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID);
*/
ResolvedConceptReferenceList roots = null;
try {
roots = new MetaTreeUtils().getSourceRoots(sab);
List list = ResolvedConceptReferenceList2List(roots);
SortUtils.quickSort(list);
return list;
} catch (Exception ex) {
}
return new ArrayList();
}
public List ResolvedConceptReferenceList2List(ResolvedConceptReferenceList rcrl)
{
ArrayList list = new ArrayList();
for (int i=0; i<rcrl.getResolvedConceptReferenceCount(); i++)
{
ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i);
list.add(rcr);
}
return list;
}
public static Vector getSynonyms(String scheme, String version, String tag, String code, String sab) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, sab);
}
public static Vector getSynonyms(String scheme, String version, String tag, String code) {
Concept concept = getConceptByCode(scheme, version, tag, code);
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept) {
return getSynonyms(concept, null);
}
public static Vector getSynonyms(Concept concept, String sab) {
if (concept == null) return null;
Vector v = new Vector();
Presentation[] properties = concept.getPresentation();
int n = 0;
for (int i=0; i<properties.length; i++)
{
Presentation p = properties[i];
// name
String term_name = p.getValue().getContent();
String term_type = "null";
String term_source = "null";
String term_source_code = "null";
// source-code
PropertyQualifier[] qualifiers = p.getPropertyQualifier();
if (qualifiers != null)
{
for (int j=0; j<qualifiers.length; j++)
{
PropertyQualifier q = qualifiers[j];
String qualifier_name = q.getPropertyQualifierName();
String qualifier_value = q.getValue().getContent();
if (qualifier_name.compareTo("source-code") == 0)
{
term_source_code = qualifier_value;
break;
}
}
}
// term type
term_type = p.getRepresentationalForm();
// source
Source[] sources = p.getSource();
if (sources != null && sources.length > 0)
{
Source src = sources[0];
term_source = src.getContent();
}
String t = null;
if (sab == null) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
} else if (term_source != null && sab.compareTo(term_source) == 0) {
t = term_name + "|" + term_type + "|" + term_source + "|" + term_source_code;
v.add(t);
}
}
SortUtils.quickSort(v);
return v;
}
public String getNCICBContactURL()
{
if (NCICBContactURL != null)
{
return NCICBContactURL;
}
String default_url = "ncicb@pop.nci.nih.gov";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCICBContactURL = properties.getProperty(NCImBrowserProperties.NCICB_CONTACT_URL);
if (NCICBContactURL == null)
{
NCICBContactURL = default_url;
}
} catch (Exception ex) {
}
System.out.println("getNCICBContactURL returns " + NCICBContactURL);
return NCICBContactURL;
}
public String getTerminologySubsetDownloadURL()
{
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
terminologySubsetDownloadURL = properties.getProperty(NCImBrowserProperties.TERMINOLOGY_SUBSET_DOWNLOAD_URL);
} catch (Exception ex) {
}
return terminologySubsetDownloadURL;
}
public String getNCIMBuildInfo()
{
if (NCIMBuildInfo != null)
{
return NCIMBuildInfo;
}
String default_info = "N/A";
NCImBrowserProperties properties = null;
try {
properties = NCImBrowserProperties.getInstance();
NCIMBuildInfo = properties.getProperty(NCImBrowserProperties.NCIM_BUILD_INFO);
if (NCIMBuildInfo == null)
{
NCIMBuildInfo = default_info;
}
} catch (Exception ex) {
}
System.out.println("getNCIMBuildInfo returns " + NCIMBuildInfo);
return NCIMBuildInfo;
}
public static Vector<String> getMatchTypeListData(String codingSchemeName, String version) {
Vector<String> v = new Vector<String>();
v.add("String");
v.add("Code");
v.add("CUI");
return v;
}
public static Vector getSources(String scheme, String version, String tag, String code) {
Vector sources = getSynonyms(scheme, version, tag, code);
//GLIOBLASTOMA MULTIFORME|DI|DXP|U000721
HashSet hset = new HashSet();
Vector source_vec = new Vector();
for (int i=0; i<sources.size(); i++)
{
String s = (String) sources.elementAt(i);
Vector ret_vec = DataUtils.parseData(s, "|");
String name = (String) ret_vec.elementAt(0);
String type = (String) ret_vec.elementAt(1);
String src = (String) ret_vec.elementAt(2);
String srccode = (String) ret_vec.elementAt(3);
if (!hset.contains(src)) {
hset.add(src);
source_vec.add(src);
}
}
SortUtils.quickSort(source_vec);
return source_vec;
}
public static boolean containSource(Vector sources, String source) {
if (sources == null || sources.size() == 0) return false;
String s = null;
for (int i=0; i<sources.size(); i++) {
s = (String) sources.elementAt(i);
if (s.compareTo(source) == 0) return true;
}
return false;
}
public Vector getAssociatedConcepts(String scheme, String version, String code, String sab) {
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
ResolvedConceptReferenceList matches = null;
Vector v = new Vector();
try {
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
//NameAndValueList nameAndValueList = ConvenienceMethods.createNameAndValueList(assocNames);
NameAndValueList nameAndValueList_qualifier = null;
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
ConceptReference graphFocus = ConvenienceMethods.createConceptReference(code, scheme);
boolean resolveForward = true;
boolean resolveBackward = true;
int resolveAssociationDepth = 1;
int maxToReturn = -1;
ResolvedConceptReferencesIterator iterator = codedNodeGraph2CodedNodeSetIterator(
cng,
graphFocus,
resolveForward,
resolveBackward,
resolveAssociationDepth,
maxToReturn);
v = resolveIterator(iterator, maxToReturn, code);
} catch (Exception ex) {
ex.printStackTrace();
}
SortUtils.quickSort(v);
return v;
}
protected boolean isValidForSAB(AssociatedConcept ac, String sab) {
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue())
if ("Source".equalsIgnoreCase(qualifier.getContent())
&& sab.equalsIgnoreCase(qualifier.getName()))
return true;
return false;
}
public Vector sortSynonyms(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String key = term_name + delim + term_source + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("type") == 0) key = term_type + delim + term_name + delim + term_source + delim + term_source_code;
if (sortBy.compareTo("source") == 0) key = term_source + delim + term_name + delim + term_source_code + delim + term_type;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_source + delim + term_type;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
/*
public Vector sortSynonymDataByRel(Vector synonyms) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String key = null;
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String category = "0";
if (parent_asso_vec.contains(rel)) category = "1";
else if (child_asso_vec.contains(rel)) category = "2";
else if (bt_vec.contains(rel)) category = "3";
else if (nt_vec.contains(rel)) category = "4";
else if (sibling_asso_vec.contains(rel)) category = "5";
else category = "6";
key = category + rel + term_name + term_source_code;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
*/
public HashMap getAssociatedConceptsHashMap(String scheme, String version, String code, String sab)
{
HashMap hmap = new HashMap();
LexBIGService lbSvc = RemoteServerUtil.createLexBIGService();
CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag();
if (version != null) csvt.setVersion(version);
// Perform the query ...
ResolvedConceptReferenceList matches = null;
List list = new ArrayList();//getSupportedRoleNames(lbSvc, scheme, version);
HashMap map = new HashMap();
try {
CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null);
if (sab != null) {
cng = cng.restrictToAssociations(null, Constructors.createNameAndValueList(sab, "Source"));
}
/*
ResolvedConceptReferenceList resolveAsList(ConceptReference graphFocus, boolean resolveForward, boolean resolveBackward, int resolveCodedEntryDepth,
int resolveAssociationDepth, LocalNameList propertyNames, CodedNodeSet.PropertyType[] propertyTypes,
SortOptionList sortOptions, LocalNameList filterOptions, int maxToReturn) */
CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
propertyTypes[0] = PropertyType.PRESENTATION;
matches = cng.resolveAsList(
ConvenienceMethods.createConceptReference(code, scheme),
//true, false, 1, 1, new LocalNameList(), null, null, 1024);
true, false, 1, 1, null, propertyTypes, null, null, -1, false);
if (matches.getResolvedConceptReferenceCount() > 0) {
Enumeration<ResolvedConceptReference> refEnum =
matches .enumerateResolvedConceptReference();
while (refEnum.hasMoreElements()) {
ResolvedConceptReference ref = refEnum.nextElement();
AssociationList sourceof = ref.getSourceOf();
Association[] associations = sourceof.getAssociation();
for (int i = 0; i < associations.length; i++) {
Association assoc = associations[i];
String associationName = assoc.getAssociationName();
Vector v = new Vector();
AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
for (int j = 0; j < acl.length; j++) {
AssociatedConcept ac = acl[j];
if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
v.add(ac);
}
}
hmap.put(associationName, v);
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return hmap;
}
private String findRepresentativeTerm(Concept c, String sab) {
Vector synonyms = getSynonyms(c, sab);
if(synonyms == null || synonyms.size() == 0) return null;
return NCImBrowserProperties.getHighestTermGroupRank(synonyms);
}
// Method for populating By Source tab relationships table
public Vector getNeighborhoodSynonyms(String scheme, String version, String code, String sab) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector w = new Vector();
HashSet hset = new HashSet();
long ms = System.currentTimeMillis();
String action = "Retrieving distance-one relationships from the server";
Utils.StopWatch stopWatch = new Utils.StopWatch();
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, sab);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
HashSet rel_hset = new HashSet();
long ms_categorization_delay = 0;
long ms_categorization;
long ms_find_highest_rank_atom_delay = 0;
long ms_find_highest_rank_atom;
long ms_remove_RO_delay = 0;
long ms_remove_RO;
long ms_all_delay = 0;
long ms_all;
ms_all = System.currentTimeMillis();
while (it.hasNext())
{
ms_categorization = System.currentTimeMillis();
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
ms_categorization_delay = ms_categorization_delay + (System.currentTimeMillis() - ms_categorization);
Vector v = (Vector) hmap.get(rel);
// For each related concept:
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
if (!hset.contains(c.getEntityCode())) {
hset.add(c.getEntityCode());
// Find the highest ranked atom data
ms_find_highest_rank_atom = System.currentTimeMillis();
String t = findRepresentativeTerm(c, sab);
ms_find_highest_rank_atom_delay = ms_find_highest_rank_atom_delay + (System.currentTimeMillis() - ms_find_highest_rank_atom);
t = t + "|" + c.getEntityCode() + "|" + rel + "|" + category;
w.add(t);
// Temporarily save non-RO other relationships
if(category.compareTo("Other") == 0 && category.compareTo("RO") != 0) {
if (rel_hset.contains(c.getEntityCode())) {
rel_hset.add(c.getEntityCode());
}
}
}
}
}
Vector u = new Vector();
// Remove redundant RO relationships
for (int i=0; i<w.size(); i++) {
String s = (String) w.elementAt(i);
Vector<String> v = parseData(s, "|");
if (v.size() >=5) {
String associationName = v.elementAt(5);
if (associationName.compareTo("RO") != 0) {
u.add(s);
} else {
String associationTargetCode = v.elementAt(4);
if (!rel_hset.contains(associationTargetCode)) {
u.add(s);
}
}
}
}
ms_all_delay = System.currentTimeMillis() - ms_all;
action = "categorizing relationships into six categories";
Debug.println("Run time (ms) for " + action + " " + ms_categorization_delay);
action = "finding highest ranked atoms";
Debug.println("Run time (ms) for " + action + " " + ms_find_highest_rank_atom_delay);
ms_remove_RO_delay = ms_all_delay - ms_categorization_delay - ms_find_highest_rank_atom_delay;
action = "removing redundant RO relationships";
Debug.println("Run time (ms) for " + action + " " + ms_remove_RO_delay);
// Initial sort (refer to sortSynonymData method for sorting by a specific column)
long ms_sort_delay = System.currentTimeMillis();
SortUtils.quickSort(u);
action = "initial sorting";
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms_sort_delay));
return u;
}
public static String getRelationshipCode(String id) {
if (id.compareTo("Parent") == 0) return "1";
else if (id.compareTo("Child") == 0) return "2";
else if (id.compareTo("Broader") == 0) return "3";
else if (id.compareTo("Narrower") == 0) return "4";
else if (id.compareTo("Sibling") == 0) return "5";
else return "6";
}
public static boolean containsAllUpperCaseChars(String s) {
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if (ch < 65 || ch > 90) return false;
}
return true;
}
public static Vector sortSynonymData(Vector synonyms, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<synonyms.size(); n++)
{
String s = (String) synonyms.elementAt(n);
Vector synonym_data = DataUtils.parseData(s, "|");
String term_name = (String) synonym_data.elementAt(0);
String term_type = (String) synonym_data.elementAt(1);
String term_source = (String) synonym_data.elementAt(2);
String term_source_code = (String) synonym_data.elementAt(3);
String cui = (String) synonym_data.elementAt(4);
String rel = (String) synonym_data.elementAt(5);
String rel_type = (String) synonym_data.elementAt(6);
String rel_type_str = getRelationshipCode(rel_type);
String key = term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("type") == 0) key = term_type +delim + term_name + delim + term_source + delim + term_source_code + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("source") == 0) key = term_source +delim + term_name + delim + term_type + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("code") == 0) key = term_source_code + delim + term_name + delim + term_type + delim + term_source + delim + cui + delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel") == 0) {
String rel_key = rel;
if (containsAllUpperCaseChars(rel)) rel_key = "|";
key = rel + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + cui + delim + rel_type_str;
}
if (sortBy.compareTo("cui") == 0) key = cui + term_name + delim + term_type + delim + term_source + delim + term_source_code +delim + rel + delim + rel_type_str;
if (sortBy.compareTo("rel_type") == 0) key = rel_type_str + delim + rel + delim + term_name + delim + term_type + delim + term_source + delim + term_source_code + delim + cui;
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
//KLO, 052909
private ArrayList removeRedundantRelationships(ArrayList associationList, String rel) {
ArrayList a = new ArrayList();
HashSet target_set = new HashSet();
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
String associationTargetCode = w.elementAt(2);
target_set.add(associationTargetCode);
}
}
for (int i=0; i<associationList.size(); i++) {
String s = (String) associationList.get(i);
Vector<String> w = parseData(s, "|");
String associationName = w.elementAt(0);
if (associationName.compareTo(rel) != 0) {
a.add(s);
} else {
String associationTargetCode = w.elementAt(2);
if (!target_set.contains(associationTargetCode)) {
a.add(s);
}
}
}
return a;
}
public static Vector sortRelationshipData(Vector relationships, String sortBy) {
if (sortBy == null) sortBy = "name";
HashMap hmap = new HashMap();
Vector key_vec = new Vector();
String delim = " ";
for (int n=0; n<relationships.size(); n++)
{
String s = (String) relationships.elementAt(n);
Vector ret_vec = DataUtils.parseData(s, "|");
String relationship_name = (String) ret_vec.elementAt(0);
String target_concept_name = (String) ret_vec.elementAt(1);
String target_concept_code = (String) ret_vec.elementAt(2);
String rel_sab = (String) ret_vec.elementAt(3);
String key = target_concept_name + delim
+ relationship_name + delim
+ target_concept_code + delim
+ rel_sab;
if (sortBy.compareTo("source") == 0) {
key = rel_sab + delim
+ target_concept_name + delim
+ relationship_name + delim
+ target_concept_code;
} else if (sortBy.compareTo("rela") == 0) {
key = relationship_name + delim
+ target_concept_name + delim
+ target_concept_code + delim
+ rel_sab;
} else if (sortBy.compareTo("code") == 0) {
key = target_concept_code + delim
+ target_concept_name + delim
+ relationship_name + delim
+ rel_sab;
}
hmap.put(key, s);
key_vec.add(key);
}
key_vec = SortUtils.quickSort(key_vec);
Vector v = new Vector();
for (int i=0; i<key_vec.size(); i++) {
String s = (String) key_vec.elementAt(i);
v.add((String) hmap.get(s));
}
return v;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code, Vector sort_option) {
Vector parent_asso_vec = new Vector(Arrays.asList(hierAssocToParentNodes_));
Vector child_asso_vec = new Vector(Arrays.asList(hierAssocToChildNodes_));
Vector sibling_asso_vec = new Vector(Arrays.asList(assocToSiblingNodes_));
Vector bt_vec = new Vector(Arrays.asList(assocToBTNodes_));
Vector nt_vec = new Vector(Arrays.asList(assocToNTNodes_));
Vector category_vec = new Vector(Arrays.asList(relationshipCategories_));
HashMap rel_hmap = new HashMap();
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
Vector vec = new Vector();
rel_hmap.put(category, vec);
}
Vector w = new Vector();
HashSet hset = new HashSet();
Utils.StopWatch stopWatch = new Utils.StopWatch();
long ms = System.currentTimeMillis();
String action = "Retrieving all relationships from the server";
// Retrieve all relationships from the server (a HashMap with key: associationName, value: vector<AssociatedConcept>)
HashMap hmap = getAssociatedConceptsHashMap(scheme, version, code, null);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
Set keyset = hmap.keySet();
Iterator it = keyset.iterator();
// Categorize relationships into six categories and find association source data
stopWatch.start();
ms = System.currentTimeMillis();
action = "Categorizing relationships into six categories; finding source data for each relationship";
while (it.hasNext())
{
String rel = (String) it.next();
String category = "Other";
if (parent_asso_vec.contains(rel)) category = "Parent";
else if (child_asso_vec.contains(rel)) category = "Child";
else if (bt_vec.contains(rel)) category = "Broader";
else if (nt_vec.contains(rel)) category = "Narrower";
else if (sibling_asso_vec.contains(rel)) category = "Sibling";
Vector v = (Vector) hmap.get(rel);
for (int i=0; i<v.size(); i++) {
AssociatedConcept ac = (AssociatedConcept) v.elementAt(i);
EntityDescription ed = ac.getEntityDescription();
Concept c = ac.getReferencedEntry();
String source = "unspecified";
for (NameAndValue qualifier : ac.getAssociationQualifiers().getNameAndValue()) {
if ("Source".equalsIgnoreCase(qualifier.getContent())) {
source = qualifier.getName();
w = (Vector) rel_hmap.get(category);
if (w == null) {
w = new Vector();
}
String str = rel + "|" + c.getEntityDescription().getContent() + "|" + c.getEntityCode() + "|" + source;
if (!w.contains(str)) {
w.add(str);
rel_hmap.put(category, w);
}
}
}
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
// Remove redundant RO relationships
stopWatch.start();
ms = System.currentTimeMillis();
action = "Removing redundant RO relationships";
HashSet other_hset = new HashSet();
Vector w2 = (Vector) rel_hmap.get("Other");
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
String t = name + "|" + target_code + "|" + src;
if (rel.compareTo("RO") != 0 && !other_hset.contains(t)) {
other_hset.add(t);
}
}
Vector w3 = new Vector();
for (int k=0; k<w2.size(); k++) {
String s = (String) w2.elementAt(k);
Vector ret_vec = DataUtils.parseData(s, "|");
String rel = (String) ret_vec.elementAt(0);
String name = (String) ret_vec.elementAt(1);
String target_code = (String) ret_vec.elementAt(2);
String src = (String) ret_vec.elementAt(3);
if (rel.compareTo("RO") != 0) {
w3.add(s);
} else { //RO
String t = name + "|" + target_code + "|" + src;
if (!other_hset.contains(t)) {
w3.add(s);
}
}
}
rel_hmap.put("Other", w3);
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
stopWatch.start();
ms = System.currentTimeMillis();
action = "Sorting relationships by sort options (columns)";
// Sort relationships by sort options (columns)
if (sort_option == null) {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
SortUtils.quickSort(w);
rel_hmap.put(category, w);
}
} else {
for (int k=0; k<category_vec.size(); k++) {
String category = (String) category_vec.elementAt(k);
w = (Vector) rel_hmap.get(category);
String sortOption = (String) sort_option.elementAt(k);
//SortUtils.quickSort(w);
w = sortRelationshipData(w, sortOption);
rel_hmap.put(category, w);
}
}
Debug.println("Run time (ms) for " + action + " " + (System.currentTimeMillis() - ms));
DBG.debugDetails("* " + action + ": " + stopWatch.getResult() + " [getAssociationTargetHashMap]");
DBG.debugTabbedValue(action, stopWatch.formatInSec());
return rel_hmap;
}
public HashMap getAssociationTargetHashMap(String scheme, String version, String code) {
return getAssociationTargetHashMap(scheme, version, code, null);
}
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/Util.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/Util.java
index 4f3e6349..3e3d6f15 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/Util.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/Util.java
@@ -1,42 +1,42 @@
package pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified;
import java.util.TreeSet;
import module.workflow.domain.ActivityLog;
import module.workflow.domain.WorkflowLog;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.refund.RefundProcess;
public class Util {
public static boolean isAppiableForYear(final int year, final SimplifiedProcedureProcess simplifiedProcedureProcess) {
final TreeSet<ActivityLog> logs = new TreeSet<ActivityLog>(WorkflowLog.COMPARATOR_BY_WHEN_REVERSED);
- for (WorkflowLog log : simplifiedProcedureProcess.getExecutionLogsSet()) {
+ for (WorkflowLog log : simplifiedProcedureProcess.getExecutionLogs(ActivityLog.class)) {
logs.add((ActivityLog) log);
}
for (final ActivityLog genericLog : logs) {
if (genericLog.getOperation().equals("RevertSkipPurchaseOrderDocument")) {
return false;
}
if (genericLog.getWhenOperationWasRan().getYear() == year && matchesAppiableForYearActivity(year, genericLog)) {
return true;
}
}
return false;
}
public static boolean isAppiableForYear(final int year, final RefundProcess refundProcess) {
// TODO : implement this properly... until then always count
// everything... which will work because there is still only one year...
// :)
// Currently I'm not sure whether this should be based on the invoice
// date, or some authorization date.
return year == 2009;
}
private static boolean matchesAppiableForYearActivity(final int year, final ActivityLog genericLog) {
return genericLog.getOperation().equals("SendAcquisitionRequestToSupplier")
|| genericLog.getOperation().equals("SendPurchaseOrderToSupplier")
|| genericLog.getOperation().equals("SkipPurchaseOrderDocument");
}
}
| true | true | public static boolean isAppiableForYear(final int year, final SimplifiedProcedureProcess simplifiedProcedureProcess) {
final TreeSet<ActivityLog> logs = new TreeSet<ActivityLog>(WorkflowLog.COMPARATOR_BY_WHEN_REVERSED);
for (WorkflowLog log : simplifiedProcedureProcess.getExecutionLogsSet()) {
logs.add((ActivityLog) log);
}
for (final ActivityLog genericLog : logs) {
if (genericLog.getOperation().equals("RevertSkipPurchaseOrderDocument")) {
return false;
}
if (genericLog.getWhenOperationWasRan().getYear() == year && matchesAppiableForYearActivity(year, genericLog)) {
return true;
}
}
return false;
}
| public static boolean isAppiableForYear(final int year, final SimplifiedProcedureProcess simplifiedProcedureProcess) {
final TreeSet<ActivityLog> logs = new TreeSet<ActivityLog>(WorkflowLog.COMPARATOR_BY_WHEN_REVERSED);
for (WorkflowLog log : simplifiedProcedureProcess.getExecutionLogs(ActivityLog.class)) {
logs.add((ActivityLog) log);
}
for (final ActivityLog genericLog : logs) {
if (genericLog.getOperation().equals("RevertSkipPurchaseOrderDocument")) {
return false;
}
if (genericLog.getWhenOperationWasRan().getYear() == year && matchesAppiableForYearActivity(year, genericLog)) {
return true;
}
}
return false;
}
|
diff --git a/src/eu/hansolo/enzo/qlocktwo/QlockGerman.java b/src/eu/hansolo/enzo/qlocktwo/QlockGerman.java
index 8e686a1..2af0577 100644
--- a/src/eu/hansolo/enzo/qlocktwo/QlockGerman.java
+++ b/src/eu/hansolo/enzo/qlocktwo/QlockGerman.java
@@ -1,248 +1,248 @@
package eu.hansolo.enzo.qlocktwo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by
* User: hansolo
* Date: 27.02.13
* Time: 15:44
*/
public class QlockGerman implements Qlock {
private static final QlockTwo.Language LANGUAGE = QlockTwo.Language.GERMAN;
private static final String[][] MATRIX = {
{"E", "S", "K", "I", "S", "T", "A", "F", "Ü", "N", "F"},
{"Z", "E", "H", "N", "Z", "W", "A", "N", "Z", "I", "G"},
{"D", "R", "E", "I", "V", "I", "E", "R", "T", "E", "L"},
{"V", "O", "R", "F", "U", "N", "K", "N", "A", "C", "H"},
{"H", "A", "L", "B", "A", "E", "L", "F", "Ü", "N", "F"},
{"E", "I", "N", "S", "X", "Ä", "M", "Z", "W", "E", "I"},
{"D", "R", "E", "I", "A", "U", "J", "V", "I", "E", "R"},
{"S", "E", "C", "H", "S", "N", "L", "A", "C", "H", "T"},
{"S", "I", "E", "B", "E", "N", "Z", "W", "Ö", "L", "F"},
{"Z", "E", "H", "N", "E", "U", "N", "K", "U", "H", "R"}
};
private boolean p1;
private boolean p2;
private boolean p3;
private boolean p4;
private final ConcurrentHashMap<Integer, String> LOOKUP;
private List<QlockWord> timeList;
public QlockGerman() {
LOOKUP = new ConcurrentHashMap<>();
LOOKUP.putAll(QlockTwo.Language.GERMAN.getLookup());
timeList = new ArrayList<>(10);
}
@Override public String[][] getMatrix() {
return MATRIX;
}
@Override public List<QlockWord> getTime(int minute, int hour) {
if (hour > 12) {
hour -= 12;
}
if (hour <= 0) {
hour += 12;
}
if (minute > 60) {
minute -= 60;
hour++;
}
if (minute < 0) {
minute += 60;
hour--;
}
if (minute %5 == 0) {
p1 = false;
p2 = false;
p3 = false;
p4 = false;
}
if (minute %10 == 1 || minute %10 == 6) {
p1 = true;
}
if (minute %10 == 2 || minute %10 == 7) {
p1 = true;
p2 = true;
}
if (minute %10 == 3 || minute %10 == 8) {
p1 = true;
p2 = true;
p3 = true;
}
if (minute %10 == 4 || minute %10 == 9) {
p1 = true;
p2 = true;
p3 = true;
p4 = true;
}
minute -= minute%5;
timeList.clear();
timeList.add(QlockLanguage.ES);
timeList.add(QlockLanguage.IST);
switch (minute) {
case 0:
- timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
+ timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour)));
timeList.add(QlockLanguage.UHR);
break;
case 5:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 10:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 15:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 20:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 25:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 30:
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 35:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 40:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 45:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 50:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 55:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
}
return timeList;
}
@Override public boolean isP1() {
return p1;
}
@Override public boolean isP2() {
return p2;
}
@Override public boolean isP3() {
return p3;
}
@Override public boolean isP4() {
return p4;
}
@Override public QlockTwo.Language getLanguage() {
return LANGUAGE;
}
private void addHour(List<QlockWord> timeList, final int HOUR) {
if (HOUR == 12) {
timeList.add(QlockLanguage.EINS);
} else if (HOUR == 5) {
timeList.add(QlockLanguage.FÜNF2);
} else {
if (HOUR + 1 == 5) {
timeList.add(QlockLanguage.FÜNF2);
} else if (HOUR + 1 == 10) {
timeList.add(QlockLanguage.ZEHN1);
} else {
timeList.add(QlockLanguage.valueOf(LOOKUP.get(HOUR + 1)));
}
}
}
private enum QlockLanguage implements QlockWord {
EINS(5, 0, 3),
ZWEI(5, 7, 10),
DREI(2, 0, 3),
VIER(6, 7, 10),
FÜNF(4, 7, 0),
FÜNF1(0, 7, 10),
FÜNF2(4, 7, 10),
SECHS(7, 0, 4),
SIEBEN(8, 0, 5),
ACHT(7, 7, 10),
NEUN(9, 3, 6),
ZEHN(1, 0, 3),
ZEHN1(9, 0, 3),
ELF(4, 5, 7),
ZWÖLF(8, 6, 10),
ES(0, 0, 1),
IST(0, 3, 5),
VOR(3, 0, 2),
NACH(3, 7, 10),
VIERTEL(2, 4, 10),
DREIVIERTEL(2, 0, 10),
HALB(4, 0, 3),
ZWANZIG(1, 4, 10),
UHR(9, 8, 10);
private final int ROW;
private final int START;
private final int STOP;
private QlockLanguage(final int ROW, final int START, final int STOP) {
this.ROW = ROW;
this.START = START;
this.STOP = STOP;
}
@Override public int getRow() {
return ROW;
}
@Override public int getStart() {
return START;
}
@Override public int getStop() {
return STOP;
}
}
}
| true | true | @Override public List<QlockWord> getTime(int minute, int hour) {
if (hour > 12) {
hour -= 12;
}
if (hour <= 0) {
hour += 12;
}
if (minute > 60) {
minute -= 60;
hour++;
}
if (minute < 0) {
minute += 60;
hour--;
}
if (minute %5 == 0) {
p1 = false;
p2 = false;
p3 = false;
p4 = false;
}
if (minute %10 == 1 || minute %10 == 6) {
p1 = true;
}
if (minute %10 == 2 || minute %10 == 7) {
p1 = true;
p2 = true;
}
if (minute %10 == 3 || minute %10 == 8) {
p1 = true;
p2 = true;
p3 = true;
}
if (minute %10 == 4 || minute %10 == 9) {
p1 = true;
p2 = true;
p3 = true;
p4 = true;
}
minute -= minute%5;
timeList.clear();
timeList.add(QlockLanguage.ES);
timeList.add(QlockLanguage.IST);
switch (minute) {
case 0:
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
timeList.add(QlockLanguage.UHR);
break;
case 5:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 10:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 15:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 20:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 25:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 30:
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 35:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 40:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 45:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 50:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 55:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
}
return timeList;
}
| @Override public List<QlockWord> getTime(int minute, int hour) {
if (hour > 12) {
hour -= 12;
}
if (hour <= 0) {
hour += 12;
}
if (minute > 60) {
minute -= 60;
hour++;
}
if (minute < 0) {
minute += 60;
hour--;
}
if (minute %5 == 0) {
p1 = false;
p2 = false;
p3 = false;
p4 = false;
}
if (minute %10 == 1 || minute %10 == 6) {
p1 = true;
}
if (minute %10 == 2 || minute %10 == 7) {
p1 = true;
p2 = true;
}
if (minute %10 == 3 || minute %10 == 8) {
p1 = true;
p2 = true;
p3 = true;
}
if (minute %10 == 4 || minute %10 == 9) {
p1 = true;
p2 = true;
p3 = true;
p4 = true;
}
minute -= minute%5;
timeList.clear();
timeList.add(QlockLanguage.ES);
timeList.add(QlockLanguage.IST);
switch (minute) {
case 0:
timeList.add(hour == 10 ? QlockLanguage.ZEHN1 : QlockLanguage.valueOf(LOOKUP.get(hour)));
timeList.add(QlockLanguage.UHR);
break;
case 5:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 10:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 15:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 20:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.valueOf(LOOKUP.get(hour)));
break;
case 25:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 30:
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 35:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.NACH);
timeList.add(QlockLanguage.HALB);
addHour(timeList, hour);
break;
case 40:
timeList.add(QlockLanguage.ZWANZIG);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 45:
timeList.add(QlockLanguage.VIERTEL);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 50:
timeList.add(QlockLanguage.ZEHN);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
case 55:
timeList.add(QlockLanguage.FÜNF1);
timeList.add(QlockLanguage.VOR);
addHour(timeList, hour);
break;
}
return timeList;
}
|
diff --git a/src/com/android/launcher2/LauncherModel.java b/src/com/android/launcher2/LauncherModel.java
index 7b53cd70..d76e0260 100644
--- a/src/com/android/launcher2/LauncherModel.java
+++ b/src/com/android/launcher2/LauncherModel.java
@@ -1,1186 +1,1187 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.os.Process;
import android.os.SystemClock;
import java.lang.ref.WeakReference;
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Maintains in-memory state of the Launcher. It is expected that there should be only one
* LauncherModel object held in a static. Also provide APIs for updating the database state
* for the Launcher.
*/
public class LauncherModel extends BroadcastReceiver {
static final boolean DEBUG_LOADERS = true;
static final String TAG = "Launcher.Model";
private final LauncherApplication mApp;
private final Object mLock = new Object();
private DeferredHandler mHandler = new DeferredHandler();
private Loader mLoader = new Loader();
private boolean mBeforeFirstLoad = true;
private WeakReference<Callbacks> mCallbacks;
private AllAppsList mAllAppsList = new AllAppsList();
public interface Callbacks {
public int getCurrentWorkspaceScreen();
public void startBinding();
public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end);
public void bindFolders(HashMap<Long,FolderInfo> folders);
public void finishBindingItems();
public void bindAppWidget(LauncherAppWidgetInfo info);
public void bindAllApplications(ArrayList<ApplicationInfo> apps);
public void bindPackageAdded(ArrayList<ApplicationInfo> apps);
public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps);
public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps);
}
LauncherModel(LauncherApplication app) {
mApp = app;
}
/**
* Adds an item to the DB if it was not created previously, or move it to a new
* <container, screen, cellX, cellY>
*/
static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY) {
if (item.container == ItemInfo.NO_ID) {
// From all apps
addItemToDatabase(context, item, container, screen, cellX, cellY, false);
} else {
// From somewhere else
moveItemInDatabase(context, item, container, screen, cellX, cellY);
}
}
/**
* Move an item in the DB to a new <container, screen, cellX, cellY>
*/
static void moveItemInDatabase(Context context, ItemInfo item, long container, int screen,
int cellX, int cellY) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
values.put(LauncherSettings.Favorites.CONTAINER, item.container);
values.put(LauncherSettings.Favorites.CELLX, item.cellX);
values.put(LauncherSettings.Favorites.CELLY, item.cellY);
values.put(LauncherSettings.Favorites.SCREEN, item.screen);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Returns true if the shortcuts already exists in the database.
* we identify a shortcut by its title and intent.
*/
static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
+ mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| true | true | static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
| static boolean shortcutExists(Context context, String title, Intent intent) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { "title", "intent" }, "title=? and intent=?",
new String[] { title, intent.toUri(0) }, null);
boolean result = false;
try {
result = c.moveToFirst();
} finally {
c.close();
}
return result;
}
/**
* Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList.
*/
FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) {
final ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null,
"_id=? and (itemType=? or itemType=?)",
new String[] { String.valueOf(id),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER),
String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER) }, null);
try {
if (c.moveToFirst()) {
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER);
final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY);
FolderInfo folderInfo = null;
switch (c.getInt(itemTypeIndex)) {
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
folderInfo = findOrMakeUserFolder(folderList, id);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
folderInfo = findOrMakeLiveFolder(folderList, id);
break;
}
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
folderInfo.container = c.getInt(containerIndex);
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
return folderInfo;
}
} finally {
c.close();
}
return null;
}
/**
* Add an item to the database in a specified container. Sets the container, screen, cellX and
* cellY fields of the item. Also assigns an ID to the item.
*/
static void addItemToDatabase(Context context, ItemInfo item, long container,
int screen, int cellX, int cellY, boolean notify) {
item.container = container;
item.screen = screen;
item.cellX = cellX;
item.cellY = cellY;
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
Uri result = cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI :
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values);
if (result != null) {
item.id = Integer.parseInt(result.getPathSegments().get(1));
}
}
/**
* Update an item to the database in a specified container.
*/
static void updateItemInDatabase(Context context, ItemInfo item) {
final ContentValues values = new ContentValues();
final ContentResolver cr = context.getContentResolver();
item.onAddToDatabase(values);
cr.update(LauncherSettings.Favorites.getContentUri(item.id, false), values, null, null);
}
/**
* Removes the specified item from the database
* @param context
* @param item
*/
static void deleteItemFromDatabase(Context context, ItemInfo item) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(item.id, false), null, null);
}
/**
* Remove the contents of the specified folder from the database
*/
static void deleteUserFolderContentsFromDatabase(Context context, UserFolderInfo info) {
final ContentResolver cr = context.getContentResolver();
cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null);
cr.delete(LauncherSettings.Favorites.CONTENT_URI,
LauncherSettings.Favorites.CONTAINER + "=" + info.id, null);
}
/**
* Set this as the current Launcher activity object for the loader.
*/
public void initialize(Callbacks callbacks) {
synchronized (mLock) {
mCallbacks = new WeakReference<Callbacks>(callbacks);
}
}
public void startLoader(Context context, boolean isLaunching) {
mLoader.startLoader(context, isLaunching);
}
public void stopLoader() {
mLoader.stopLoader();
}
/**
* We pick up most of the changes to all apps.
*/
public void setAllAppsDirty() {
mLoader.setAllAppsDirty();
}
public void setWorkspaceDirty() {
mLoader.setWorkspaceDirty();
}
/**
* Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and
* ACTION_PACKAGE_CHANGED.
*/
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive intent=" + intent);
// Use the app as the context.
context = mApp;
final String packageName = intent.getData().getSchemeSpecificPart();
ArrayList<ApplicationInfo> added = null;
ArrayList<ApplicationInfo> removed = null;
ArrayList<ApplicationInfo> modified = null;
boolean update = false;
boolean remove = false;
synchronized (mLock) {
if (mBeforeFirstLoad) {
// If we haven't even loaded yet, don't bother, since we'll just pick
// up the changes.
return;
}
final String action = intent.getAction();
final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
if (packageName == null || packageName.length() == 0) {
// they sent us a bad intent
return;
}
if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
mAllAppsList.updatePackage(context, packageName);
update = true;
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
if (!replacing) {
mAllAppsList.removePackage(packageName);
remove = true;
}
// else, we are replacing the package, so a PACKAGE_ADDED will be sent
// later, we will update the package at this time
} else {
if (!replacing) {
mAllAppsList.addPackage(context, packageName);
} else {
mAllAppsList.updatePackage(context, packageName);
update = true;
}
}
if (mAllAppsList.added.size() > 0) {
added = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
}
if (mAllAppsList.removed.size() > 0) {
removed = mAllAppsList.removed;
mAllAppsList.removed = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info: removed) {
AppInfoCache.remove(info.intent.getComponent());
}
}
if (mAllAppsList.modified.size() > 0) {
modified = mAllAppsList.modified;
mAllAppsList.modified = new ArrayList<ApplicationInfo>();
}
final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null;
if (callbacks == null) {
Log.d(TAG, "nobody to tell about the new app");
return;
}
if (added != null) {
final ArrayList<ApplicationInfo> addedFinal = added;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageAdded(addedFinal);
}
});
}
if (update || modified != null) {
final ArrayList<ApplicationInfo> modifiedFinal = modified;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageUpdated(packageName, modifiedFinal);
}
});
}
if (remove || removed != null) {
final ArrayList<ApplicationInfo> removedFinal = removed;
mHandler.post(new Runnable() {
public void run() {
callbacks.bindPackageRemoved(packageName, removedFinal);
}
});
}
}
}
public class Loader {
private static final int ITEMS_CHUNK = 6;
private LoaderThread mLoaderThread;
private int mLastWorkspaceSeq = 0;
private int mWorkspaceSeq = 1;
private int mLastAllAppsSeq = 0;
private int mAllAppsSeq = 1;
final ArrayList<ItemInfo> mItems = new ArrayList<ItemInfo>();
final ArrayList<LauncherAppWidgetInfo> mAppWidgets = new ArrayList<LauncherAppWidgetInfo>();
final HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
/**
* Call this from the ui thread so the handler is initialized on the correct thread.
*/
public Loader() {
}
public void startLoader(Context context, boolean isLaunching) {
synchronized (mLock) {
Log.d(TAG, "startLoader isLaunching=" + isLaunching);
// Don't bother to start the thread if we know it's not going to do anything
if (mCallbacks.get() != null) {
LoaderThread oldThread = mLoaderThread;
if (oldThread != null) {
if (oldThread.isLaunching()) {
// don't downgrade isLaunching if we're already running
isLaunching = true;
}
oldThread.stopLocked();
}
mLoaderThread = new LoaderThread(context, oldThread, isLaunching);
mLoaderThread.start();
}
}
}
public void stopLoader() {
synchronized (mLock) {
if (mLoaderThread != null) {
mLoaderThread.stopLocked();
}
}
}
public void setWorkspaceDirty() {
synchronized (mLock) {
mWorkspaceSeq++;
}
}
public void setAllAppsDirty() {
synchronized (mLock) {
mAllAppsSeq++;
}
}
/**
* Runnable for the thread that loads the contents of the launcher:
* - workspace icons
* - widgets
* - all apps icons
*/
private class LoaderThread extends Thread {
private Context mContext;
private Thread mWaitThread;
private boolean mIsLaunching;
private boolean mStopped;
private boolean mWorkspaceDoneBinding;
LoaderThread(Context context, Thread waitThread, boolean isLaunching) {
mContext = context;
mWaitThread = waitThread;
mIsLaunching = isLaunching;
}
boolean isLaunching() {
return mIsLaunching;
}
/**
* If another LoaderThread was supplied, we need to wait for that to finish before
* we start our processing. This keeps the ordering of the setting and clearing
* of the dirty flags correct by making sure we don't start processing stuff until
* they've had a chance to re-set them. We do this waiting the worker thread, not
* the ui thread to avoid ANRs.
*/
private void waitForOtherThread() {
if (mWaitThread != null) {
boolean done = false;
while (!done) {
try {
mWaitThread.join();
done = true;
} catch (InterruptedException ex) {
// Ignore
}
}
mWaitThread = null;
}
}
public void run() {
waitForOtherThread();
// Elevate priority when Home launches for the first time to avoid
// starving at boot time. Staring at a blank home is not cool.
synchronized (mLock) {
android.os.Process.setThreadPriority(mIsLaunching
? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND);
}
// Load the workspace only if it's dirty.
int workspaceSeq;
boolean workspaceDirty;
synchronized (mLock) {
workspaceSeq = mWorkspaceSeq;
workspaceDirty = mWorkspaceSeq != mLastWorkspaceSeq;
}
if (workspaceDirty) {
loadWorkspace();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mWorkspaceSeq.
if (mStopped) {
return;
}
if (workspaceSeq == mWorkspaceSeq) {
mLastWorkspaceSeq = mWorkspaceSeq;
}
}
// Bind the workspace
bindWorkspace();
// Wait until the either we're stopped or the other threads are done.
// This way we don't start loading all apps until the workspace has settled
// down.
synchronized (LoaderThread.this) {
mHandler.postIdle(new Runnable() {
public void run() {
synchronized (LoaderThread.this) {
mWorkspaceDoneBinding = true;
Log.d(TAG, "done with workspace");
LoaderThread.this.notify();
}
}
});
Log.d(TAG, "waiting to be done with workspace");
while (!mStopped && !mWorkspaceDoneBinding) {
try {
this.wait();
} catch (InterruptedException ex) {
// Ignore
}
}
Log.d(TAG, "done waiting to be done with workspace");
}
// Load all apps if they're dirty
int allAppsSeq;
boolean allAppsDirty;
synchronized (mLock) {
allAppsSeq = mAllAppsSeq;
allAppsDirty = mAllAppsSeq != mLastAllAppsSeq;
//Log.d(TAG, "mAllAppsSeq=" + mAllAppsSeq
// + " mLastAllAppsSeq=" + mLastAllAppsSeq + " allAppsDirty");
}
if (allAppsDirty) {
loadAllApps();
}
synchronized (mLock) {
// If we're not stopped, and nobody has incremented mAllAppsSeq.
if (mStopped) {
return;
}
if (allAppsSeq == mAllAppsSeq) {
mLastAllAppsSeq = mAllAppsSeq;
}
}
// Bind all apps
if (allAppsDirty) {
bindAllApps();
}
// Clear out this reference, otherwise we end up holding it until all of the
// callback runnables are done.
mContext = null;
synchronized (mLock) {
// Setting the reference is atomic, but we can't do it inside the other critical
// sections.
mLoaderThread = null;
}
}
public void stopLocked() {
synchronized (LoaderThread.this) {
mStopped = true;
this.notify();
}
}
/**
* Gets the callbacks object. If we've been stopped, or if the launcher object
* has somehow been garbage collected, return null instead.
*/
Callbacks tryGetCallbacks() {
synchronized (mLock) {
if (mStopped) {
return null;
}
final Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
Log.w(TAG, "no mCallbacks");
return null;
}
return callbacks;
}
}
private void loadWorkspace() {
long t = SystemClock.uptimeMillis();
final Context context = mContext;
final ContentResolver contentResolver = context.getContentResolver();
final PackageManager manager = context.getPackageManager();
/* TODO
if (mLocaleChanged) {
updateShortcutLabels(contentResolver, manager);
}
*/
mItems.clear();
mAppWidgets.clear();
final Cursor c = contentResolver.query(
LauncherSettings.Favorites.CONTENT_URI, null, null, null, null);
try {
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.INTENT);
final int titleIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.TITLE);
final int iconTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_TYPE);
final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON);
final int iconPackageIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_PACKAGE);
final int iconResourceIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ICON_RESOURCE);
final int containerIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.CONTAINER);
final int itemTypeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.ITEM_TYPE);
final int appWidgetIdIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.APPWIDGET_ID);
final int screenIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SCREEN);
final int cellXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLX);
final int cellYIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.CELLY);
final int spanXIndex = c.getColumnIndexOrThrow
(LauncherSettings.Favorites.SPANX);
final int spanYIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.SPANY);
final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI);
final int displayModeIndex = c.getColumnIndexOrThrow(
LauncherSettings.Favorites.DISPLAY_MODE);
ApplicationInfo info;
String intentDescription;
Widget widgetInfo;
LauncherAppWidgetInfo appWidgetInfo;
int container;
long id;
Intent intent;
while (!mStopped && c.moveToNext()) {
try {
int itemType = c.getInt(itemTypeIndex);
switch (itemType) {
case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
intentDescription = c.getString(intentIndex);
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
continue;
}
if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
info = getApplicationInfo(manager, intent, context);
} else {
info = getApplicationInfoShortcut(c, context, iconTypeIndex,
iconPackageIndex, iconResourceIndex, iconIndex);
}
if (info == null) {
info = new ApplicationInfo();
info.icon = manager.getDefaultActivityIcon();
}
if (info != null) {
info.title = c.getString(titleIndex);
info.intent = intent;
info.id = c.getLong(idIndex);
container = c.getInt(containerIndex);
info.container = container;
info.screen = c.getInt(screenIndex);
info.cellX = c.getInt(cellXIndex);
info.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(info);
break;
default:
// Item is in a user folder
UserFolderInfo folderInfo =
findOrMakeUserFolder(mFolders, container);
folderInfo.add(info);
break;
}
}
break;
case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
id = c.getLong(idIndex);
UserFolderInfo folderInfo = findOrMakeUserFolder(mFolders, id);
folderInfo.title = c.getString(titleIndex);
folderInfo.id = id;
container = c.getInt(containerIndex);
folderInfo.container = container;
folderInfo.screen = c.getInt(screenIndex);
folderInfo.cellX = c.getInt(cellXIndex);
folderInfo.cellY = c.getInt(cellYIndex);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(folderInfo);
break;
}
mFolders.put(folderInfo.id, folderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
id = c.getLong(idIndex);
LiveFolderInfo liveFolderInfo = findOrMakeLiveFolder(mFolders, id);
intentDescription = c.getString(intentIndex);
intent = null;
if (intentDescription != null) {
try {
intent = Intent.parseUri(intentDescription, 0);
} catch (URISyntaxException e) {
// Ignore, a live folder might not have a base intent
}
}
liveFolderInfo.title = c.getString(titleIndex);
liveFolderInfo.id = id;
container = c.getInt(containerIndex);
liveFolderInfo.container = container;
liveFolderInfo.screen = c.getInt(screenIndex);
liveFolderInfo.cellX = c.getInt(cellXIndex);
liveFolderInfo.cellY = c.getInt(cellYIndex);
liveFolderInfo.uri = Uri.parse(c.getString(uriIndex));
liveFolderInfo.baseIntent = intent;
liveFolderInfo.displayMode = c.getInt(displayModeIndex);
loadLiveFolderIcon(context, c, iconTypeIndex, iconPackageIndex,
iconResourceIndex, liveFolderInfo);
switch (container) {
case LauncherSettings.Favorites.CONTAINER_DESKTOP:
mItems.add(liveFolderInfo);
break;
}
mFolders.put(liveFolderInfo.id, liveFolderInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
widgetInfo = Widget.makeSearch();
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP ignoring!");
continue;
}
widgetInfo.id = c.getLong(idIndex);
widgetInfo.screen = c.getInt(screenIndex);
widgetInfo.container = container;
widgetInfo.cellX = c.getInt(cellXIndex);
widgetInfo.cellY = c.getInt(cellYIndex);
mItems.add(widgetInfo);
break;
case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
// Read all Launcher-specific widget details
int appWidgetId = c.getInt(appWidgetIdIndex);
appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId);
appWidgetInfo.id = c.getLong(idIndex);
appWidgetInfo.screen = c.getInt(screenIndex);
appWidgetInfo.cellX = c.getInt(cellXIndex);
appWidgetInfo.cellY = c.getInt(cellYIndex);
appWidgetInfo.spanX = c.getInt(spanXIndex);
appWidgetInfo.spanY = c.getInt(spanYIndex);
container = c.getInt(containerIndex);
if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP) {
Log.e(TAG, "Widget found where container "
+ "!= CONTAINER_DESKTOP -- ignoring!");
continue;
}
appWidgetInfo.container = c.getInt(containerIndex);
mAppWidgets.add(appWidgetInfo);
break;
}
} catch (Exception e) {
Log.w(TAG, "Desktop items loading interrupted:", e);
}
}
} finally {
c.close();
}
Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
}
/**
* Read everything out of our database.
*/
private void bindWorkspace() {
final long t = SystemClock.uptimeMillis();
// Don't use these two variables in any of the callback runnables.
// Otherwise we hold a reference to them.
Callbacks callbacks = mCallbacks.get();
if (callbacks == null) {
// This launcher has exited and nobody bothered to tell us. Just bail.
Log.w(TAG, "LoaderThread running with no launcher");
return;
}
int N;
// Tell the workspace that we're about to start firing items at it
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.startBinding();
}
}
});
// Add the items to the workspace.
N = mItems.size();
for (int i=0; i<N; i+=ITEMS_CHUNK) {
final int start = i;
final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i);
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindItems(mItems, start, start+chunkSize);
}
}
});
}
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindFolders(mFolders);
}
}
});
// Wait until the queue goes empty.
mHandler.postIdle(new Runnable() {
public void run() {
Log.d(TAG, "Going to start binding widgets soon.");
}
});
// Bind the widgets, one at a time.
// WARNING: this is calling into the workspace from the background thread,
// but since getCurrentScreen() just returns the int, we should be okay. This
// is just a hint for the order, and if it's wrong, we'll be okay.
// TODO: instead, we should have that push the current screen into here.
final int currentScreen = callbacks.getCurrentWorkspaceScreen();
N = mAppWidgets.size();
// once for the current screen
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen == currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// once for the other screens
for (int i=0; i<N; i++) {
final LauncherAppWidgetInfo widget = mAppWidgets.get(i);
if (widget.screen != currentScreen) {
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAppWidget(widget);
}
}
});
}
}
// Tell the workspace that we're done.
mHandler.post(new Runnable() {
public void run() {
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.finishBindingItems();
}
}
});
// If we're profiling, this is the last thing in the queue.
mHandler.post(new Runnable() {
public void run() {
Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms");
if (Launcher.PROFILE_ROTATE) {
android.os.Debug.stopMethodTracing();
}
}
});
}
private void loadAllApps() {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final Callbacks callbacks = tryGetCallbacks();
if (callbacks == null) {
return;
}
final Context context = mContext;
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
synchronized (mLock) {
mBeforeFirstLoad = false;
mAllAppsList.clear();
if (apps != null) {
long t = SystemClock.uptimeMillis();
int N = apps.size();
Utilities.BubbleText bubble = new Utilities.BubbleText(context);
for (int i=0; i<N && !mStopped; i++) {
// This builds the icon bitmaps.
mAllAppsList.add(AppInfoCache.cache(apps.get(i), context, bubble));
}
Collections.sort(mAllAppsList.data, sComparator);
Collections.sort(mAllAppsList.added, sComparator);
Log.d(TAG, "cached app icons in " + (SystemClock.uptimeMillis()-t) + "ms");
}
}
}
private void bindAllApps() {
synchronized (mLock) {
final ArrayList<ApplicationInfo> results = mAllAppsList.added;
mAllAppsList.added = new ArrayList<ApplicationInfo>();
mHandler.post(new Runnable() {
public void run() {
final long t = SystemClock.uptimeMillis();
final int count = results.size();
Callbacks callbacks = tryGetCallbacks();
if (callbacks != null) {
callbacks.bindAllApplications(results);
}
Log.d(TAG, "bound app " + count + " icons in "
+ (SystemClock.uptimeMillis()-t) + "ms");
}
});
}
}
}
}
/**
* Make an ApplicationInfo object for an application.
*/
private static ApplicationInfo getApplicationInfo(PackageManager manager, Intent intent,
Context context) {
final ResolveInfo resolveInfo = manager.resolveActivity(intent, 0);
if (resolveInfo == null) {
return null;
}
final ApplicationInfo info = new ApplicationInfo();
final ActivityInfo activityInfo = resolveInfo.activityInfo;
info.icon = Utilities.createIconThumbnail(activityInfo.loadIcon(manager), context);
if (info.title == null || info.title.length() == 0) {
info.title = activityInfo.loadLabel(manager);
}
if (info.title == null) {
info.title = "";
}
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
return info;
}
/**
* Make an ApplicationInfo object for a sortcut
*/
private static ApplicationInfo getApplicationInfoShortcut(Cursor c, Context context,
int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex) {
final ApplicationInfo info = new ApplicationInfo();
info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
info.icon = Utilities.createIconThumbnail(resources.getDrawable(id), context);
} catch (Exception e) {
info.icon = packageManager.getDefaultActivityIcon();
}
info.iconResource = new Intent.ShortcutIconResource();
info.iconResource.packageName = packageName;
info.iconResource.resourceName = resourceName;
info.customIcon = false;
break;
case LauncherSettings.Favorites.ICON_TYPE_BITMAP:
byte[] data = c.getBlob(iconIndex);
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
info.icon = new FastBitmapDrawable(
Utilities.createBitmapThumbnail(bitmap, context));
} catch (Exception e) {
packageManager = context.getPackageManager();
info.icon = packageManager.getDefaultActivityIcon();
}
info.filtered = true;
info.customIcon = true;
break;
default:
info.icon = context.getPackageManager().getDefaultActivityIcon();
info.customIcon = false;
break;
}
return info;
}
private static void loadLiveFolderIcon(Context context, Cursor c, int iconTypeIndex,
int iconPackageIndex, int iconResourceIndex, LiveFolderInfo liveFolderInfo) {
int iconType = c.getInt(iconTypeIndex);
switch (iconType) {
case LauncherSettings.Favorites.ICON_TYPE_RESOURCE:
String packageName = c.getString(iconPackageIndex);
String resourceName = c.getString(iconResourceIndex);
PackageManager packageManager = context.getPackageManager();
try {
Resources resources = packageManager.getResourcesForApplication(packageName);
final int id = resources.getIdentifier(resourceName, null, null);
liveFolderInfo.icon = resources.getDrawable(id);
} catch (Exception e) {
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
liveFolderInfo.iconResource = new Intent.ShortcutIconResource();
liveFolderInfo.iconResource.packageName = packageName;
liveFolderInfo.iconResource.resourceName = resourceName;
break;
default:
liveFolderInfo.icon =
context.getResources().getDrawable(R.drawable.ic_launcher_folder);
}
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously,
* or make a new one.
*/
private static UserFolderInfo findOrMakeUserFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof UserFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new UserFolderInfo();
folders.put(id, folderInfo);
}
return (UserFolderInfo) folderInfo;
}
/**
* Return an existing UserFolderInfo object if we have encountered this ID previously, or make a
* new one.
*/
private static LiveFolderInfo findOrMakeLiveFolder(HashMap<Long, FolderInfo> folders, long id) {
// See if a placeholder was created for us already
FolderInfo folderInfo = folders.get(id);
if (folderInfo == null || !(folderInfo instanceof LiveFolderInfo)) {
// No placeholder -- create a new instance
folderInfo = new LiveFolderInfo();
folders.put(id, folderInfo);
}
return (LiveFolderInfo) folderInfo;
}
private static void updateShortcutLabels(ContentResolver resolver, PackageManager manager) {
final Cursor c = resolver.query(LauncherSettings.Favorites.CONTENT_URI,
new String[] { LauncherSettings.Favorites._ID, LauncherSettings.Favorites.TITLE,
LauncherSettings.Favorites.INTENT, LauncherSettings.Favorites.ITEM_TYPE },
null, null, null);
final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID);
final int intentIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.INTENT);
final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE);
final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE);
// boolean changed = false;
try {
while (c.moveToNext()) {
try {
if (c.getInt(itemTypeIndex) !=
LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) {
continue;
}
final String intentUri = c.getString(intentIndex);
if (intentUri != null) {
final Intent shortcut = Intent.parseUri(intentUri, 0);
if (Intent.ACTION_MAIN.equals(shortcut.getAction())) {
final ComponentName name = shortcut.getComponent();
if (name != null) {
final ActivityInfo activityInfo = manager.getActivityInfo(name, 0);
final String title = c.getString(titleIndex);
String label = getLabel(manager, activityInfo);
if (title == null || !title.equals(label)) {
final ContentValues values = new ContentValues();
values.put(LauncherSettings.Favorites.TITLE, label);
resolver.update(
LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION,
values, "_id=?",
new String[] { String.valueOf(c.getLong(idIndex)) });
// changed = true;
}
}
}
}
} catch (URISyntaxException e) {
// Ignore
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
} finally {
c.close();
}
// if (changed) resolver.notifyChange(Settings.Favorites.CONTENT_URI, null);
}
private static String getLabel(PackageManager manager, ActivityInfo activityInfo) {
String label = activityInfo.loadLabel(manager).toString();
if (label == null) {
label = manager.getApplicationLabel(activityInfo.applicationInfo).toString();
if (label == null) {
label = activityInfo.name;
}
}
return label;
}
private static final Collator sCollator = Collator.getInstance();
private static final Comparator<ApplicationInfo> sComparator
= new Comparator<ApplicationInfo>() {
public final int compare(ApplicationInfo a, ApplicationInfo b) {
return sCollator.compare(a.title.toString(), b.title.toString());
}
};
}
|
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest3.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest3.java
index 91287bd..f536be8 100644
--- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest3.java
+++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest3.java
@@ -1,73 +1,73 @@
package org.akquinet.audit.bsi.httpd;
import java.io.File;
import java.util.List;
import org.akquinet.audit.FormattedConsole;
import org.akquinet.audit.ModuleHelper;
import org.akquinet.audit.YesNoQuestion;
import org.akquinet.httpd.ConfigFile;
import org.akquinet.httpd.syntax.Directive;
public class Quest3 extends ModuleHelper implements YesNoQuestion
{
private static final String _id = "Quest3";
private static final FormattedConsole _console = FormattedConsole.getDefault();
private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q1;
public Quest3(ConfigFile conf, File apacheExecutable)
{
super(conf, apacheExecutable);
}
@Override
public boolean answer()
{
_console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----");
//TODO: test
List<Directive> loadList = getLoadModuleList();
for (Directive directive : loadList)
{
- String[] arguments = directive.getValue().trim().split("( |\t)*");
+ String[] arguments = directive.getValue().trim().split("[ \t]+");
if(arguments == null || arguments.length < 2)
{
continue;
}
if(arguments[0].equals("security2_module"))
{
Directive modSec = directive;
_console.printAnswer(_level, true, "ModSecurity is being loaded:");
_console.println(_level, modSec.getLinenumber() + ": " + modSec.getName() + " " + modSec.getValue());
return true;
}
}
//maybe ModSecurity is compiled into the apache binary, check for that:
String[] modList = getCompiledIntoModulesList();
for (String str : modList)
{
if(str.matches("( |\t)*mod_security.c"))
{
_console.printAnswer(_level, true, "ModSecurity is compiled into the httpd binary.");
return true;
}
}
_console.printAnswer(_level, false, "ModSecurity seems not to be loaded.");
return false;
}
@Override
public boolean isCritical()
{
return false;
}
@Override
public String getID()
{
return _id;
}
}
| true | true | public boolean answer()
{
_console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----");
//TODO: test
List<Directive> loadList = getLoadModuleList();
for (Directive directive : loadList)
{
String[] arguments = directive.getValue().trim().split("( |\t)*");
if(arguments == null || arguments.length < 2)
{
continue;
}
if(arguments[0].equals("security2_module"))
{
Directive modSec = directive;
_console.printAnswer(_level, true, "ModSecurity is being loaded:");
_console.println(_level, modSec.getLinenumber() + ": " + modSec.getName() + " " + modSec.getValue());
return true;
}
}
//maybe ModSecurity is compiled into the apache binary, check for that:
String[] modList = getCompiledIntoModulesList();
for (String str : modList)
{
if(str.matches("( |\t)*mod_security.c"))
{
_console.printAnswer(_level, true, "ModSecurity is compiled into the httpd binary.");
return true;
}
}
_console.printAnswer(_level, false, "ModSecurity seems not to be loaded.");
return false;
}
| public boolean answer()
{
_console.println(FormattedConsole.OutputLevel.HEADING, "----" + _id + "----");
//TODO: test
List<Directive> loadList = getLoadModuleList();
for (Directive directive : loadList)
{
String[] arguments = directive.getValue().trim().split("[ \t]+");
if(arguments == null || arguments.length < 2)
{
continue;
}
if(arguments[0].equals("security2_module"))
{
Directive modSec = directive;
_console.printAnswer(_level, true, "ModSecurity is being loaded:");
_console.println(_level, modSec.getLinenumber() + ": " + modSec.getName() + " " + modSec.getValue());
return true;
}
}
//maybe ModSecurity is compiled into the apache binary, check for that:
String[] modList = getCompiledIntoModulesList();
for (String str : modList)
{
if(str.matches("( |\t)*mod_security.c"))
{
_console.printAnswer(_level, true, "ModSecurity is compiled into the httpd binary.");
return true;
}
}
_console.printAnswer(_level, false, "ModSecurity seems not to be loaded.");
return false;
}
|
diff --git a/henplus/src/henplus/commands/AutocommitCommand.java b/henplus/src/henplus/commands/AutocommitCommand.java
index d85fcd2..1493f67 100644
--- a/henplus/src/henplus/commands/AutocommitCommand.java
+++ b/henplus/src/henplus/commands/AutocommitCommand.java
@@ -1,68 +1,74 @@
/*
* This is free software, licensed under the Gnu Public License (GPL)
* get a copy from <http://www.gnu.org/licenses/gpl.html>
*
* author: Henner Zeller <H.Zeller@acm.org>
*/
package henplus.commands;
import henplus.HenPlus;
import henplus.SQLSession;
import henplus.AbstractCommand;
import java.util.StringTokenizer;
import java.sql.SQLException;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
/**
* document me.
*/
public class AutocommitCommand extends AbstractCommand {
/**
* returns the command-strings this command can handle.
*/
public String[] getCommandList() {
return new String[] {
"autocommit-on", "autocommit-off"
};
}
/**
* execute the command given.
*/
public int execute(SQLSession session, String cmd, String param) {
try {
if ("autocommit-on".equals(cmd)) {
+ /*
+ * due to a bug in Sybase, we have to close the
+ * transaction first before setting autcommit.
+ * This is probably a save choice to do.
+ */
+ session.getConnection().commit();
session.getConnection().setAutoCommit(true);
System.err.println("set autocommit on");
}
else if ("autocommit-off".equals(cmd)) {
session.getConnection().setAutoCommit(false);
System.err.println("set autocommit off");
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return SUCCESS;
}
/**
* return a descriptive string.
*/
public String getShortDescription() {
return "switches autocommit on/off";
}
}
/*
* Local variables:
* c-basic-offset: 4
* compile-command: "ant -emacs -find build.xml"
* End:
*/
| true | true | public int execute(SQLSession session, String cmd, String param) {
try {
if ("autocommit-on".equals(cmd)) {
session.getConnection().setAutoCommit(true);
System.err.println("set autocommit on");
}
else if ("autocommit-off".equals(cmd)) {
session.getConnection().setAutoCommit(false);
System.err.println("set autocommit off");
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return SUCCESS;
}
| public int execute(SQLSession session, String cmd, String param) {
try {
if ("autocommit-on".equals(cmd)) {
/*
* due to a bug in Sybase, we have to close the
* transaction first before setting autcommit.
* This is probably a save choice to do.
*/
session.getConnection().commit();
session.getConnection().setAutoCommit(true);
System.err.println("set autocommit on");
}
else if ("autocommit-off".equals(cmd)) {
session.getConnection().setAutoCommit(false);
System.err.println("set autocommit off");
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return SUCCESS;
}
|
diff --git a/src/com/android/mms/transaction/MmsSystemEventReceiver.java b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
index 9b78ea08..d89a31a4 100644
--- a/src/com/android/mms/transaction/MmsSystemEventReceiver.java
+++ b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
@@ -1,96 +1,99 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.util.Log;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
/**
* MmsSystemEventReceiver receives the
* {@link android.content.intent.ACTION_BOOT_COMPLETED},
* {@link com.android.internal.telephony.TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED}
* and performs a series of operations which may include:
* <ul>
* <li>Show/hide the icon in notification area which is used to indicate
* whether there is new incoming message.</li>
* <li>Resend the MM's in the outbox.</li>
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = "MmsSystemEventReceiver";
private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "wakeUpService: start transaction service ...");
}
context.startService(new Intent(context, TransactionService.class));
}
@Override
public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
+ if (mmsNetworkInfo == null) {
+ return;
+ }
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
| public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo == null) {
return;
}
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
|
diff --git a/src/org/timadorus/webapp/client/login/LoginPanel.java b/src/org/timadorus/webapp/client/login/LoginPanel.java
index ed43c10..d6d72b8 100644
--- a/src/org/timadorus/webapp/client/login/LoginPanel.java
+++ b/src/org/timadorus/webapp/client/login/LoginPanel.java
@@ -1,296 +1,296 @@
package org.timadorus.webapp.client.login;
import java.util.Date;
import org.timadorus.webapp.client.SessionId;
import org.timadorus.webapp.client.TimadorusWebApp;
import org.timadorus.webapp.client.User;
import org.timadorus.webapp.client.rpc.service.LoginService;
import org.timadorus.webapp.client.rpc.service.LoginServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.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.Cookies;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.HistoryListener;
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 Login
@SuppressWarnings("deprecation")
public class LoginPanel extends FormPanel implements HistoryListener {
private final int rows = 4;
private final int columns = 2;
private Grid grid = new Grid(rows, columns);
private TextBox userBox = new TextBox();
private PasswordTextBox passBox = new PasswordTextBox();
private Label userLabel = new Label("Benutzername");;
private Label passLabel = new Label("Passwort");
private HTML errorHTML = new HTML();
private Button submit = new Button("Einloggen");
public User user;
private SessionId sessionId;
private TimadorusWebApp entry;
private static final long TWO_MIN = 1000 * 60 * 2;
private int logincounter;
private static LoginPanel loginPanel;
public LoginPanel(SessionId session, TimadorusWebApp entryIn) {
super();
this.entry = entryIn;
setUser(new User());
logincounter = 0;
setupHistory();
userBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
userBox.setText("");
}
});
passBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
passBox.setText("");
}
});
this.sessionId = session;
// RootPanel.get("context").add(new Label("Benutzer login"));
grid.setWidget(0, 0, userLabel);
grid.setWidget(0, 1, userBox);
grid.setWidget(1, 0, passLabel);
grid.setWidget(1, 1, passBox);
grid.setWidget(2, 1, errorHTML);
grid.setWidget(3, 1, submit);
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Wird ausgelöst, wenn Button gedrückt wurde
*/
public void onClick(ClickEvent event) {
handleEvent();
}
/**
* Prüft ob "Enter" gedrückt wurde
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
handleEvent();
}
}
private void handleEvent() {
clearError();
getUser().setUsername(userBox.getText());
getUser().setPassword(passBox.getText());
if (getUser().getUsername().equals("") || user.getPassword().equals("")) {
loginInvalid("Bitte Felder ausf�llen!");
History.newItem("login");
} else {
sendToServer();
userBox.setText("");
passBox.setText("");
}
}
/*public void sendToServerLogout(){
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
if (result != null) {
if (result.equals(LOGOUT_STATE)) {
gettimadorus().setLoggedin(false);
Cookies.setCookie("session", null);
sessionId.setSessionId(null);
// System.out.println("logout session => " + result);
History.newItem("login");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.logout(user, asyncCallback);
}*/
/**
* Username und Passwort an Server senden
*/
private void sendToServer() {
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
final int maxAttempts = 4;
if (result != null) {
if (result.equals(User.USER_INACTIVE)) {
loginInvalid("User ist deaktiviert!");
History.newItem("welcome");
- RootPanel.get("content").add(
+ RootPanel.get("content").add(
new HTML("<div id=\"info\" class=\"info\">Der angegebene User ist deaktiviert. "
+ "Das kann mehrere Gruende haben<br />(Anmerkung vom Programmierer: Welche denn? "
+ "Gesperrt durch Admin oder sowas? Oder ist damit gemeint 'Registriert, aber Mail "
+ "noch nicht verifiziert'? Oder beides?) </div>"));
submit.setEnabled(true);
gettimadorus().setLoggedin(false);
} else if (result.equals(User.USER_INVALID)) {
loginInvalid("Username und/oder Passwort falsch!");
submit.setEnabled(true);
logincounter++;
gettimadorus().setLoggedin(false);
System.out.println("logincounter " + logincounter);
if (logincounter < maxAttempts) {
History.newItem("login");
} else {
History.newItem("welcome");
}
} else {
gettimadorus().setLoggedin(true);
getUser().setActive(true);
Cookies.setCookie("session", result, new Date(System.currentTimeMillis() + TWO_MIN));
sessionId.setSessionId(result);
System.out.println("login session => " + result);
History.newItem("welcome");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.login(user, asyncCallback);
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
submit.addClickHandler(handler);
userBox.addKeyUpHandler(handler);
passBox.addKeyUpHandler(handler);
setWidget(grid);
setStyleName("formPanel");
}
public static final LoginPanel getLoginPanel(SessionId sessionId, TimadorusWebApp entry) {
if (LoginPanel.loginPanel == null) {
LoginPanel.loginPanel = new LoginPanel(sessionId, entry);
}
return LoginPanel.loginPanel;
}
private void setupHistory() {
History.addHistoryListener(this);
// History.onHistoryChanged("login");
}
public void setTimadorusWebApp(TimadorusWebApp webapp) {
this.entry = webapp;
}
/**
* In dieser Methode wird das Ereignis "Login ungültig" verarbeitet.
*/
private void loginInvalid(String message) {
errorHTML.setHTML("<span class=\"error\">" + message + "</span>");
}
private void clearError() {
errorHTML.setHTML("");
Element info = DOM.getElementById("info");
if (info != null) {
info.getParentElement().removeChild(info);
}
}
@Override
public void onHistoryChanged(String historyToken) {
// if (LOGIN_STATE.equals(historyToken)) {
// gettimadorus().loadLoginPanel();
// }else if (LOGOUT_STATE.equals(historyToken)) {
// gettimadorus().loadLogoutPanel();
// } else if (WELCOME_STATE.equals(historyToken)) {
// gettimadorus().loadWelcomePanel();
// } else if (CREATE_CHARACTER_STATE.equals(historyToken)) {
// gettimadorus().loadCreateCharacter();
// } else if (REGISTER_STATE.equals(historyToken)) {
// gettimadorus().loadRegisterPanel();
// }
}
private TimadorusWebApp gettimadorus() {
return entry;
}
public User getUser() {
return user;
}
public void setUser(User userIn) {
this.user = userIn;
}
}
| true | true | public LoginPanel(SessionId session, TimadorusWebApp entryIn) {
super();
this.entry = entryIn;
setUser(new User());
logincounter = 0;
setupHistory();
userBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
userBox.setText("");
}
});
passBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
passBox.setText("");
}
});
this.sessionId = session;
// RootPanel.get("context").add(new Label("Benutzer login"));
grid.setWidget(0, 0, userLabel);
grid.setWidget(0, 1, userBox);
grid.setWidget(1, 0, passLabel);
grid.setWidget(1, 1, passBox);
grid.setWidget(2, 1, errorHTML);
grid.setWidget(3, 1, submit);
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Wird ausgelöst, wenn Button gedrückt wurde
*/
public void onClick(ClickEvent event) {
handleEvent();
}
/**
* Prüft ob "Enter" gedrückt wurde
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
handleEvent();
}
}
private void handleEvent() {
clearError();
getUser().setUsername(userBox.getText());
getUser().setPassword(passBox.getText());
if (getUser().getUsername().equals("") || user.getPassword().equals("")) {
loginInvalid("Bitte Felder ausf�llen!");
History.newItem("login");
} else {
sendToServer();
userBox.setText("");
passBox.setText("");
}
}
/*public void sendToServerLogout(){
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
if (result != null) {
if (result.equals(LOGOUT_STATE)) {
gettimadorus().setLoggedin(false);
Cookies.setCookie("session", null);
sessionId.setSessionId(null);
// System.out.println("logout session => " + result);
History.newItem("login");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.logout(user, asyncCallback);
}*/
/**
* Username und Passwort an Server senden
*/
private void sendToServer() {
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
final int maxAttempts = 4;
if (result != null) {
if (result.equals(User.USER_INACTIVE)) {
loginInvalid("User ist deaktiviert!");
History.newItem("welcome");
RootPanel.get("content").add(
new HTML("<div id=\"info\" class=\"info\">Der angegebene User ist deaktiviert. "
+ "Das kann mehrere Gruende haben<br />(Anmerkung vom Programmierer: Welche denn? "
+ "Gesperrt durch Admin oder sowas? Oder ist damit gemeint 'Registriert, aber Mail "
+ "noch nicht verifiziert'? Oder beides?) </div>"));
submit.setEnabled(true);
gettimadorus().setLoggedin(false);
} else if (result.equals(User.USER_INVALID)) {
loginInvalid("Username und/oder Passwort falsch!");
submit.setEnabled(true);
logincounter++;
gettimadorus().setLoggedin(false);
System.out.println("logincounter " + logincounter);
if (logincounter < maxAttempts) {
History.newItem("login");
} else {
History.newItem("welcome");
}
} else {
gettimadorus().setLoggedin(true);
getUser().setActive(true);
Cookies.setCookie("session", result, new Date(System.currentTimeMillis() + TWO_MIN));
sessionId.setSessionId(result);
System.out.println("login session => " + result);
History.newItem("welcome");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.login(user, asyncCallback);
}
}
| public LoginPanel(SessionId session, TimadorusWebApp entryIn) {
super();
this.entry = entryIn;
setUser(new User());
logincounter = 0;
setupHistory();
userBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
userBox.setText("");
}
});
passBox.addFocusHandler(new FocusHandler() {
@Override
public void onFocus(FocusEvent event) {
passBox.setText("");
}
});
this.sessionId = session;
// RootPanel.get("context").add(new Label("Benutzer login"));
grid.setWidget(0, 0, userLabel);
grid.setWidget(0, 1, userBox);
grid.setWidget(1, 0, passLabel);
grid.setWidget(1, 1, passBox);
grid.setWidget(2, 1, errorHTML);
grid.setWidget(3, 1, submit);
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Wird ausgelöst, wenn Button gedrückt wurde
*/
public void onClick(ClickEvent event) {
handleEvent();
}
/**
* Prüft ob "Enter" gedrückt wurde
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
handleEvent();
}
}
private void handleEvent() {
clearError();
getUser().setUsername(userBox.getText());
getUser().setPassword(passBox.getText());
if (getUser().getUsername().equals("") || user.getPassword().equals("")) {
loginInvalid("Bitte Felder ausf�llen!");
History.newItem("login");
} else {
sendToServer();
userBox.setText("");
passBox.setText("");
}
}
/*public void sendToServerLogout(){
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
if (result != null) {
if (result.equals(LOGOUT_STATE)) {
gettimadorus().setLoggedin(false);
Cookies.setCookie("session", null);
sessionId.setSessionId(null);
// System.out.println("logout session => " + result);
History.newItem("login");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.logout(user, asyncCallback);
}*/
/**
* Username und Passwort an Server senden
*/
private void sendToServer() {
LoginServiceAsync loginServiceAsync = GWT.create(LoginService.class);
AsyncCallback<String> asyncCallback = new AsyncCallback<String>() {
public void onSuccess(String result) {
final int maxAttempts = 4;
if (result != null) {
if (result.equals(User.USER_INACTIVE)) {
loginInvalid("User ist deaktiviert!");
History.newItem("welcome");
RootPanel.get("content").add(
new HTML("<div id=\"info\" class=\"info\">Der angegebene User ist deaktiviert. "
+ "Das kann mehrere Gruende haben<br />(Anmerkung vom Programmierer: Welche denn? "
+ "Gesperrt durch Admin oder sowas? Oder ist damit gemeint 'Registriert, aber Mail "
+ "noch nicht verifiziert'? Oder beides?) </div>"));
submit.setEnabled(true);
gettimadorus().setLoggedin(false);
} else if (result.equals(User.USER_INVALID)) {
loginInvalid("Username und/oder Passwort falsch!");
submit.setEnabled(true);
logincounter++;
gettimadorus().setLoggedin(false);
System.out.println("logincounter " + logincounter);
if (logincounter < maxAttempts) {
History.newItem("login");
} else {
History.newItem("welcome");
}
} else {
gettimadorus().setLoggedin(true);
getUser().setActive(true);
Cookies.setCookie("session", result, new Date(System.currentTimeMillis() + TWO_MIN));
sessionId.setSessionId(result);
System.out.println("login session => " + result);
History.newItem("welcome");
}
}
}
public void onFailure(Throwable caught) {
gettimadorus().showDialogBox("Fehlermeldung", "Fehler bei der Anmeldung");
loginInvalid("Fehler bei der Anmeldung!");
History.newItem("login");
System.out.println(caught);
}
};
loginServiceAsync.login(user, asyncCallback);
}
}
|
diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/HeaderBlock.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/HeaderBlock.java
index d03d2d24d9..ee305a6f84 100644
--- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/HeaderBlock.java
+++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/HeaderBlock.java
@@ -1,34 +1,38 @@
/**
* 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.yarn.webapp.view;
import static org.apache.hadoop.yarn.webapp.Params.*;
public class HeaderBlock extends HtmlBlock {
@Override protected void render(Block html) {
+ String loggedIn = "";
+ if (request().getRemoteUser() != null) {
+ loggedIn = "Logged in as: " + request().getRemoteUser();
+ }
html.
div("#header.ui-widget").
div("#user").
- _("Logged in as: "+ request().getRemoteUser())._().
+ _(loggedIn)._().
div("#logo").
img("/static/hadoop-st.png")._().
h1($(TITLE))._();
}
}
| false | true | @Override protected void render(Block html) {
html.
div("#header.ui-widget").
div("#user").
_("Logged in as: "+ request().getRemoteUser())._().
div("#logo").
img("/static/hadoop-st.png")._().
h1($(TITLE))._();
}
| @Override protected void render(Block html) {
String loggedIn = "";
if (request().getRemoteUser() != null) {
loggedIn = "Logged in as: " + request().getRemoteUser();
}
html.
div("#header.ui-widget").
div("#user").
_(loggedIn)._().
div("#logo").
img("/static/hadoop-st.png")._().
h1($(TITLE))._();
}
|
diff --git a/2waySMS/app/controllers/Security.java b/2waySMS/app/controllers/Security.java
index 56e1499..a276861 100644
--- a/2waySMS/app/controllers/Security.java
+++ b/2waySMS/app/controllers/Security.java
@@ -1,13 +1,13 @@
package controllers;
import play.libs.Crypto;
import models.User;
public class Security extends Secure.Security {
static boolean authenticate(String username, String password) {
- User user = User.find("byMunchkinId", username.toLowerCase()).first();
+ User user = User.find("byMunchkinId", username.toUpperCase().trim()).first();
return user != null
&& user.password.equals(Crypto.passwordHash(password));
}
}
| true | true | static boolean authenticate(String username, String password) {
User user = User.find("byMunchkinId", username.toLowerCase()).first();
return user != null
&& user.password.equals(Crypto.passwordHash(password));
}
| static boolean authenticate(String username, String password) {
User user = User.find("byMunchkinId", username.toUpperCase().trim()).first();
return user != null
&& user.password.equals(Crypto.passwordHash(password));
}
|
diff --git a/src/game/NetworkManager.java b/src/game/NetworkManager.java
index d0f5976..8e9e892 100644
--- a/src/game/NetworkManager.java
+++ b/src/game/NetworkManager.java
@@ -1,151 +1,154 @@
package game;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import level.Loader;
import level.Point;
import network.Input;
import network.Server;
import entities.Bomb;
import entities.Player;
import enums.Gamemode;
import enums.NetworkInputType;
public class NetworkManager extends Thread {
private Server server;
private Socket socket;
private BufferedReader inStream;
private DataOutputStream outStream;
private CopyOnWriteArrayList<Input> out_queue, in_queue;
public int playerID;
public CopyOnWriteArrayList<NetworkPlayerKeys> networkplayer;
public NetworkManager(Server server) {
this.server = server;
this.out_queue = new CopyOnWriteArrayList<Input>();
this.in_queue = new CopyOnWriteArrayList<Input>();
this.networkplayer = new CopyOnWriteArrayList<NetworkPlayerKeys>();
}
public boolean connect() {
try {
this.socket = new Socket(this.server.host, this.server.port);
} catch (IOException e) {
Debug.log(Debug.ERROR, "Can't connect to gameserver");
return false;
}
try {
this.inStream = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.outStream = new DataOutputStream(this.socket.getOutputStream());
} catch (IOException e) {
Debug.log(Debug.ERROR, "Can't get input/output stream");
}
return true;
}
@Override
public void run() {
Game.gamemode = Gamemode.NETWORK;
while (true) {
if (this.out_queue.isEmpty() == false) {
this.sendCommand();
}
try {
String command = this.inStream.readLine();
Input in = null;
if (command.startsWith("input:")) {
in = new Input();
command = command.replace("input:", "").replace(";", "");
String[] parts = command.split(",");
in.playerID = Integer.valueOf(parts[0]);
in.type = NetworkInputType.valueOf(parts[1]);
if ((in.type == NetworkInputType.PLAYER) || (in.type == NetworkInputType.BOMB)) {
in.x = Integer.valueOf(parts[2]);
in.y = Integer.valueOf(parts[3]);
}
if (in.type == NetworkInputType.BOMB) {
Game.entities.add(new Bomb(in.x, in.y, in.playerID));
Debug.log(Debug.VERBOSE, "Bomb received");
} else if (in.type == NetworkInputType.PLAYER) {
Player p = (Player) Game.players.get(in.playerID);
p.setPosition(in.x, in.y);
Debug.log(Debug.VERBOSE, "Got new player position");
}
} else if (command.startsWith("me:")) {
this.playerID = Integer.valueOf(command.replace("me:", "").replace(";", ""));
Debug.log(Debug.VERBOSE, "PlayerID: " + this.playerID);
} else if (command.startsWith("m:")) {
String mapname = command.replace("m:", "").replace(";", "");
// Game.key_settings = new ArrayList<KeySettings>();
Game.getInstance().init(mapname);
ArrayList<Point> spawns = new Loader().getSpawnPoints(mapname);
for (int i = 0; i < spawns.size(); i++) {
+ KeySettings keys;
+ Player p;
Point po = spawns.get(i);
if (i == this.playerID) {
/*
* KeySettings s1 = new KeySettings(); s1.bomb =
* Game.keys.bomb; s1.left = Game.keys.left;
* s1.right = Game.keys.right; s1.up = Game.keys.up;
* s1.down = Game.keys.down;
* Game.key_settings.add(s1);
*/
- Player p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
- KeySettings keys = Game.getKeySettings(0);
+ p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
+ keys = Game.getKeySettings(0);
p.setKeys(keys);
- Game.players.add(p);
} else {
- NetworkPlayerKeys keys = new NetworkPlayerKeys(i);
- Player p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
+ keys = new NetworkPlayerKeys(i);
+ p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
p.setKeys(keys);
- Game.players.add(p);
}
+ p.setKeys(keys);
+ Game.players.add(p);
+ Game.entities.add(p);
}
}
if (in != null) {
this.in_queue.add(in);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void sendCommand() {
for (Input in : this.out_queue) {
try {
this.outStream.write(("input:" + this.playerID + "," + in.type + "," + in.x + "," + in.y + ";\n")
.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void send(Input in) {
this.out_queue.add(in);
}
}
| false | true | public void run() {
Game.gamemode = Gamemode.NETWORK;
while (true) {
if (this.out_queue.isEmpty() == false) {
this.sendCommand();
}
try {
String command = this.inStream.readLine();
Input in = null;
if (command.startsWith("input:")) {
in = new Input();
command = command.replace("input:", "").replace(";", "");
String[] parts = command.split(",");
in.playerID = Integer.valueOf(parts[0]);
in.type = NetworkInputType.valueOf(parts[1]);
if ((in.type == NetworkInputType.PLAYER) || (in.type == NetworkInputType.BOMB)) {
in.x = Integer.valueOf(parts[2]);
in.y = Integer.valueOf(parts[3]);
}
if (in.type == NetworkInputType.BOMB) {
Game.entities.add(new Bomb(in.x, in.y, in.playerID));
Debug.log(Debug.VERBOSE, "Bomb received");
} else if (in.type == NetworkInputType.PLAYER) {
Player p = (Player) Game.players.get(in.playerID);
p.setPosition(in.x, in.y);
Debug.log(Debug.VERBOSE, "Got new player position");
}
} else if (command.startsWith("me:")) {
this.playerID = Integer.valueOf(command.replace("me:", "").replace(";", ""));
Debug.log(Debug.VERBOSE, "PlayerID: " + this.playerID);
} else if (command.startsWith("m:")) {
String mapname = command.replace("m:", "").replace(";", "");
// Game.key_settings = new ArrayList<KeySettings>();
Game.getInstance().init(mapname);
ArrayList<Point> spawns = new Loader().getSpawnPoints(mapname);
for (int i = 0; i < spawns.size(); i++) {
Point po = spawns.get(i);
if (i == this.playerID) {
/*
* KeySettings s1 = new KeySettings(); s1.bomb =
* Game.keys.bomb; s1.left = Game.keys.left;
* s1.right = Game.keys.right; s1.up = Game.keys.up;
* s1.down = Game.keys.down;
* Game.key_settings.add(s1);
*/
Player p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
KeySettings keys = Game.getKeySettings(0);
p.setKeys(keys);
Game.players.add(p);
} else {
NetworkPlayerKeys keys = new NetworkPlayerKeys(i);
Player p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
p.setKeys(keys);
Game.players.add(p);
}
}
}
if (in != null) {
this.in_queue.add(in);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| public void run() {
Game.gamemode = Gamemode.NETWORK;
while (true) {
if (this.out_queue.isEmpty() == false) {
this.sendCommand();
}
try {
String command = this.inStream.readLine();
Input in = null;
if (command.startsWith("input:")) {
in = new Input();
command = command.replace("input:", "").replace(";", "");
String[] parts = command.split(",");
in.playerID = Integer.valueOf(parts[0]);
in.type = NetworkInputType.valueOf(parts[1]);
if ((in.type == NetworkInputType.PLAYER) || (in.type == NetworkInputType.BOMB)) {
in.x = Integer.valueOf(parts[2]);
in.y = Integer.valueOf(parts[3]);
}
if (in.type == NetworkInputType.BOMB) {
Game.entities.add(new Bomb(in.x, in.y, in.playerID));
Debug.log(Debug.VERBOSE, "Bomb received");
} else if (in.type == NetworkInputType.PLAYER) {
Player p = (Player) Game.players.get(in.playerID);
p.setPosition(in.x, in.y);
Debug.log(Debug.VERBOSE, "Got new player position");
}
} else if (command.startsWith("me:")) {
this.playerID = Integer.valueOf(command.replace("me:", "").replace(";", ""));
Debug.log(Debug.VERBOSE, "PlayerID: " + this.playerID);
} else if (command.startsWith("m:")) {
String mapname = command.replace("m:", "").replace(";", "");
// Game.key_settings = new ArrayList<KeySettings>();
Game.getInstance().init(mapname);
ArrayList<Point> spawns = new Loader().getSpawnPoints(mapname);
for (int i = 0; i < spawns.size(); i++) {
KeySettings keys;
Player p;
Point po = spawns.get(i);
if (i == this.playerID) {
/*
* KeySettings s1 = new KeySettings(); s1.bomb =
* Game.keys.bomb; s1.left = Game.keys.left;
* s1.right = Game.keys.right; s1.up = Game.keys.up;
* s1.down = Game.keys.down;
* Game.key_settings.add(s1);
*/
p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
keys = Game.getKeySettings(0);
p.setKeys(keys);
} else {
keys = new NetworkPlayerKeys(i);
p = new Player(po.x * Game.BLOCK_SIZE, po.y * Game.BLOCK_SIZE);
p.setKeys(keys);
}
p.setKeys(keys);
Game.players.add(p);
Game.entities.add(p);
}
}
if (in != null) {
this.in_queue.add(in);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/org.spearce.jgit/src/org/spearce/jgit/lib/WindowCache.java b/org.spearce.jgit/src/org/spearce/jgit/lib/WindowCache.java
index c5f5b604..b1265cb2 100644
--- a/org.spearce.jgit/src/org/spearce/jgit/lib/WindowCache.java
+++ b/org.spearce.jgit/src/org/spearce/jgit/lib/WindowCache.java
@@ -1,261 +1,262 @@
/*
* Copyright (C) 2006 Shawn Pearce <spearce@spearce.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License, version 2, as published by the Free Software Foundation.
*
* This 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*/
package org.spearce.jgit.lib;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.util.zip.Inflater;
/**
* The WindowCache manages reusable <code>Windows</code> and inflaters used by
* the other windowed file access classes.
*/
public class WindowCache {
private static final int bits(int sz) {
if (sz < 4096)
throw new IllegalArgumentException("Invalid window size");
if (Integer.bitCount(sz) != 1)
throw new IllegalArgumentException("Window size must be power of 2");
return Integer.numberOfTrailingZeros(sz);
}
private final Inflater[] inflaterCache;
private final int maxByteCount;
final int sz;
final int szb;
final int szm;
final boolean mmap;
final ReferenceQueue<?> clearedWindowQueue;
final UnpackedObjectCache deltaBaseCache;
private final ByteWindow[] windows;
private int openWindowCount;
private int openByteCount;
private int openInflaterCount;
private int accessClock;
/**
* Create a new window cache, using configured values.
*
* @param cfg
* repository (or global user) configuration to control the
* cache. If cache parameters are not specified by the given
* configuration they will use default values.
*/
public WindowCache(final RepositoryConfig cfg) {
maxByteCount = cfg.getCore().getPackedGitLimit();
szb = bits(cfg.getCore().getPackedGitWindowSize());
sz = 1 << szb;
szm = (1 << szb) - 1;
mmap = cfg.getCore().isPackedGitMMAP();
windows = new ByteWindow[maxByteCount / sz];
inflaterCache = new Inflater[4];
clearedWindowQueue = new ReferenceQueue<Object>();
deltaBaseCache = new UnpackedObjectCache(cfg);
}
synchronized Inflater borrowInflater() {
if (openInflaterCount > 0) {
final Inflater r = inflaterCache[--openInflaterCount];
inflaterCache[openInflaterCount] = null;
return r;
}
return new Inflater(false);
}
synchronized void returnInflater(final Inflater i) {
if (openInflaterCount == inflaterCache.length)
i.end();
else
inflaterCache[openInflaterCount++] = i;
}
/**
* Get a specific window.
*
* @param curs
* an active cursor object to maintain the window reference while
* the caller needs it.
* @param wp
* the provider of the window. If the window is not currently in
* the cache then the provider will be asked to load it.
* @param id
* the id, unique only within the scope of the specific provider
* <code>wp</code>. Typically this id is the byte offset
* within the file divided by the window size, but its meaning is
* left open to the provider.
* @throws IOException
* the window was not found in the cache and the given provider
* was unable to load the window on demand.
*/
public synchronized final void get(final WindowCursor curs,
final WindowedFile wp, final int id) throws IOException {
int idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
if (++wp.openCount == 1) {
try {
wp.cacheOpen();
} catch (IOException ioe) {
wp.openCount = 0;
throw ioe;
} catch (RuntimeException ioe) {
wp.openCount = 0;
throw ioe;
} catch (Error ioe) {
wp.openCount = 0;
throw ioe;
}
// The cacheOpen may have mapped the window we are trying to
// map ourselves. Retrying the search ensures that does not
// happen to us.
//
idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
}
idx = -(idx + 1);
for (;;) {
final ByteWindow<?> w = (ByteWindow<?>) clearedWindowQueue.poll();
if (w == null)
break;
final int oldest = binarySearch(w.provider,w.id);
if (oldest < 0 || windows[oldest] != w)
continue; // Must have been evicted by our other controls.
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
if (oldest < idx)
idx--;
}
final int wSz = wp.getWindowSize(id);
while (openWindowCount == windows.length
|| (openWindowCount > 0 && openByteCount + wSz > maxByteCount)) {
int oldest = 0;
for (int k = openWindowCount - 1; k > 0; k--) {
if (windows[k].lastAccessed < windows[oldest].lastAccessed)
oldest = k;
}
final ByteWindow w = windows[oldest];
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
w.enqueue();
if (oldest < idx)
idx--;
}
+ if (idx < 0)
+ idx = 0;
final int toMove = openWindowCount - idx;
if (toMove > 0)
System.arraycopy(windows, idx, windows, idx + 1, toMove);
wp.loadWindow(curs, id);
windows[idx] = curs.window;
openWindowCount++;
openByteCount += curs.window.size;
- return;
}
private final int binarySearch(final WindowedFile sprov, final int sid) {
if (openWindowCount == 0)
return -1;
final int shc = sprov.hash;
int high = openWindowCount;
int low = 0;
do {
final int mid = (low + high) / 2;
final ByteWindow mw = windows[mid];
if (mw.provider == sprov && mw.id == sid)
return mid;
final int mhc = mw.provider.hash;
if (mhc < shc || (shc == mhc && mw.id < sid))
low = mid + 1;
else
high = mid;
} while (low < high);
return -(low + 1);
}
/**
* Remove all windows associated with a specific provider.
* <p>
* Providers should invoke this method as part of their cleanup/close
* routines, ensuring that the window cache releases all windows that cannot
* ever be requested again.
* </p>
*
* @param wp
* the window provider whose windows should be removed from the
* cache.
*/
public synchronized final void purge(final WindowedFile wp) {
int d = 0;
for (int s = 0; s < openWindowCount; s++) {
final ByteWindow win = windows[s];
if (win.provider != wp)
windows[d++] = win;
else
openByteCount -= win.size;
}
openWindowCount = d;
if (wp.openCount > 0) {
wp.openCount = 0;
wp.cacheClose();
}
}
}
| false | true | public synchronized final void get(final WindowCursor curs,
final WindowedFile wp, final int id) throws IOException {
int idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
if (++wp.openCount == 1) {
try {
wp.cacheOpen();
} catch (IOException ioe) {
wp.openCount = 0;
throw ioe;
} catch (RuntimeException ioe) {
wp.openCount = 0;
throw ioe;
} catch (Error ioe) {
wp.openCount = 0;
throw ioe;
}
// The cacheOpen may have mapped the window we are trying to
// map ourselves. Retrying the search ensures that does not
// happen to us.
//
idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
}
idx = -(idx + 1);
for (;;) {
final ByteWindow<?> w = (ByteWindow<?>) clearedWindowQueue.poll();
if (w == null)
break;
final int oldest = binarySearch(w.provider,w.id);
if (oldest < 0 || windows[oldest] != w)
continue; // Must have been evicted by our other controls.
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
if (oldest < idx)
idx--;
}
final int wSz = wp.getWindowSize(id);
while (openWindowCount == windows.length
|| (openWindowCount > 0 && openByteCount + wSz > maxByteCount)) {
int oldest = 0;
for (int k = openWindowCount - 1; k > 0; k--) {
if (windows[k].lastAccessed < windows[oldest].lastAccessed)
oldest = k;
}
final ByteWindow w = windows[oldest];
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
w.enqueue();
if (oldest < idx)
idx--;
}
final int toMove = openWindowCount - idx;
if (toMove > 0)
System.arraycopy(windows, idx, windows, idx + 1, toMove);
wp.loadWindow(curs, id);
windows[idx] = curs.window;
openWindowCount++;
openByteCount += curs.window.size;
return;
}
| public synchronized final void get(final WindowCursor curs,
final WindowedFile wp, final int id) throws IOException {
int idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
if (++wp.openCount == 1) {
try {
wp.cacheOpen();
} catch (IOException ioe) {
wp.openCount = 0;
throw ioe;
} catch (RuntimeException ioe) {
wp.openCount = 0;
throw ioe;
} catch (Error ioe) {
wp.openCount = 0;
throw ioe;
}
// The cacheOpen may have mapped the window we are trying to
// map ourselves. Retrying the search ensures that does not
// happen to us.
//
idx = binarySearch(wp, id);
if (0 <= idx) {
final ByteWindow<?> w = windows[idx];
if ((curs.handle = w.get()) != null) {
w.lastAccessed = ++accessClock;
curs.window = w;
return;
}
}
}
idx = -(idx + 1);
for (;;) {
final ByteWindow<?> w = (ByteWindow<?>) clearedWindowQueue.poll();
if (w == null)
break;
final int oldest = binarySearch(w.provider,w.id);
if (oldest < 0 || windows[oldest] != w)
continue; // Must have been evicted by our other controls.
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
if (oldest < idx)
idx--;
}
final int wSz = wp.getWindowSize(id);
while (openWindowCount == windows.length
|| (openWindowCount > 0 && openByteCount + wSz > maxByteCount)) {
int oldest = 0;
for (int k = openWindowCount - 1; k > 0; k--) {
if (windows[k].lastAccessed < windows[oldest].lastAccessed)
oldest = k;
}
final ByteWindow w = windows[oldest];
final WindowedFile p = w.provider;
if (--p.openCount == 0 && p != wp)
p.cacheClose();
openByteCount -= w.size;
final int toMove = openWindowCount - oldest - 1;
if (toMove > 0)
System.arraycopy(windows, oldest + 1, windows, oldest, toMove);
windows[--openWindowCount] = null;
w.enqueue();
if (oldest < idx)
idx--;
}
if (idx < 0)
idx = 0;
final int toMove = openWindowCount - idx;
if (toMove > 0)
System.arraycopy(windows, idx, windows, idx + 1, toMove);
wp.loadWindow(curs, id);
windows[idx] = curs.window;
openWindowCount++;
openByteCount += curs.window.size;
}
|
diff --git a/sample-chat-jc/src/main/java/pl/bristleback/sample/chat/web/config/BristlebackServletConfig.java b/sample-chat-jc/src/main/java/pl/bristleback/sample/chat/web/config/BristlebackServletConfig.java
index 541da9a..ceec87f 100644
--- a/sample-chat-jc/src/main/java/pl/bristleback/sample/chat/web/config/BristlebackServletConfig.java
+++ b/sample-chat-jc/src/main/java/pl/bristleback/sample/chat/web/config/BristlebackServletConfig.java
@@ -1,75 +1,75 @@
package pl.bristleback.sample.chat.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import pl.bristleback.sample.chat.user.ChatUser;
import pl.bristleback.server.bristle.api.users.UserContext;
import pl.bristleback.server.bristle.conf.resolver.init.PojoConfigResolver;
import pl.bristleback.server.bristle.engine.servlet.BristlebackHttpHandler;
import java.util.HashMap;
import java.util.Map;
/**
* Configuration class for annotation application context.
*
* @author Tom-Steve Watzke
* @see pl.bristleback.server.bristle.conf.namespace.BristlebackServletBeanDefinitionParser
*/
@Configuration
@Profile("servlet")
@Import(BristlebackServerMessagesConfig.class)
public class BristlebackServletConfig {
/**
* Servlet engine to be used.
*/
private final static String ENGINE_NAME = "system.engine.tomcat.servlet";
/**
* Logging level for debugging using Log4J.
*/
private final static String LOGGING_LEVEL = "org.apache.log4j.Level.DEBUG";
/**
* User context class
*/
private final static Class<? extends UserContext> USER_CONTEXT = ChatUser.class;
/**
* Default: "**\/*" (without "\")
*/
private final static String SERVLET_MAPPING = "/websocket";
@Bean
public PojoConfigResolver initialConfigurationResolver() {
PojoConfigResolver configResolver = new PojoConfigResolver();
configResolver.setEngineName(ENGINE_NAME);
configResolver.setLoggingLevel(LOGGING_LEVEL);
configResolver.setUserContextClass(USER_CONTEXT);
return configResolver;
}
@Bean
public SimpleUrlHandlerMapping bristlebackHandlerMappings() {
- Map<String, BristlebackHttpHandler> mappings = new HashMap<>();
+ Map<String, BristlebackHttpHandler> mappings = new HashMap<String, BristlebackHttpHandler>();
mappings.put(SERVLET_MAPPING, bristlebackHttpHandler());
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setUrlMap(mappings);
return handlerMapping;
}
@Bean
public BristlebackHttpHandler bristlebackHttpHandler() {
BristlebackHttpHandler httpHandler = new BristlebackHttpHandler();
httpHandler.setInitialConfigurationResolver(initialConfigurationResolver());
return httpHandler;
}
}
| true | true | public SimpleUrlHandlerMapping bristlebackHandlerMappings() {
Map<String, BristlebackHttpHandler> mappings = new HashMap<>();
mappings.put(SERVLET_MAPPING, bristlebackHttpHandler());
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setUrlMap(mappings);
return handlerMapping;
}
| public SimpleUrlHandlerMapping bristlebackHandlerMappings() {
Map<String, BristlebackHttpHandler> mappings = new HashMap<String, BristlebackHttpHandler>();
mappings.put(SERVLET_MAPPING, bristlebackHttpHandler());
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setUrlMap(mappings);
return handlerMapping;
}
|
diff --git a/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java b/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java
index a1684f3..af9d119 100644
--- a/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java
+++ b/src/main/java/com/asascience/ncsos/cdmclasses/CDMUtils.java
@@ -1,217 +1,217 @@
package com.asascience.ncsos.cdmclasses;
import com.asascience.ncsos.getobs.ObservationOffering;
import java.util.ArrayList;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Class for common util functions that are used across the CDM classes
* @author abird
* @version 1.0.0
*/
public class CDMUtils {
/**
* Add the offering to the get caps document
* @param offering
* @param document
* @return
*/
public static Document addObsOfferingToDoc(ObservationOffering offering,Document document ) {
NodeList obsOfferingList = document.getElementsByTagName("ObservationOfferingList");
Element obsOfferEl = (Element) obsOfferingList.item(0);
obsOfferEl.appendChild(constructObsOfferingNodes(offering,document));
offering = null;
return document;
}
/**
* constructs the node to be added to the document
* @param offering
* @param document
* @return
*/
public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) {
//Create the observation offering
Element obsOfferingEl = document.createElement("ObservationOffering");
//add the station ID to the created element
obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID());
//create the description and add the offering info
Element obsOfferingDescripEl = document.createElement("gml:description");
obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription()));
//create the obs name and add it to the element
Element obsOfferingNameEl = document.createElement("gml:name");
obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName()));
//create the source name el and add data
Element obsOfferingSrsNameEl = document.createElement("gml:srsName");
obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName()));
//create bounded area node
Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy");
// create the envelope node and add attribute srs name
Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope");
obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName());
//create the lower coner node
Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner");
obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner()));
//create the upper corner node
Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner");
obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner()));
//add the upper and lower to the envelope node
obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl);
obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl);
//add the envelope node to the bounded by node
obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl);
//create time node
Element obsOfferingTimeEl = document.createElement("time");
//create time period node
Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod");
//create begin position node
Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition");
obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin()));
//create end position node
Element obsOfferingTimeEndEl = document.createElement("gml:endPosition");
checkEndDateElementNode(offering, obsOfferingTimeEndEl,document);
//add time begin to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl);
//add time end to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl);
//add time period to time
obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl);
//create procedure node and add element
Element obsOfferingProcedureEl = document.createElement("procedure");
obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink());
//create feature of interest node and add element
Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest");
obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest());
//create response format(s)
- ArrayList<Element> responseFormats = createResponseFormatNode(document);
- if (responseFormats == null) {
- System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'");
- }
+// ArrayList<Element> responseFormats = createResponseFormatNode(document);
+// if (responseFormats == null) {
+// System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'");
+// }
//create response model
Element obsOfferingModelEl = document.createElement("responseModel");
obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel()));
//create response model
Element obsOfferingModeEl = document.createElement("responseMode");
obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode()));
//add the new elements to the XML doc
obsOfferingEl.appendChild(obsOfferingDescripEl);
obsOfferingEl.appendChild(obsOfferingNameEl);
obsOfferingEl.appendChild(obsOfferingSrsNameEl);
obsOfferingEl.appendChild(obsOfferingBoundedByEl);
obsOfferingEl.appendChild(obsOfferingTimeEl);
obsOfferingEl.appendChild(obsOfferingProcedureEl);
//create obs property node and add element
for (int i = 0; i < offering.getObservationObserveredList().size(); i++) {
Element obsOfferingObsPropertyEll = document.createElement("observedProperty");
obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i));
obsOfferingEl.appendChild(obsOfferingObsPropertyEll);
}
obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl);
// add our response formats
- for (Element elem : responseFormats) {
- obsOfferingEl.appendChild(elem);
- }
+// for (Element elem : responseFormats) {
+// obsOfferingEl.appendChild(elem);
+// }
obsOfferingEl.appendChild(obsOfferingModelEl);
obsOfferingEl.appendChild(obsOfferingModeEl);
return obsOfferingEl;
}
/**
* Checks the end node for an end date
* @param offering
* @param obsOfferingTimeEndEl
* @param document
* @throws DOMException
*/
private static void checkEndDateElementNode(ObservationOffering offering, Element obsOfferingTimeEndEl,Document document) throws DOMException {
//check the string to see if it either needs attribute of element
if ((offering.getObservationTimeEnd().isEmpty()) || (offering.getObservationTimeEnd().length() < 2) || (offering.getObservationTimeEnd().contentEquals(""))) {
obsOfferingTimeEndEl.setAttribute("indeterminatePosition", "unknown");
} else {
obsOfferingTimeEndEl.appendChild(document.createTextNode(offering.getObservationTimeEnd()));
}
}
/**
* Creates the response format nodes for each format contained inside the sosGetCapabilities.xml template
* @param doc the xml document which holds the get capabilities response
* @return node list of each responseFormat node
*/
private static ArrayList<Element> createResponseFormatNode(Document doc) {
ArrayList<Element> retval = null;
// get a list of the response formats
NodeList nodeList = doc.getElementsByTagName("ows:Operation");
Element getObservation = null;
for (int i=0; i<nodeList.getLength(); i++) {
if ("GetObservation".equals(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue())) {
getObservation = (Element) nodeList.item(i);
break;
}
}
if (getObservation == null) {
System.out.println("Could not find GetObservation! node");
return retval;
}
// now get our "response format" node
nodeList = getObservation.getElementsByTagName("ows:Parameter");
Element responseFormat = null;
for (int j=0; j<nodeList.getLength(); j++) {
if("responseFormat".equals(nodeList.item(j).getAttributes().getNamedItem("name").getNodeValue())) {
responseFormat = (Element) nodeList.item(j);
break;
}
}
if (responseFormat == null) {
System.out.println("Could not find responseFormat node");
return retval;
}
// now get all of our values
nodeList = responseFormat.getElementsByTagName("ows:AllowedValues");
if (nodeList == null) {
System.out.println("Could not find ows:AllowedValues");
return retval;
}
nodeList = ((Element) nodeList.item(0)).getElementsByTagName("ows:Value");
if (nodeList == null) {
System.out.println("Could not find ows:Value(s)");
return retval;
}
// create our array list and populate it with the node list
retval = new ArrayList<Element>(nodeList.getLength());
Element respForm = null;
for (int k=0; k<nodeList.getLength(); k++) {
respForm = doc.createElement("responseFormat");
respForm.setTextContent(((Element) nodeList.item(k)).getTextContent());
retval.add(respForm);
}
return retval;
}
}
| false | true | public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) {
//Create the observation offering
Element obsOfferingEl = document.createElement("ObservationOffering");
//add the station ID to the created element
obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID());
//create the description and add the offering info
Element obsOfferingDescripEl = document.createElement("gml:description");
obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription()));
//create the obs name and add it to the element
Element obsOfferingNameEl = document.createElement("gml:name");
obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName()));
//create the source name el and add data
Element obsOfferingSrsNameEl = document.createElement("gml:srsName");
obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName()));
//create bounded area node
Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy");
// create the envelope node and add attribute srs name
Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope");
obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName());
//create the lower coner node
Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner");
obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner()));
//create the upper corner node
Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner");
obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner()));
//add the upper and lower to the envelope node
obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl);
obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl);
//add the envelope node to the bounded by node
obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl);
//create time node
Element obsOfferingTimeEl = document.createElement("time");
//create time period node
Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod");
//create begin position node
Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition");
obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin()));
//create end position node
Element obsOfferingTimeEndEl = document.createElement("gml:endPosition");
checkEndDateElementNode(offering, obsOfferingTimeEndEl,document);
//add time begin to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl);
//add time end to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl);
//add time period to time
obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl);
//create procedure node and add element
Element obsOfferingProcedureEl = document.createElement("procedure");
obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink());
//create feature of interest node and add element
Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest");
obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest());
//create response format(s)
ArrayList<Element> responseFormats = createResponseFormatNode(document);
if (responseFormats == null) {
System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'");
}
//create response model
Element obsOfferingModelEl = document.createElement("responseModel");
obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel()));
//create response model
Element obsOfferingModeEl = document.createElement("responseMode");
obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode()));
//add the new elements to the XML doc
obsOfferingEl.appendChild(obsOfferingDescripEl);
obsOfferingEl.appendChild(obsOfferingNameEl);
obsOfferingEl.appendChild(obsOfferingSrsNameEl);
obsOfferingEl.appendChild(obsOfferingBoundedByEl);
obsOfferingEl.appendChild(obsOfferingTimeEl);
obsOfferingEl.appendChild(obsOfferingProcedureEl);
//create obs property node and add element
for (int i = 0; i < offering.getObservationObserveredList().size(); i++) {
Element obsOfferingObsPropertyEll = document.createElement("observedProperty");
obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i));
obsOfferingEl.appendChild(obsOfferingObsPropertyEll);
}
obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl);
// add our response formats
for (Element elem : responseFormats) {
obsOfferingEl.appendChild(elem);
}
obsOfferingEl.appendChild(obsOfferingModelEl);
obsOfferingEl.appendChild(obsOfferingModeEl);
return obsOfferingEl;
}
| public static Element constructObsOfferingNodes(ObservationOffering offering,Document document) {
//Create the observation offering
Element obsOfferingEl = document.createElement("ObservationOffering");
//add the station ID to the created element
obsOfferingEl.setAttribute("gml:id", offering.getObservationStationID());
//create the description and add the offering info
Element obsOfferingDescripEl = document.createElement("gml:description");
obsOfferingDescripEl.appendChild(document.createTextNode(offering.getObservationStationDescription()));
//create the obs name and add it to the element
Element obsOfferingNameEl = document.createElement("gml:name");
obsOfferingNameEl.appendChild(document.createTextNode(offering.getObservationName()));
//create the source name el and add data
Element obsOfferingSrsNameEl = document.createElement("gml:srsName");
obsOfferingSrsNameEl.appendChild(document.createTextNode(offering.getObservationSrsName()));
//create bounded area node
Element obsOfferingBoundedByEl = document.createElement("gml:boundedBy");
// create the envelope node and add attribute srs name
Element obsOfferingEnvelopeEl = document.createElement("gml:Envelope");
obsOfferingEnvelopeEl.setAttribute("srsName", offering.getObservationSrsName());
//create the lower coner node
Element obsOfferinglowerCornerEl = document.createElement("gml:lowerCorner");
obsOfferinglowerCornerEl.appendChild(document.createTextNode(offering.getObservationStationLowerCorner()));
//create the upper corner node
Element obsOfferingUpperCornerEl = document.createElement("gml:upperCorner");
obsOfferingUpperCornerEl.appendChild(document.createTextNode(offering.getObservationStationUpperCorner()));
//add the upper and lower to the envelope node
obsOfferingEnvelopeEl.appendChild(obsOfferinglowerCornerEl);
obsOfferingEnvelopeEl.appendChild(obsOfferingUpperCornerEl);
//add the envelope node to the bounded by node
obsOfferingBoundedByEl.appendChild(obsOfferingEnvelopeEl);
//create time node
Element obsOfferingTimeEl = document.createElement("time");
//create time period node
Element obsOfferingTimePeriodEl = document.createElement("gml:TimePeriod");
//create begin position node
Element obsOfferingTimeBeginEl = document.createElement("gml:beginPosition");
obsOfferingTimeBeginEl.appendChild(document.createTextNode(offering.getObservationTimeBegin()));
//create end position node
Element obsOfferingTimeEndEl = document.createElement("gml:endPosition");
checkEndDateElementNode(offering, obsOfferingTimeEndEl,document);
//add time begin to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeBeginEl);
//add time end to time period
obsOfferingTimePeriodEl.appendChild(obsOfferingTimeEndEl);
//add time period to time
obsOfferingTimeEl.appendChild(obsOfferingTimePeriodEl);
//create procedure node and add element
Element obsOfferingProcedureEl = document.createElement("procedure");
obsOfferingProcedureEl.setAttribute("xlink:href", offering.getObservationProcedureLink());
//create feature of interest node and add element
Element obsOfferingFeatureOfInterestEl = document.createElement("featureOfInterest");
obsOfferingFeatureOfInterestEl.setAttribute("xlink:href", offering.getObservationFeatureOfInterest());
//create response format(s)
// ArrayList<Element> responseFormats = createResponseFormatNode(document);
// if (responseFormats == null) {
// System.out.println("Could not find responseFormat in ows:Operation 'GetObservation'");
// }
//create response model
Element obsOfferingModelEl = document.createElement("responseModel");
obsOfferingModelEl.appendChild(document.createTextNode(offering.getObservationModel()));
//create response model
Element obsOfferingModeEl = document.createElement("responseMode");
obsOfferingModeEl.appendChild(document.createTextNode(offering.getObservationResponseMode()));
//add the new elements to the XML doc
obsOfferingEl.appendChild(obsOfferingDescripEl);
obsOfferingEl.appendChild(obsOfferingNameEl);
obsOfferingEl.appendChild(obsOfferingSrsNameEl);
obsOfferingEl.appendChild(obsOfferingBoundedByEl);
obsOfferingEl.appendChild(obsOfferingTimeEl);
obsOfferingEl.appendChild(obsOfferingProcedureEl);
//create obs property node and add element
for (int i = 0; i < offering.getObservationObserveredList().size(); i++) {
Element obsOfferingObsPropertyEll = document.createElement("observedProperty");
obsOfferingObsPropertyEll.setAttribute("xlink:href", (String) offering.getObservationObserveredList().get(i));
obsOfferingEl.appendChild(obsOfferingObsPropertyEll);
}
obsOfferingEl.appendChild(obsOfferingFeatureOfInterestEl);
// add our response formats
// for (Element elem : responseFormats) {
// obsOfferingEl.appendChild(elem);
// }
obsOfferingEl.appendChild(obsOfferingModelEl);
obsOfferingEl.appendChild(obsOfferingModeEl);
return obsOfferingEl;
}
|
diff --git a/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/clientoffline/Network.java b/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/clientoffline/Network.java
index de1bdaab4..daaaceb8b 100644
--- a/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/clientoffline/Network.java
+++ b/branches/5.0.0/Crux/src/core/org/cruxframework/crux/core/clientoffline/Network.java
@@ -1,249 +1,251 @@
/*
* Copyright 2013 cruxframework.org.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.cruxframework.crux.core.clientoffline;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.cruxframework.crux.core.client.collection.FastList;
import org.cruxframework.crux.core.clientoffline.NetworkEvent.Handler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.logging.client.LogConfiguration;
/**
* A Network detection tool.
* @author Thiago da Rosa de Bustamante
*
*/
public class Network implements HasNetworkHandlers
{
private static Logger logger = Logger.getLogger(Network.class.getName());
private static Network instance;
private Impl impl;
public static abstract class Impl implements HasNetworkHandlers
{
private OfflineMessages messages = GWT.create(OfflineMessages.class);
protected FastList<Handler> handlers = new FastList<NetworkEvent.Handler>();
public HandlerRegistration addNetworkHandler(final Handler handler)
{
handlers.add(handler);
return new HandlerRegistration()
{
@Override
public void removeHandler()
{
int index = handlers.indexOf(handler);
if (index >= 0)
{
handlers.remove(index);
}
}
};
}
/**
* Check if this browser support Crux offline working.
* @return
*/
public boolean isSupported()
{
return true;
}
protected void fireOnLineEvent()
{
if (LogConfiguration.loggingIsEnabled())
{
logger.log(Level.INFO, messages.networkOnLine());
}
fireEvent(new NetworkEvent(true));
}
protected void fireOffLineEvent()
{
if (LogConfiguration.loggingIsEnabled())
{
logger.log(Level.INFO, messages.networkOffLine());
}
fireEvent(new NetworkEvent(false));
}
public void fireEvent(NetworkEvent event)
{
for (int i = 0; i < handlers.size(); i++)
{
handlers.get(i).onNetworkChanged(event);
}
}
}
public static class SafariImpl extends Impl
{
public SafariImpl()
{
createNetworkEventListeners(this);
}
@Override
public native boolean isOnLine()/*-{
return navigator.onLine;
}-*/;
private native void createNetworkEventListeners(SafariImpl instance)/*-{
$wnd.addEventListener('offline',
function(event) {
instance.@org.cruxframework.crux.core.clientoffline.Network.SafariImpl::fireOffLineEvent()();
}, false);
$wnd.addEventListener('online',
function(event) {
instance.@org.cruxframework.crux.core.clientoffline.Network.SafariImpl::fireOnLineEvent()();
}, false);
}-*/;
}
public static class UnsupportedImpl extends Impl
{
@Override
public boolean isOnLine()
{
throw new UnsupportedOperationException();
}
@Override
public HandlerRegistration addNetworkHandler(Handler handler)
{
throw new UnsupportedOperationException();
};
@Override
public boolean isSupported()
{
return false;
}
}
public static class CacheManifestImpl extends Impl
{
private boolean isOnLine = getInitialState();
public CacheManifestImpl()
{
ApplicationCacheHandler.addApplicationCacheHandler(new ApplicationCacheEvent.Handler()
{
@Override
public void onCacheEvent(ApplicationCacheEvent event)
{
switch (event.getEventType())
{
case onDownloading:
case onUpdateready:
case onNoupdate:
onCacheHitEvent();
break;
case onError:
- onCacheFailedEvent();
+ onCacheFailedEvent();
+ default:
+ break;
}
}
});
ApplicationCacheHandler.updateCache();
}
private native boolean getInitialState()/*-{
if (navigator.onLine){
return true;
}
return false;
}-*/;
@Override
public boolean isOnLine()
{
return isOnLine;
}
private void onCacheHitEvent()
{
boolean oldStatus = isOnLine;
isOnLine = true;
if (!oldStatus)
{
fireOnLineEvent();
}
}
private void onCacheFailedEvent()
{
boolean oldStatus = isOnLine;
isOnLine = false;
if (oldStatus)
{
fireOffLineEvent();
}
}
}
/**
* Singleton constructor
*/
private Network()
{
impl = GWT.create(Impl.class);
}
/**
* Retrieve the Network instance
* @return
*/
public static Network get()
{
if (instance == null)
{
instance = new Network();
}
return instance;
}
/**
* Returns true if the application has network connection
*/
@Override
public boolean isOnLine()
{
return impl.isOnLine();
}
/**
* Add a network events handler
*/
@Override
public HandlerRegistration addNetworkHandler(Handler handler)
{
return impl.addNetworkHandler(handler);
}
/**
* Check if this browser support Crux offLine working.
* @return true if offLine is supported.
*/
public boolean isSupported()
{
return impl.isSupported();
}
}
| true | true | public CacheManifestImpl()
{
ApplicationCacheHandler.addApplicationCacheHandler(new ApplicationCacheEvent.Handler()
{
@Override
public void onCacheEvent(ApplicationCacheEvent event)
{
switch (event.getEventType())
{
case onDownloading:
case onUpdateready:
case onNoupdate:
onCacheHitEvent();
break;
case onError:
onCacheFailedEvent();
}
}
});
ApplicationCacheHandler.updateCache();
}
| public CacheManifestImpl()
{
ApplicationCacheHandler.addApplicationCacheHandler(new ApplicationCacheEvent.Handler()
{
@Override
public void onCacheEvent(ApplicationCacheEvent event)
{
switch (event.getEventType())
{
case onDownloading:
case onUpdateready:
case onNoupdate:
onCacheHitEvent();
break;
case onError:
onCacheFailedEvent();
default:
break;
}
}
});
ApplicationCacheHandler.updateCache();
}
|
diff --git a/src/main/java/com/sk89q/skmcl/minecraft/MinecraftInstall.java b/src/main/java/com/sk89q/skmcl/minecraft/MinecraftInstall.java
index 7458f6e..c7d3f95 100644
--- a/src/main/java/com/sk89q/skmcl/minecraft/MinecraftInstall.java
+++ b/src/main/java/com/sk89q/skmcl/minecraft/MinecraftInstall.java
@@ -1,186 +1,187 @@
/*
* SK's Minecraft Launcher
* Copyright (C) 2010, 2011 Albert Pham <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.skmcl.minecraft;
import com.sk89q.skmcl.application.Instance;
import com.sk89q.skmcl.install.FileResource;
import com.sk89q.skmcl.install.ZipExtract;
import com.sk89q.skmcl.launch.JavaProcessBuilder;
import com.sk89q.skmcl.launch.LaunchContext;
import com.sk89q.skmcl.launch.LaunchedProcess;
import com.sk89q.skmcl.minecraft.model.Library;
import com.sk89q.skmcl.minecraft.model.ReleaseManifest;
import com.sk89q.skmcl.profile.Profile;
import com.sk89q.skmcl.session.Session;
import com.sk89q.skmcl.util.Environment;
import com.sk89q.skmcl.util.Operation;
import com.sk89q.skmcl.util.Platform;
import com.sun.istack.internal.NotNull;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.File;
import java.io.IOException;
import static com.sk89q.skmcl.minecraft.model.Library.Extract;
/**
* An installed version of Minecraft.
*/
@ToString
public class MinecraftInstall implements Instance {
@Getter
private final Profile profile;
@Getter
private final Release version;
@Getter
private final String versionPath;
@Getter
private final Environment environment;
/**
* Create a new instance.
*
* @param profile the profile containing this installation
* @param version the version
* @param environment the environment
*/
public MinecraftInstall(@NotNull final Profile profile,
@NotNull final Release version,
@NotNull final Environment environment) {
this.profile = profile;
this.version = version;
this.environment = environment;
versionPath = String.format("versions/%1$s/%1$s", version.getId());
}
/**
* Get the path to the manifest .json file for this version.
*
* @return the path
*/
public File getManifestPath() {
return new File(getProfile().getContentDir(), versionPath + ".json");
}
/**
* Get the path to the .jar file for this version.
*
* @return the path
*/
public File getJarPath() {
return new File(getProfile().getContentDir(), versionPath + ".jar");
}
/**
* Get the path to shared assets directory.
*
* @return the path
*/
public File getAssetsDir() {
return new File(getProfile().getSharedDir(), "assets");
}
/**
* Get the path to a new temporary directory to store extracted libraries.
*
* <p>The returned directory can be deleted at any point in time.</p>
*
* @return the path
*/
protected File createExtractDir() {
String id = "-natives-" + System.currentTimeMillis();
return new File(getProfile().getContentDir(), versionPath + id);
}
@Override
public Operation getUpdater() {
return new MinecraftUpdater(this);
}
@Override
public LaunchedProcess launch(final LaunchContext context) throws IOException {
Session session = context.getSession();
ObjectMapper mapper = new ObjectMapper();
final File extractDir = createExtractDir();
JavaProcessBuilder builder = new JavaProcessBuilder();
ReleaseManifest manifest = mapper.readValue(
getManifestPath(), ReleaseManifest.class);
String sessionId = session.getSessionId() != null ?
session.getSessionId() : "offline";
// Add libraries to classpath or extract the libraries as necessary
for (Library library : manifest.getLibraries()) {
File path = new File(getProfile().getContentDir(),
"libraries/" + library.getPath(context.getEnvironment()));
if (path.exists()) {
Extract extract = library.getExtract();
if (extract != null) {
ZipExtract zipExtract = new ZipExtract(
new FileResource(path), extractDir);
zipExtract.setExclude(extract.getExclude());
zipExtract.run();
} else {
builder.classPath(path);
}
}
}
// Add arguments for the .jar
String[] args = manifest.getMinecraftArguments().split(" +");
for (String arg : args) {
arg = arg.replace("${version_name}", manifest.getId());
arg = arg.replace("${game_directory}", getProfile().getContentDir().getAbsolutePath());
arg = arg.replace("${game_assets}", getAssetsDir().getAbsolutePath());
arg = arg.replace("${auth_player_name}", session.getUsername());
arg = arg.replace("${auth_username}", session.getUsername());
- arg = arg.replace("${auth_access_token}", session.getAccessToken());
+ arg = arg.replace("${auth_access_token}",
+ session.getAccessToken() != null ? session.getAccessToken() : "?");
arg = arg.replace("${auth_session}", sessionId);
builder.getArgs().add(arg);
}
// Mac OS X arguments
if (getEnvironment().getPlatform() == Platform.MAC_OS_X) {
File icnsPath = new File(getAssetsDir(), "icons/minecraft.icns");
builder.getFlags().add("-Xdock:icon=" + icnsPath.getAbsolutePath());
builder.getFlags().add("-Xdock:name=Minecraft");
}
builder.getFlags().add("-Djava.library.path=" + extractDir.getAbsoluteFile());
builder.classPath(getJarPath());
builder.setMainClass(manifest.getMainClass());
ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand());
processBuilder.directory(getProfile().getContentDir());
Process process = processBuilder.start();
// Return the process
return new LaunchedProcess(process) {
@Override
public void close() throws IOException {
FileUtils.deleteDirectory(extractDir);
}
};
}
}
| true | true | public LaunchedProcess launch(final LaunchContext context) throws IOException {
Session session = context.getSession();
ObjectMapper mapper = new ObjectMapper();
final File extractDir = createExtractDir();
JavaProcessBuilder builder = new JavaProcessBuilder();
ReleaseManifest manifest = mapper.readValue(
getManifestPath(), ReleaseManifest.class);
String sessionId = session.getSessionId() != null ?
session.getSessionId() : "offline";
// Add libraries to classpath or extract the libraries as necessary
for (Library library : manifest.getLibraries()) {
File path = new File(getProfile().getContentDir(),
"libraries/" + library.getPath(context.getEnvironment()));
if (path.exists()) {
Extract extract = library.getExtract();
if (extract != null) {
ZipExtract zipExtract = new ZipExtract(
new FileResource(path), extractDir);
zipExtract.setExclude(extract.getExclude());
zipExtract.run();
} else {
builder.classPath(path);
}
}
}
// Add arguments for the .jar
String[] args = manifest.getMinecraftArguments().split(" +");
for (String arg : args) {
arg = arg.replace("${version_name}", manifest.getId());
arg = arg.replace("${game_directory}", getProfile().getContentDir().getAbsolutePath());
arg = arg.replace("${game_assets}", getAssetsDir().getAbsolutePath());
arg = arg.replace("${auth_player_name}", session.getUsername());
arg = arg.replace("${auth_username}", session.getUsername());
arg = arg.replace("${auth_access_token}", session.getAccessToken());
arg = arg.replace("${auth_session}", sessionId);
builder.getArgs().add(arg);
}
// Mac OS X arguments
if (getEnvironment().getPlatform() == Platform.MAC_OS_X) {
File icnsPath = new File(getAssetsDir(), "icons/minecraft.icns");
builder.getFlags().add("-Xdock:icon=" + icnsPath.getAbsolutePath());
builder.getFlags().add("-Xdock:name=Minecraft");
}
builder.getFlags().add("-Djava.library.path=" + extractDir.getAbsoluteFile());
builder.classPath(getJarPath());
builder.setMainClass(manifest.getMainClass());
ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand());
processBuilder.directory(getProfile().getContentDir());
Process process = processBuilder.start();
// Return the process
return new LaunchedProcess(process) {
@Override
public void close() throws IOException {
FileUtils.deleteDirectory(extractDir);
}
};
}
| public LaunchedProcess launch(final LaunchContext context) throws IOException {
Session session = context.getSession();
ObjectMapper mapper = new ObjectMapper();
final File extractDir = createExtractDir();
JavaProcessBuilder builder = new JavaProcessBuilder();
ReleaseManifest manifest = mapper.readValue(
getManifestPath(), ReleaseManifest.class);
String sessionId = session.getSessionId() != null ?
session.getSessionId() : "offline";
// Add libraries to classpath or extract the libraries as necessary
for (Library library : manifest.getLibraries()) {
File path = new File(getProfile().getContentDir(),
"libraries/" + library.getPath(context.getEnvironment()));
if (path.exists()) {
Extract extract = library.getExtract();
if (extract != null) {
ZipExtract zipExtract = new ZipExtract(
new FileResource(path), extractDir);
zipExtract.setExclude(extract.getExclude());
zipExtract.run();
} else {
builder.classPath(path);
}
}
}
// Add arguments for the .jar
String[] args = manifest.getMinecraftArguments().split(" +");
for (String arg : args) {
arg = arg.replace("${version_name}", manifest.getId());
arg = arg.replace("${game_directory}", getProfile().getContentDir().getAbsolutePath());
arg = arg.replace("${game_assets}", getAssetsDir().getAbsolutePath());
arg = arg.replace("${auth_player_name}", session.getUsername());
arg = arg.replace("${auth_username}", session.getUsername());
arg = arg.replace("${auth_access_token}",
session.getAccessToken() != null ? session.getAccessToken() : "?");
arg = arg.replace("${auth_session}", sessionId);
builder.getArgs().add(arg);
}
// Mac OS X arguments
if (getEnvironment().getPlatform() == Platform.MAC_OS_X) {
File icnsPath = new File(getAssetsDir(), "icons/minecraft.icns");
builder.getFlags().add("-Xdock:icon=" + icnsPath.getAbsolutePath());
builder.getFlags().add("-Xdock:name=Minecraft");
}
builder.getFlags().add("-Djava.library.path=" + extractDir.getAbsoluteFile());
builder.classPath(getJarPath());
builder.setMainClass(manifest.getMainClass());
ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand());
processBuilder.directory(getProfile().getContentDir());
Process process = processBuilder.start();
// Return the process
return new LaunchedProcess(process) {
@Override
public void close() throws IOException {
FileUtils.deleteDirectory(extractDir);
}
};
}
|
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/MoveTest.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
index cf5429bdb..db82db256 100644
--- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
+++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/internal/localstore/MoveTest.java
@@ -1,704 +1,705 @@
package org.eclipse.core.tests.internal.localstore;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.internal.resources.*;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
/**
* Tests the move operation.
*/
public class MoveTest extends LocalStoreTest {
public MoveTest() {
super();
}
public MoveTest(String name) {
super(name);
}
public String[] defineHierarchy() {
return new String[] {
"/",
"/file1",
"/file2",
"/folder1/",
"/folder1/file3",
"/folder1/file4",
"/folder2/",
"/folder2/file5",
"/folder2/file6",
"/folder1/folder3/",
"/folder1/folder3/file7",
"/folder1/folder3/file8" };
}
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(new MoveTest("testRenameProjects"));
suite.addTest(new MoveTest("testRenameFolder"));
suite.addTest(new MoveTest("testRenameFile"));
suite.addTest(new MoveTest("testMoveFolderBetweenProjects"));
suite.addTest(new MoveTest("testMoveFileBetweenProjects"));
suite.addTest(new MoveTest("testMoveFolderAcrossVolumes"));
suite.addTest(new MoveTest("testMoveFileAcrossVolumes"));
suite.addTest(new MoveTest("testMoveHierarchy"));
suite.addTest(new MoveTest("testMoveHierarchyBetweenProjects"));
suite.addTest(new MoveTest("testMoveResource"));
return suite;
}
/**
* This test has Windows as the target OS. Drives C: and D: should be available.
*/
public void testMoveFileAcrossVolumes() {
/* test if we are in the adequate environment */
if (!new java.io.File("c:\\").exists() || !new java.io.File("d:\\").exists())
return;
// create common objects
IProject source = getWorkspace().getRoot().getProject("SourceProject");
IProject destination = getWorkspace().getRoot().getProject("DestinationProject");
try {
source.create(getMonitor());
source.open(getMonitor());
IProjectDescription description = getWorkspace().newProjectDescription("DestinationProject");
description.setLocation(new Path("d:/temp/destination"));
destination.create(description, getMonitor());
destination.open(getMonitor());
} catch (CoreException e) {
fail("0.0", e);
}
String fileName = "fileToBeMoved.txt";
IFile file = source.getFile(fileName);
try {
file.create(getRandomContents(), true, getMonitor());
} catch (CoreException e) {
fail("1.0", e);
}
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
try {
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
} catch (CoreException e) {
fail("2.0", e);
}
// move file
IPath dest = destination.getFile(fileName).getFullPath();
try {
file.move(dest, true, getMonitor());
} catch (CoreException e) {
fail("3.0", e);
}
// assert file was moved
IFile newFile = destination.getFile(fileName);
assertDoesNotExistInWorkspace("4.1", file);
assertDoesNotExistInFileSystem("4.2", file);
assertExistsInWorkspace("4.3", newFile);
assertExistsInFileSystem("4.4", newFile);
// assert properties still exist (server, local and session)
try {
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertEquals("5.1", persistentValue, propValues[j]);
assertEquals("5.2", sessionValue, propValues[j]);
}
} catch (CoreException e) {
fail("5.3", e);
}
// remove garbage
try {
source.delete(true, true, getMonitor());
destination.delete(true, true, getMonitor());
} catch (CoreException e) {
fail("20.0", e);
}
}
/**
* Move one file from one project to another.
*/
public void testMoveFileBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// get file instance
String fileName = "newFile.txt";
IFile file = projects[0].getFile(fileName);
ensureExistsInWorkspace(file, true);
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
// move file
IPath destination = projects[1].getFile(fileName).getFullPath();
file.move(destination, true, null);
// get new file instance
IFile newFile = projects[1].getFile(fileName);
// assert file was renamed
assertDoesNotExistInWorkspace(file);
assertDoesNotExistInFileSystem(file);
assertExistsInWorkspace(newFile);
assertExistsInFileSystem(newFile);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* This test has Windows as the target OS. Drives C: and D: should be available.
*/
public void testMoveFolderAcrossVolumes() {
/* test if we are in the adequate environment */
if (!new java.io.File("c:\\").exists() || !new java.io.File("d:\\").exists())
return;
// create common objects
IProject source = getWorkspace().getRoot().getProject("SourceProject");
IProject destination = getWorkspace().getRoot().getProject("DestinationProject");
try {
source.create(getMonitor());
source.open(getMonitor());
IProjectDescription description = getWorkspace().newProjectDescription("DestinationProject");
description.setLocation(new Path("d:/temp/destination"));
destination.create(description, getMonitor());
destination.open(getMonitor());
} catch (CoreException e) {
fail("0.0", e);
}
// get folder instance
String folderName = "folderToBeMoved";
IFolder folder = source.getFolder(folderName);
try {
folder.create(true, true, getMonitor());
} catch (CoreException e) {
fail("1.0", e);
}
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
try {
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
} catch (CoreException e) {
fail("2.0", e);
}
// rename folder
IPath dest = destination.getFile(folderName).getFullPath();
try {
folder.move(dest, true, getMonitor());
} catch (CoreException e) {
fail("3.0", e);
}
// assert folder was renamed
IFolder newFolder = destination.getFolder(folderName);
assertDoesNotExistInWorkspace("4.1", folder);
assertDoesNotExistInFileSystem("4.2", folder);
assertExistsInWorkspace("4.3", newFolder);
assertExistsInFileSystem("4.4", newFolder);
// assert properties still exist (server, local and session)
try {
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertEquals("5.1", persistentValue, propValues[j]);
assertEquals("5.2", sessionValue, propValues[j]);
}
} catch (CoreException e) {
fail("5.3", e);
}
// remove garbage
try {
source.delete(true, true, getMonitor());
destination.delete(true, true, getMonitor());
} catch (CoreException e) {
fail("20.0", e);
}
}
/**
* Move one folder from one project to another.
*/
public void testMoveFolderBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// get folder instance
String folderName = "newFolder";
IFolder folder = projects[0].getFolder(folderName);
ensureExistsInWorkspace(folder, true);
// add some properties to folder (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
// rename folder
IPath destination = projects[1].getFolder(folderName).getFullPath();
folder.move(destination, true, null);
// get new folder instance
IFolder newFolder = projects[1].getFolder(folderName);
// assert folder was renamed
assertDoesNotExistInWorkspace(folder);
assertDoesNotExistInFileSystem(folder);
assertExistsInWorkspace(newFolder);
assertExistsInFileSystem(newFolder);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* Move some hierarchy of folders and files.
*/
public void testMoveHierarchy() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create the source folder
String folderSourceName = "folder source";
IFolder folderSource = projects[0].getFolder(folderSourceName);
ensureExistsInWorkspace(folderSource, true);
// create hierarchy
String[] hierarchy = defineHierarchy();
IResource[] resources = buildResources(folderSource, hierarchy);
ensureExistsInWorkspace(resources, true);
// add some properties to each resource (persistent and session)
String[] propNames = new String[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = "prop" + j;
propValues[j] = "value" + j;
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
QualifiedName propName = new QualifiedName("test", resource.getName() + propNames[j]);
String propValue = resource.getName() + propValues[j];
resource.setPersistentProperty(propName, propValue);
resource.setSessionProperty(propName, propValue);
}
}
// create the destination folder
String folderDestinationName = "folder destination";
IFolder folderDestination = projects[0].getFolder(folderDestinationName);
// move hierarchy
//IProgressMonitor monitor = new LoggingProgressMonitor(System.out);
IProgressMonitor monitor = getMonitor();
folderSource.move(folderDestination.getFullPath(), true, monitor);
// get new hierarchy instance
IResource[] newResources = buildResources(folderDestination, hierarchy);
// assert hierarchy was moved
assertDoesNotExistInWorkspace(resources);
assertDoesNotExistInFileSystem(resources);
assertExistsInWorkspace(newResources);
assertExistsInFileSystem(newResources);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
for (int i = 0; i < newResources.length; i++) {
IResource destResource = newResources[i];
IResource sourceResource = resources[i];
/* The names of the properties will remain the same in both the source and
destination hierarchies. So, be sure to use sourceResource to get the
name or your qualified name will contain 'folder destination' instead of
'folder source' and the property value will be null.
*/
QualifiedName propName = new QualifiedName("test", sourceResource.getName() + propNames[j]);
String propValue = sourceResource.getName() + propValues[j];
String persistentValue = destResource.getPersistentProperty(propName);
Object sessionValue = destResource.getSessionProperty(propName);
assertTrue("persistent property value is not the same", propValue.equals(persistentValue));
assertTrue("session property value is not the same", propValue.equals(sessionValue));
}
}
}
/**
* Move some hierarchy of folders and files between projects. It also test moving a
* hierarchy across volumes.
*/
public void testMoveHierarchyBetweenProjects() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create the source folder
String folderSourceName = "source";
IFolder folderSource = projects[0].getFolder(folderSourceName);
ensureExistsInWorkspace(folderSource, true);
// build hierarchy
String[] hierarchy = defineHierarchy();
IResource[] resources = buildResources(folderSource, hierarchy);
ensureExistsInWorkspace(resources, true);
// add some properties to each resource
String[] propNames = new String[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = "prop" + j;
propValues[j] = "value" + j;
for (int i = 0; i < resources.length; i++) {
IResource resource = resources[i];
QualifiedName propName = new QualifiedName("test", resource.getName() + propNames[j]);
String propValue = resource.getName() + propValues[j];
resource.setPersistentProperty(propName, propValue);
resource.setSessionProperty(propName, propValue);
}
}
// create the destination folder
String folderDestinationName = "destination";
IFolder folderDestination = projects[1].getFolder(folderDestinationName);
// move hierarchy
folderSource.move(folderDestination.getFullPath(), true, null);
// get new hierarchy instance
IResource[] newResources = buildResources(folderDestination, hierarchy);
// assert hierarchy was moved
assertDoesNotExistInWorkspace(resources);
assertDoesNotExistInFileSystem(resources);
assertExistsInWorkspace(newResources);
assertExistsInFileSystem(newResources);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
for (int i = 0; i < newResources.length; i++) {
IResource destResource = newResources[i];
IResource sourceResource = resources[i];
/* The names of the properties will remain the same in both the source and
destination hierarchies. So, be sure to use sourceResource to get the
name or your qualified name will contain 'destination' instead of
'source' and the property value will be null.
*/
QualifiedName propName = new QualifiedName("test", sourceResource.getName() + propNames[j]);
String propValue = sourceResource.getName() + propValues[j];
String persistentValue = destResource.getPersistentProperty(propName);
Object sessionValue = destResource.getSessionProperty(propName);
assertTrue("persistent property value is not the same", propValue.equals(persistentValue));
assertTrue("session property value is not the same", propValue.equals(sessionValue));
}
}
}
public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
+ // FIXME: should #move be a best effort operation?
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
- assertTrue("4.4", destination.exists());
+ assertTrue("4.4", !destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
/**
* A simple test that renames a file.
*/
public void testRenameFile() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create a folder
String fileName = "file.txt";
IFile file = projects[0].getFile(fileName);
ensureExistsInWorkspace(file, true);
// add some properties to file (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
file.setPersistentProperty(propNames[j], propValues[j]);
file.setSessionProperty(propNames[j], propValues[j]);
}
// rename file
String newFileName = "newFile.txt";
IPath destination = projects[0].getFile(newFileName).getFullPath();
file.move(destination, true, null);
// get new folder instance
IFile newFile = projects[0].getFile(newFileName);
// assert file was renamed
assertDoesNotExistInWorkspace(file);
assertDoesNotExistInFileSystem(file);
assertExistsInWorkspace(newFile);
assertExistsInFileSystem(newFile);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFile.getPersistentProperty(propNames[j]);
Object sessionValue = newFile.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* A simple test that renames a folder.
*
* - creates a folder
* - set properties (server, local and session)
* - rename folder
* - assert rename worked
* - assert properties still exist
*/
public void testRenameFolder() throws Exception {
// create common objects
IProject[] projects = getWorkspace().getRoot().getProjects();
// create a folder
String folderName = "folder";
IFolder folder = projects[0].getFolder(folderName);
ensureExistsInWorkspace(folder, true);
// add some properties to folder (persistent and session)
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int j = 0; j < numberOfProperties; j++) {
propNames[j] = new QualifiedName("test", "prop" + j);
propValues[j] = "value" + j;
folder.setPersistentProperty(propNames[j], propValues[j]);
folder.setSessionProperty(propNames[j], propValues[j]);
}
// rename folder
String newFolderName = "newFolder";
IPath destination = projects[0].getFolder(newFolderName).getFullPath();
folder.move(destination, true, null);
// get new folder instance
IFolder newFolder = projects[0].getFolder(newFolderName);
// assert folder was renamed
assertDoesNotExistInWorkspace(folder);
assertDoesNotExistInFileSystem(folder);
assertExistsInWorkspace(newFolder);
assertExistsInFileSystem(newFolder);
// assert properties still exist (server, local and session)
for (int j = 0; j < numberOfProperties; j++) {
String persistentValue = newFolder.getPersistentProperty(propNames[j]);
Object sessionValue = newFolder.getSessionProperty(propNames[j]);
assertTrue("persistent property value is not the same", propValues[j].equals(persistentValue));
assertTrue("session property value is not the same", propValues[j].equals(sessionValue));
}
}
/**
* Renames 3 projects using their names.
*
* - add properties to projects (server, local and session)
* - rename projects
* - assert properties are correct
* - assert resources are correct
*/
public void testRenameProjects() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
// add some properties to projects (persistent and session)
numberOfProperties = numberOfProjects;
QualifiedName[] propNames = new QualifiedName[numberOfProperties];
String[] propValues = new String[numberOfProperties];
for (int i = 0; i < numberOfProjects; i++) {
propNames[i] = new QualifiedName("test", "prop" + i);
propValues[i] = "value" + i;
projects[i].setPersistentProperty(propNames[i], propValues[i]);
projects[i].setSessionProperty(propNames[i], propValues[i]);
}
// assert properties exist (persistent and session)
for (int i = 0; i < numberOfProjects; i++) {
String persistentValue = projects[i].getPersistentProperty(propNames[i]);
Object sessionValue = projects[i].getSessionProperty(propNames[i]);
assertTrue("1.0." + i, propValues[i].equals(persistentValue));
assertTrue("1.1." + i, propValues[i].equals(sessionValue));
}
// move (rename) projects
String prefix = "Renamed_PrOjEcT";
for (int i = 0; i < numberOfProjects; i++) {
String projectName = prefix + i;
IPath destination = getWorkspace().getRoot().getProject(projectName).getFullPath();
projects[i].move(destination, true, null);
projectNames[i] = projectName;
}
// get new projects instances
for (int i = 0; i < numberOfProjects; i++)
projects[i] = getWorkspace().getRoot().getProject(projectNames[i]);
// assert properties still exist (persistent and session)
for (int i = 0; i < numberOfProjects; i++) {
String persistentValue = projects[i].getPersistentProperty(propNames[i]);
Object sessionValue = projects[i].getSessionProperty(propNames[i]);
assertTrue("2.0." + i, propValues[i].equals(persistentValue));
assertTrue("2.1." + i, propValues[i].equals(sessionValue));
}
}
}
| false | true | public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
assertTrue("4.4", destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
| public void testMoveResource() throws Exception {
/* create common objects */
IProject[] projects = getWorkspace().getRoot().getProjects();
/* create folder and file */
IFolder folder = projects[0].getFolder("folder");
IFile file = folder.getFile("file.txt");
ensureExistsInWorkspace(folder, true);
ensureExistsInWorkspace(file, true);
/* move to absolute destination */
IResource destination = projects[0].getFile("file.txt");
file.move(destination.getFullPath(), true, null);
assertTrue("1.1", !file.exists());
assertTrue("1.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("1.3", file.exists());
assertTrue("1.4", !destination.exists());
/* move to relative destination */
IPath path = new Path("destination");
destination = folder.getFile(path);
file.move(path, true, null);
assertTrue("2.1", !file.exists());
assertTrue("2.2", destination.exists());
destination.move(file.getFullPath(), true, null);
assertTrue("2.3", file.exists());
assertTrue("2.4", !destination.exists());
/* move folder to destination under its hierarchy */
destination = folder.getFolder("subfolder");
boolean ok = false;
try {
folder.move(destination.getFullPath(), true, null);
} catch (RuntimeException e) {
ok = true;
}
assertTrue("3.1", ok);
/* test flag force = false */
projects[0].refreshLocal(IResource.DEPTH_INFINITE, null);
IFolder subfolder = folder.getFolder("aaa");
ensureExistsInFileSystem(subfolder);
IFile anotherFile = folder.getFile("bbb");
ensureExistsInFileSystem(anotherFile);
destination = projects[0].getFolder("destination");
ok = false;
try {
folder.move(destination.getFullPath(), false, null);
} catch (CoreException e) {
ok = true;
// FIXME: remove this check?
// assertTrue("4.1", e.getStatus().getChildren().length == 2);
}
assertTrue("4.2", ok);
try {
folder.move(destination.getFullPath(), false, null);
fail("4.2.1");
} catch (CoreException e) {
}
assertTrue("4.3", folder.exists());
// FIXME: should #move be a best effort operation?
// its ok for the root to be moved but ensure the destination child wasn't moved
IResource destChild = ((IContainer) destination).getFile(new Path(anotherFile.getName()));
assertTrue("4.4", !destination.exists());
assertTrue("4.5", !destChild.exists());
// cleanup and delete the destination
try {
destination.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
} catch (CoreException e) {
fail("4.6", e);
}
try {
destination.delete(true, getMonitor());
} catch (CoreException e) {
fail("4.7", e);
}
folder.refreshLocal(IResource.DEPTH_INFINITE, getMonitor());
try {
folder.move(destination.getFullPath(), false, getMonitor());
} catch (CoreException e) {
fail("4.8");
}
destination.move(folder.getFullPath(), true, null);
assertTrue("4.9", folder.exists());
assertTrue("4.10", !destination.exists());
/* move a file that is not local but exists in the workspace */
file = projects[0].getFile("ghost");
final IFile hackFile = file;
final Workspace workspace = (Workspace) this.getWorkspace();
IWorkspaceRunnable operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
workspace.createResource(hackFile, false);
}
};
workspace.run(operation, null);
destination = projects[0].getFile("destination");
ok = false;
try {
file.move(destination.getFullPath(), true, null);
} catch (CoreException e) {
ok = true;
}
assertTrue("5.1", ok);
/* move file over a phantom */
assertTrue("6.1", file.exists());
operation = new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
((Resource) hackFile).convertToPhantom();
}
};
workspace.run(operation, null);
assertTrue("6.2", !file.exists());
ResourceInfo info = ((File) file).getResourceInfo(true, false);
int flags = ((File) file).getFlags(info);
assertTrue("6.3", ((Resource) file).exists(flags, true));
anotherFile = folder.getFile("anotherFile");
ensureExistsInWorkspace(anotherFile, true);
anotherFile.move(file.getFullPath(), true, null);
assertTrue("6.4", file.exists());
}
|
diff --git a/src/org/eclipse/core/tests/internal/watson/TestElementComparator.java b/src/org/eclipse/core/tests/internal/watson/TestElementComparator.java
index 9b0d58f..d92a56d 100644
--- a/src/org/eclipse/core/tests/internal/watson/TestElementComparator.java
+++ b/src/org/eclipse/core/tests/internal/watson/TestElementComparator.java
@@ -1,80 +1,73 @@
/*******************************************************************************
* 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 Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.internal.watson;
import org.eclipse.core.internal.dtree.NodeComparison;
import org.eclipse.core.internal.watson.IElementComparator;
/**
* This is what you would expect for an element tree comparator.
* Clients of the element tree that want specific comparison behaviour
* must define their own element comparator (without subclassing or
* otherwise extending this comparator). Internal element tree operations
* rely on the behaviour of this type, and the ElementTree maintainer
* reserves the right to change its behaviour as necessary.
*/
public class TestElementComparator implements IElementComparator {
private static IElementComparator fSingleton;
static final int ADDED = NodeComparison.K_ADDED;
static final int REMOVED = NodeComparison.K_REMOVED;
static final int CHANGED = NodeComparison.K_CHANGED;
/**
* Force clients to use the singleton
*/
protected TestElementComparator() {
super();
}
/**
* Returns the type of change.
*/
public int compare(Object oldInfo, Object newInfo) {
if (oldInfo == null) {
- if (newInfo == null) {
+ if (newInfo == null)
return CHANGED;
- } else {
- return ADDED;
- }
- }
- if (newInfo == null) {
- if (oldInfo == null) {
- return CHANGED;
- } else {
- return REMOVED;
- }
+ return ADDED;
}
+ if (newInfo == null)
+ return REMOVED;
return testEquality(oldInfo, newInfo) ? K_NO_CHANGE : CHANGED;
}
/**
* Returns the singleton instance
*/
public static IElementComparator getComparator() {
if (fSingleton == null) {
fSingleton = new TestElementComparator();
}
return fSingleton;
}
/**
* Makes a comparison based on equality
*/
protected boolean testEquality(Object oldInfo, Object newInfo) {
if (oldInfo == null && newInfo == null)
return true;
if (oldInfo == null || newInfo == null)
return false;
return oldInfo.equals(newInfo);
}
}
| false | true | public int compare(Object oldInfo, Object newInfo) {
if (oldInfo == null) {
if (newInfo == null) {
return CHANGED;
} else {
return ADDED;
}
}
if (newInfo == null) {
if (oldInfo == null) {
return CHANGED;
} else {
return REMOVED;
}
}
return testEquality(oldInfo, newInfo) ? K_NO_CHANGE : CHANGED;
}
| public int compare(Object oldInfo, Object newInfo) {
if (oldInfo == null) {
if (newInfo == null)
return CHANGED;
return ADDED;
}
if (newInfo == null)
return REMOVED;
return testEquality(oldInfo, newInfo) ? K_NO_CHANGE : CHANGED;
}
|
diff --git a/wcs1_0/src/test/java/org/geoserver/wcs/xml/GetCoverageXmlParserTest.java b/wcs1_0/src/test/java/org/geoserver/wcs/xml/GetCoverageXmlParserTest.java
index 1c23d62ad..af0e29b40 100644
--- a/wcs1_0/src/test/java/org/geoserver/wcs/xml/GetCoverageXmlParserTest.java
+++ b/wcs1_0/src/test/java/org/geoserver/wcs/xml/GetCoverageXmlParserTest.java
@@ -1,196 +1,196 @@
package org.geoserver.wcs.xml;
import java.io.StringReader;
import junit.framework.TestCase;
import net.opengis.gml.GridType;
import net.opengis.wcs10.AxisSubsetType;
import net.opengis.wcs10.GetCoverageType;
import net.opengis.wcs10.IntervalType;
import net.opengis.wcs10.RangeSubsetType;
import org.geoserver.wcs.xml.v1_0_0.WcsXmlReader;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.referencing.CRS;
import org.geotools.wcs.WCSConfiguration;
import org.opengis.coverage.grid.GridEnvelope;
import org.vfny.geoserver.wcs.WcsException;
public class GetCoverageXmlParserTest extends TestCase {
private WCSConfiguration configuration;
private WcsXmlReader reader;
@Override
protected void setUp() throws Exception {
super.setUp();
configuration = new WCSConfiguration();
reader = new WcsXmlReader("GetCoverage", "1.0.0", configuration);
}
public void testInvalid() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ //
"<GetCoverage service=\"WCS\" version=\"1.0.0\""
+ " xmlns=\"http://www.opengis.net/wcs\" "
+ " xmlns:nurc=\"http://www.nurc.nato.int\""
+ " xmlns:ogc=\"http://www.opengis.net/ogc\""
+ " xmlns:gml=\"http://www.opengis.net/gml\" "
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ " xsi:schemaLocation=\"http://www.opengis.net/wcs schemas/wcs/1.0.0/getCoverage.xsd\">"
+ " <sourceCoverage>nurc:Pk50095</sourceCoverage>" + "</GetCoverage>";
try {
GetCoverageType cov = (GetCoverageType) reader.read(null, new StringReader(request),
null);
fail("This request is not valid!!!");
} catch (WcsException e) {
// ok, we do expect a validation exception in fact
/*
* The content of element 'GetCoverage' is not complete. One of
* '{"http://www.opengis.net/wcs":domainSubset}' is expected.
*/
}
}
public void testBasic() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ //
"<GetCoverage service=\"WCS\" version=\"1.0.0\""
+ //
" xmlns=\"http://www.opengis.net/wcs\" "
+ //
" xmlns:nurc=\"http://www.nurc.nato.int\""
+ //
" xmlns:ogc=\"http://www.opengis.net/ogc\""
+ //
" xmlns:gml=\"http://www.opengis.net/gml\" "
+ //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ //
" xsi:schemaLocation=\"http://www.opengis.net/wcs schemas/wcs/1.0.0/getCoverage.xsd\">"
+ //
" <sourceCoverage>nurc:Pk50095</sourceCoverage>" + //
" <domainSubset>" + //
" <spatialSubset>" + //
" <gml:Envelope srsName=\"EPSG:32633\">" + //
" <gml:pos>347649.93086859107 5176214.082539256</gml:pos>" + //
" <gml:pos>370725.976428591 5196961.352859256</gml:pos>" + //
" </gml:Envelope>" + //
" <gml:Grid dimension=\"2\" srsName=\"EPSG:4326\">" + //
" <gml:limits>" + //
" <gml:GridEnvelope>" + //
" <gml:low>0 0</gml:low>" + //
" <gml:high>545 490</gml:high>" + //
" </gml:GridEnvelope>" + //
" </gml:limits>" + //
" <gml:axisName>Lon</gml:axisName>" + //
" <gml:axisName>Lat</gml:axisName>" + //
" </gml:Grid>" + //
" </spatialSubset>" + //
" </domainSubset>" + //
" <output>" + //
" <crs>EPSG:4326</crs>" + //
" <format>TIFF</format>" + //
" </output>" + //
"</GetCoverage>";
// smoke test, we only try out a very basic request
GetCoverageType gc = (GetCoverageType) reader.read(null, new StringReader(request), null);
assertEquals("WCS", gc.getService());
assertEquals("1.0.0", gc.getVersion());
assertEquals("nurc:Pk50095", gc.getSourceCoverage());
GeneralEnvelope envelope = ((GeneralEnvelope) gc.getDomainSubset().getSpatialSubset()
.getEnvelope().get(0));
assertEquals("EPSG:32633", CRS.lookupIdentifier(envelope.getCoordinateReferenceSystem(),
true));
assertEquals(347649.93086859107, envelope.getLowerCorner().getOrdinate(0));
assertEquals(5176214.082539256, envelope.getLowerCorner().getOrdinate(1));
assertEquals(370725.976428591, envelope.getUpperCorner().getOrdinate(0));
assertEquals(5196961.352859256, envelope.getUpperCorner().getOrdinate(1));
assertNotNull(gc.getOutput().getCrs());
assertEquals("EPSG:4326", gc.getOutput().getCrs().getValue());
assertNotNull(gc.getOutput().getFormat());
assertEquals("TIFF", gc.getOutput().getFormat().getValue());
}
public void testRangeSubsetKeys() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ //
"<GetCoverage service=\"WCS\" version=\"1.0.0\""
+ //
" xmlns=\"http://www.opengis.net/wcs\" "
+ //
" xmlns:nurc=\"http://www.nurc.nato.int\""
+ //
" xmlns:ogc=\"http://www.opengis.net/ogc\""
+ //
" xmlns:gml=\"http://www.opengis.net/gml\" "
+ //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ //
" xsi:schemaLocation=\"http://www.opengis.net/wcs schemas/wcs/1.0.0/getCoverage.xsd\">"
+ //
" <sourceCoverage>nurc:Pk50095</sourceCoverage>" + //
" <domainSubset>" + //
" <spatialSubset>" + //
" <gml:Envelope srsName=\"EPSG:32633\">" + //
" <gml:pos>347649.93086859107 5176214.082539256</gml:pos>" + //
" <gml:pos>370725.976428591 5196961.352859256</gml:pos>" + //
" </gml:Envelope>" + //
" <gml:Grid dimension=\"2\" srsName=\"EPSG:4326\">" + //
" <gml:limits>" + //
" <gml:GridEnvelope>" + //
" <gml:low>0 0</gml:low>" + //
" <gml:high>545 490</gml:high>" + //
" </gml:GridEnvelope>" + //
" </gml:limits>" + //
" <gml:axisName>Column</gml:axisName>" + //
" <gml:axisName>Row</gml:axisName>" + //
" </gml:Grid>" + //
" </spatialSubset>" + //
" </domainSubset>" + //
" <rangeSubset>" + //
" <axisSubset name=\"Band\">" + //
" <interval atomic=\"false\">" + //
" <min>1</min>" + //
" <max>3</max>" + //
" <res>1</res>" + //
" </interval>" + //
" </axisSubset>" + //
" </rangeSubset>" + //
" <output>" + //
" <crs>EPSG:4326</crs>" + //
" <format>TIFF</format>" + //
" </output>" + //
"</GetCoverage>";
GetCoverageType gc = (GetCoverageType) reader.read(null, new StringReader(request), null);
assertEquals(1, gc.getRangeSubset().getAxisSubset().size());
GridType grid = (GridType) gc.getDomainSubset().getSpatialSubset().getGrid().get(0);
assertEquals(grid.getSrsName(), "EPSG:4326");
assertEquals(grid.getAxisName().get(0), "Column");
assertEquals(grid.getAxisName().get(1), "Row");
GridEnvelope gridLimits = grid.getLimits();
- assertEquals(0.0, gridLimits.getLow(0));
- assertEquals(0.0, gridLimits.getLow(1));
- assertEquals(545.0, gridLimits.getHigh(0));
- assertEquals(490.0, gridLimits.getHigh(1));
+ assertEquals(0, gridLimits.getLow(0));
+ assertEquals(0, gridLimits.getLow(1));
+ assertEquals(545, gridLimits.getHigh(0));
+ assertEquals(490, gridLimits.getHigh(1));
RangeSubsetType rangeSet = gc.getRangeSubset();
AxisSubsetType axisSubset = (AxisSubsetType) rangeSet.getAxisSubset().get(0);
assertEquals("Band", axisSubset.getName());
assertEquals(axisSubset.getSingleValue().size(), 0);
assertEquals(axisSubset.getInterval().size(), 1);
IntervalType interval = (IntervalType) axisSubset.getInterval().get(0);
assertEquals("1", interval.getMin().getValue());
assertEquals("3", interval.getMax().getValue());
assertEquals("1", interval.getRes().getValue());
}
}
| true | true | public void testRangeSubsetKeys() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ //
"<GetCoverage service=\"WCS\" version=\"1.0.0\""
+ //
" xmlns=\"http://www.opengis.net/wcs\" "
+ //
" xmlns:nurc=\"http://www.nurc.nato.int\""
+ //
" xmlns:ogc=\"http://www.opengis.net/ogc\""
+ //
" xmlns:gml=\"http://www.opengis.net/gml\" "
+ //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ //
" xsi:schemaLocation=\"http://www.opengis.net/wcs schemas/wcs/1.0.0/getCoverage.xsd\">"
+ //
" <sourceCoverage>nurc:Pk50095</sourceCoverage>" + //
" <domainSubset>" + //
" <spatialSubset>" + //
" <gml:Envelope srsName=\"EPSG:32633\">" + //
" <gml:pos>347649.93086859107 5176214.082539256</gml:pos>" + //
" <gml:pos>370725.976428591 5196961.352859256</gml:pos>" + //
" </gml:Envelope>" + //
" <gml:Grid dimension=\"2\" srsName=\"EPSG:4326\">" + //
" <gml:limits>" + //
" <gml:GridEnvelope>" + //
" <gml:low>0 0</gml:low>" + //
" <gml:high>545 490</gml:high>" + //
" </gml:GridEnvelope>" + //
" </gml:limits>" + //
" <gml:axisName>Column</gml:axisName>" + //
" <gml:axisName>Row</gml:axisName>" + //
" </gml:Grid>" + //
" </spatialSubset>" + //
" </domainSubset>" + //
" <rangeSubset>" + //
" <axisSubset name=\"Band\">" + //
" <interval atomic=\"false\">" + //
" <min>1</min>" + //
" <max>3</max>" + //
" <res>1</res>" + //
" </interval>" + //
" </axisSubset>" + //
" </rangeSubset>" + //
" <output>" + //
" <crs>EPSG:4326</crs>" + //
" <format>TIFF</format>" + //
" </output>" + //
"</GetCoverage>";
GetCoverageType gc = (GetCoverageType) reader.read(null, new StringReader(request), null);
assertEquals(1, gc.getRangeSubset().getAxisSubset().size());
GridType grid = (GridType) gc.getDomainSubset().getSpatialSubset().getGrid().get(0);
assertEquals(grid.getSrsName(), "EPSG:4326");
assertEquals(grid.getAxisName().get(0), "Column");
assertEquals(grid.getAxisName().get(1), "Row");
GridEnvelope gridLimits = grid.getLimits();
assertEquals(0.0, gridLimits.getLow(0));
assertEquals(0.0, gridLimits.getLow(1));
assertEquals(545.0, gridLimits.getHigh(0));
assertEquals(490.0, gridLimits.getHigh(1));
RangeSubsetType rangeSet = gc.getRangeSubset();
AxisSubsetType axisSubset = (AxisSubsetType) rangeSet.getAxisSubset().get(0);
assertEquals("Band", axisSubset.getName());
assertEquals(axisSubset.getSingleValue().size(), 0);
assertEquals(axisSubset.getInterval().size(), 1);
IntervalType interval = (IntervalType) axisSubset.getInterval().get(0);
assertEquals("1", interval.getMin().getValue());
assertEquals("3", interval.getMax().getValue());
assertEquals("1", interval.getRes().getValue());
}
| public void testRangeSubsetKeys() throws Exception {
String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ //
"<GetCoverage service=\"WCS\" version=\"1.0.0\""
+ //
" xmlns=\"http://www.opengis.net/wcs\" "
+ //
" xmlns:nurc=\"http://www.nurc.nato.int\""
+ //
" xmlns:ogc=\"http://www.opengis.net/ogc\""
+ //
" xmlns:gml=\"http://www.opengis.net/gml\" "
+ //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ //
" xsi:schemaLocation=\"http://www.opengis.net/wcs schemas/wcs/1.0.0/getCoverage.xsd\">"
+ //
" <sourceCoverage>nurc:Pk50095</sourceCoverage>" + //
" <domainSubset>" + //
" <spatialSubset>" + //
" <gml:Envelope srsName=\"EPSG:32633\">" + //
" <gml:pos>347649.93086859107 5176214.082539256</gml:pos>" + //
" <gml:pos>370725.976428591 5196961.352859256</gml:pos>" + //
" </gml:Envelope>" + //
" <gml:Grid dimension=\"2\" srsName=\"EPSG:4326\">" + //
" <gml:limits>" + //
" <gml:GridEnvelope>" + //
" <gml:low>0 0</gml:low>" + //
" <gml:high>545 490</gml:high>" + //
" </gml:GridEnvelope>" + //
" </gml:limits>" + //
" <gml:axisName>Column</gml:axisName>" + //
" <gml:axisName>Row</gml:axisName>" + //
" </gml:Grid>" + //
" </spatialSubset>" + //
" </domainSubset>" + //
" <rangeSubset>" + //
" <axisSubset name=\"Band\">" + //
" <interval atomic=\"false\">" + //
" <min>1</min>" + //
" <max>3</max>" + //
" <res>1</res>" + //
" </interval>" + //
" </axisSubset>" + //
" </rangeSubset>" + //
" <output>" + //
" <crs>EPSG:4326</crs>" + //
" <format>TIFF</format>" + //
" </output>" + //
"</GetCoverage>";
GetCoverageType gc = (GetCoverageType) reader.read(null, new StringReader(request), null);
assertEquals(1, gc.getRangeSubset().getAxisSubset().size());
GridType grid = (GridType) gc.getDomainSubset().getSpatialSubset().getGrid().get(0);
assertEquals(grid.getSrsName(), "EPSG:4326");
assertEquals(grid.getAxisName().get(0), "Column");
assertEquals(grid.getAxisName().get(1), "Row");
GridEnvelope gridLimits = grid.getLimits();
assertEquals(0, gridLimits.getLow(0));
assertEquals(0, gridLimits.getLow(1));
assertEquals(545, gridLimits.getHigh(0));
assertEquals(490, gridLimits.getHigh(1));
RangeSubsetType rangeSet = gc.getRangeSubset();
AxisSubsetType axisSubset = (AxisSubsetType) rangeSet.getAxisSubset().get(0);
assertEquals("Band", axisSubset.getName());
assertEquals(axisSubset.getSingleValue().size(), 0);
assertEquals(axisSubset.getInterval().size(), 1);
IntervalType interval = (IntervalType) axisSubset.getInterval().get(0);
assertEquals("1", interval.getMin().getValue());
assertEquals("3", interval.getMax().getValue());
assertEquals("1", interval.getRes().getValue());
}
|
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 9f614b09..7a6ea413 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -1,2616 +1,2617 @@
/*
* 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.browser;
import com.android.browser.IntentHandler.UrlData;
import com.android.browser.UI.DropdownChangeListener;
import com.android.browser.search.SearchEngine;
import com.android.common.Search;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.SearchManager;
import android.content.ClipboardManager;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceActivity;
import android.provider.Browser;
import android.provider.BrowserContract;
import android.provider.BrowserContract.Images;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
import android.speech.RecognizerIntent;
import android.speech.RecognizerResultsIntent;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
/**
* Controller for browser
*/
public class Controller
implements WebViewController, UiController {
private static final String LOGTAG = "Controller";
private static final String SEND_APP_ID_EXTRA =
"android.speech.extras.SEND_APPLICATION_ID_EXTRA";
// public message ids
public final static int LOAD_URL = 1001;
public final static int STOP_LOAD = 1002;
// Message Ids
private static final int FOCUS_NODE_HREF = 102;
private static final int RELEASE_WAKELOCK = 107;
static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
private static final int OPEN_BOOKMARKS = 201;
private static final int EMPTY_MENU = -1;
// activity requestCode
final static int PREFERENCES_PAGE = 3;
final static int FILE_SELECTED = 4;
final static int AUTOFILL_SETUP = 5;
private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
// As the ids are dynamically created, we can't guarantee that they will
// be in sequence, so this static array maps ids to a window number.
final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
{ R.id.window_one_menu_id, R.id.window_two_menu_id,
R.id.window_three_menu_id, R.id.window_four_menu_id,
R.id.window_five_menu_id, R.id.window_six_menu_id,
R.id.window_seven_menu_id, R.id.window_eight_menu_id };
// "source" parameter for Google search through search key
final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
// "source" parameter for Google search through simplily type
final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
private Activity mActivity;
private UI mUi;
private TabControl mTabControl;
private BrowserSettings mSettings;
private WebViewFactory mFactory;
private OptionsMenuHandler mOptionsMenuHandler = null;
private WakeLock mWakeLock;
private UrlHandler mUrlHandler;
private UploadHandler mUploadHandler;
private IntentHandler mIntentHandler;
private PageDialogsHandler mPageDialogsHandler;
private NetworkStateHandler mNetworkHandler;
private Message mAutoFillSetupMessage;
private boolean mShouldShowErrorConsole;
private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
// FIXME, temp address onPrepareMenu performance problem.
// When we move everything out of view, we should rewrite this.
private int mCurrentMenuState = 0;
private int mMenuState = R.id.MAIN_MENU;
private int mOldMenuState = EMPTY_MENU;
private Menu mCachedMenu;
// Used to prevent chording to result in firing two shortcuts immediately
// one after another. Fixes bug 1211714.
boolean mCanChord;
private boolean mMenuIsDown;
// For select and find, we keep track of the ActionMode so that
// finish() can be called as desired.
private ActionMode mActionMode;
/**
* Only meaningful when mOptionsMenuOpen is true. This variable keeps track
* of whether the configuration has changed. The first onMenuOpened call
* after a configuration change is simply a reopening of the same menu
* (i.e. mIconView did not change).
*/
private boolean mConfigChanged;
/**
* Keeps track of whether the options menu is open. This is important in
* determining whether to show or hide the title bar overlay
*/
private boolean mOptionsMenuOpen;
/**
* Whether or not the options menu is in its bigger, popup menu form. When
* true, we want the title bar overlay to be gone. When false, we do not.
* Only meaningful if mOptionsMenuOpen is true.
*/
private boolean mExtendedMenuOpen;
private boolean mInLoad;
private boolean mActivityPaused = true;
private boolean mLoadStopped;
private Handler mHandler;
// Checks to see when the bookmarks database has changed, and updates the
// Tabs' notion of whether they represent bookmarked sites.
private ContentObserver mBookmarksObserver;
private DataController mDataController;
private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
@Override
public Void doInBackground(File... files) {
if (files != null) {
for (File f : files) {
if (!f.delete()) {
Log.e(LOGTAG, f.getPath() + " was not deleted");
}
}
}
return null;
}
}
public Controller(Activity browser) {
mActivity = browser;
mSettings = BrowserSettings.getInstance();
mDataController = DataController.getInstance(mActivity);
mTabControl = new TabControl(this);
mSettings.setController(this);
mUrlHandler = new UrlHandler(this);
mIntentHandler = new IntentHandler(mActivity, this);
mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
PowerManager pm = (PowerManager) mActivity
.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
startHandler();
mBookmarksObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
int size = mTabControl.getTabCount();
for (int i = 0; i < size; i++) {
mTabControl.getTab(i).updateBookmarkedStatus();
}
}
};
browser.getContentResolver().registerContentObserver(
BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
mNetworkHandler = new NetworkStateHandler(mActivity, this);
// Start watching the default geolocation permissions
mSystemAllowGeolocationOrigins =
new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
mSystemAllowGeolocationOrigins.start();
retainIconsOnStartup();
}
void start(final Bundle icicle, final Intent intent) {
// Unless the last browser usage was within 24 hours, destroy any
// remaining incognito tabs.
Calendar lastActiveDate = icicle != null ?
(Calendar) icicle.getSerializable("lastActiveDate") : null;
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
final boolean restoreIncognitoTabs = !(lastActiveDate == null
|| lastActiveDate.before(yesterday)
|| lastActiveDate.after(today));
// Find out if we will restore any state and remember the tab.
final int currentTab =
mTabControl.canRestoreState(icicle, restoreIncognitoTabs);
if (currentTab == -1) {
// Not able to restore so we go ahead and clear session cookies. We
// must do this before trying to login the user as we don't want to
// clear any session cookies set during login.
CookieManager.getInstance().removeSessionCookie();
}
GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings,
new Runnable() {
@Override public void run() {
start(icicle, intent, currentTab, restoreIncognitoTabs);
}
});
}
private void start(Bundle icicle, Intent intent, int currentTab,
boolean restoreIncognitoTabs) {
if (currentTab == -1) {
final Bundle extra = intent.getExtras();
// Create an initial tab.
// If the intent is ACTION_VIEW and data is not null, the Browser is
// invoked to view the content by another application. In this case,
// the tab will be close when exit.
UrlData urlData = mIntentHandler.getUrlDataFromIntent(intent);
String action = intent.getAction();
final Tab t = mTabControl.createNewTab(
(Intent.ACTION_VIEW.equals(action) &&
intent.getData() != null)
|| RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
.equals(action),
intent.getStringExtra(Browser.EXTRA_APPLICATION_ID),
urlData.mUrl, false);
addTab(t);
setActiveTab(t);
WebView webView = t.getWebView();
if (extra != null) {
int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
if (scale > 0 && scale <= 1000) {
webView.setInitialScale(scale);
}
}
if (urlData.isEmpty()) {
loadUrl(webView, mSettings.getHomePage());
} else {
// monkey protection against delayed start
if (t != null) {
loadUrlDataIn(t, urlData);
}
}
} else {
mTabControl.restoreState(icicle, currentTab, restoreIncognitoTabs,
mUi.needsRestoreAllTabs());
mUi.updateTabs(mTabControl.getTabs());
// TabControl.restoreState() will create a new tab even if
// restoring the state fails.
setActiveTab(mTabControl.getCurrentTab());
}
// clear up the thumbnail directory, which is no longer used;
// ideally this should only be run once after an upgrade from
// a previous version of the browser
new ClearThumbnails().execute(mTabControl.getThumbnailDir()
.listFiles());
// Read JavaScript flags if it exists.
String jsFlags = getSettings().getJsFlags();
if (jsFlags.trim().length() != 0) {
getCurrentWebView().setJsFlags(jsFlags);
}
if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
bookmarksOrHistoryPicker(false);
}
}
void setWebViewFactory(WebViewFactory factory) {
mFactory = factory;
}
@Override
public WebViewFactory getWebViewFactory() {
return mFactory;
}
@Override
public void onSetWebView(Tab tab, WebView view) {
mUi.onSetWebView(tab, view);
}
@Override
public void createSubWindow(Tab tab) {
endActionMode();
WebView mainView = tab.getWebView();
WebView subView = mFactory.createWebView((mainView == null)
? false
: mainView.isPrivateBrowsingEnabled());
mUi.createSubWindow(tab, subView);
}
@Override
public Activity getActivity() {
return mActivity;
}
void setUi(UI ui) {
mUi = ui;
}
BrowserSettings getSettings() {
return mSettings;
}
IntentHandler getIntentHandler() {
return mIntentHandler;
}
@Override
public UI getUi() {
return mUi;
}
int getMaxTabs() {
return mActivity.getResources().getInteger(R.integer.max_tabs);
}
@Override
public TabControl getTabControl() {
return mTabControl;
}
@Override
public List<Tab> getTabs() {
return mTabControl.getTabs();
}
// Open the icon database and retain all the icons for visited sites.
// This is done on a background thread so as not to stall startup.
private void retainIconsOnStartup() {
// WebIconDatabase needs to be retrieved on the UI thread so that if
// it has not been created successfully yet the Handler is started on the
// UI thread.
new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute();
}
private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> {
private WebIconDatabase mDb;
public RetainIconsOnStartupTask(WebIconDatabase db) {
mDb = db;
}
@Override
protected Void doInBackground(Void... unused) {
mDb.open(mActivity.getDir("icons", 0).getPath());
Cursor c = null;
try {
c = Browser.getAllBookmarks(mActivity.getContentResolver());
if (c.moveToFirst()) {
int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
do {
String url = c.getString(urlIndex);
mDb.retainIconForPageUrl(url);
} while (c.moveToNext());
}
} catch (IllegalStateException e) {
Log.e(LOGTAG, "retainIconsOnStartup", e);
} finally {
if (c != null) c.close();
}
return null;
}
}
private void startHandler() {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case OPEN_BOOKMARKS:
bookmarksOrHistoryPicker(false);
break;
case FOCUS_NODE_HREF:
{
String url = (String) msg.getData().get("url");
String title = (String) msg.getData().get("title");
String src = (String) msg.getData().get("src");
if (url == "") url = src; // use image if no anchor
if (TextUtils.isEmpty(url)) {
break;
}
HashMap focusNodeMap = (HashMap) msg.obj;
WebView view = (WebView) focusNodeMap.get("webview");
// Only apply the action if the top window did not change.
if (getCurrentTopWebView() != view) {
break;
}
switch (msg.arg1) {
case R.id.open_context_menu_id:
loadUrlFromContext(getCurrentTopWebView(), url);
break;
case R.id.view_image_context_menu_id:
loadUrlFromContext(getCurrentTopWebView(), src);
break;
case R.id.open_newtab_context_menu_id:
final Tab parent = mTabControl.getCurrentTab();
final Tab newTab = openTab(parent, url, false);
if (newTab != null && newTab != parent) {
parent.addChildTab(newTab);
}
break;
case R.id.copy_link_context_menu_id:
copy(url);
break;
case R.id.save_link_context_menu_id:
case R.id.download_context_menu_id:
DownloadHandler.onDownloadStartNoStream(
mActivity, url, null, null, null,
view.isPrivateBrowsingEnabled());
break;
}
break;
}
case LOAD_URL:
loadUrlFromContext(getCurrentTopWebView(), (String) msg.obj);
break;
case STOP_LOAD:
stopLoading();
break;
case RELEASE_WAKELOCK:
if (mWakeLock.isHeld()) {
mWakeLock.release();
// if we reach here, Browser should be still in the
// background loading after WAKELOCK_TIMEOUT (5-min).
// To avoid burning the battery, stop loading.
mTabControl.stopAllLoading();
}
break;
case UPDATE_BOOKMARK_THUMBNAIL:
Tab tab = (Tab) msg.obj;
if (tab != null) {
updateScreenshot(tab);
}
break;
}
}
};
}
@Override
public void shareCurrentPage() {
shareCurrentPage(mTabControl.getCurrentTab());
}
private void shareCurrentPage(Tab tab) {
if (tab != null) {
sharePage(mActivity, tab.getTitle(),
tab.getUrl(), tab.getFavicon(),
createScreenshot(tab.getWebView(),
getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
}
}
/**
* Share a page, providing the title, url, favicon, and a screenshot. Uses
* an {@link Intent} to launch the Activity chooser.
* @param c Context used to launch a new Activity.
* @param title Title of the page. Stored in the Intent with
* {@link Intent#EXTRA_SUBJECT}
* @param url URL of the page. Stored in the Intent with
* {@link Intent#EXTRA_TEXT}
* @param favicon Bitmap of the favicon for the page. Stored in the Intent
* with {@link Browser#EXTRA_SHARE_FAVICON}
* @param screenshot Bitmap of a screenshot of the page. Stored in the
* Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
*/
static final void sharePage(Context c, String title, String url,
Bitmap favicon, Bitmap screenshot) {
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
send.putExtra(Intent.EXTRA_TEXT, url);
send.putExtra(Intent.EXTRA_SUBJECT, title);
send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
try {
c.startActivity(Intent.createChooser(send, c.getString(
R.string.choosertitle_sharevia)));
} catch(android.content.ActivityNotFoundException ex) {
// if no app handles it, do nothing
}
}
private void copy(CharSequence text) {
ClipboardManager cm = (ClipboardManager) mActivity
.getSystemService(Context.CLIPBOARD_SERVICE);
cm.setText(text);
}
// lifecycle
protected void onConfgurationChanged(Configuration config) {
mConfigChanged = true;
if (mPageDialogsHandler != null) {
mPageDialogsHandler.onConfigurationChanged(config);
}
mUi.onConfigurationChanged(config);
}
@Override
public void handleNewIntent(Intent intent) {
mIntentHandler.onNewIntent(intent);
}
protected void onPause() {
if (mUi.isCustomViewShowing()) {
hideCustomView();
}
if (mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already paused.");
return;
}
mActivityPaused = true;
Tab tab = mTabControl.getCurrentTab();
if (tab != null) {
tab.pause();
if (!pauseWebViewTimers(tab)) {
mWakeLock.acquire();
mHandler.sendMessageDelayed(mHandler
.obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
}
}
mUi.onPause();
mNetworkHandler.onPause();
WebView.disablePlatformNotifications();
}
void onSaveInstanceState(Bundle outState) {
// the default implementation requires each view to have an id. As the
// browser handles the state itself and it doesn't use id for the views,
// don't call the default implementation. Otherwise it will trigger the
// warning like this, "couldn't save which view has focus because the
// focused view XXX has no id".
// Save all the tabs
mTabControl.saveState(outState);
// Save time so that we know how old incognito tabs (if any) are.
outState.putSerializable("lastActiveDate", Calendar.getInstance());
}
void onResume() {
if (!mActivityPaused) {
Log.e(LOGTAG, "BrowserActivity is already resumed.");
return;
}
mActivityPaused = false;
Tab current = mTabControl.getCurrentTab();
if (current != null) {
current.resume();
resumeWebViewTimers(current);
}
if (mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
mUi.onResume();
mNetworkHandler.onResume();
WebView.enablePlatformNotifications();
}
/**
* resume all WebView timers using the WebView instance of the given tab
* @param tab guaranteed non-null
*/
private void resumeWebViewTimers(Tab tab) {
boolean inLoad = tab.inPageLoad();
if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
CookieSyncManager.getInstance().startSync();
WebView w = tab.getWebView();
if (w != null) {
w.resumeTimers();
}
}
}
/**
* Pause all WebView timers using the WebView of the given tab
* @param tab
* @return true if the timers are paused or tab is null
*/
private boolean pauseWebViewTimers(Tab tab) {
if (tab == null) {
return true;
} else if (!tab.inPageLoad()) {
CookieSyncManager.getInstance().stopSync();
WebView w = getCurrentWebView();
if (w != null) {
w.pauseTimers();
}
return true;
}
return false;
}
void onDestroy() {
if (mUploadHandler != null && !mUploadHandler.handled()) {
mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
mUploadHandler = null;
}
if (mTabControl == null) return;
mUi.onDestroy();
// Remove the current tab and sub window
Tab t = mTabControl.getCurrentTab();
if (t != null) {
dismissSubWindow(t);
removeTab(t);
}
mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
// Destroy all the tabs
mTabControl.destroy();
WebIconDatabase.getInstance().close();
// Stop watching the default geolocation permissions
mSystemAllowGeolocationOrigins.stop();
mSystemAllowGeolocationOrigins = null;
}
protected boolean isActivityPaused() {
return mActivityPaused;
}
protected void onLowMemory() {
mTabControl.freeMemory();
}
@Override
public boolean shouldShowErrorConsole() {
return mShouldShowErrorConsole;
}
protected void setShouldShowErrorConsole(boolean show) {
if (show == mShouldShowErrorConsole) {
// Nothing to do.
return;
}
mShouldShowErrorConsole = show;
Tab t = mTabControl.getCurrentTab();
if (t == null) {
// There is no current tab so we cannot toggle the error console
return;
}
mUi.setShouldShowErrorConsole(t, show);
}
@Override
public void stopLoading() {
mLoadStopped = true;
Tab tab = mTabControl.getCurrentTab();
WebView w = getCurrentTopWebView();
w.stopLoading();
mUi.onPageStopped(tab);
}
boolean didUserStopLoading() {
return mLoadStopped;
}
// WebViewController
@Override
public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
// We've started to load a new page. If there was a pending message
// to save a screenshot then we will now take the new page and save
// an incorrect screenshot. Therefore, remove any pending thumbnail
// messages from the queue.
mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL,
tab);
// reset sync timer to avoid sync starts during loading a page
CookieSyncManager.getInstance().resetSync();
if (!mNetworkHandler.isNetworkUp()) {
view.setNetworkAvailable(false);
}
// when BrowserActivity just starts, onPageStarted may be called before
// onResume as it is triggered from onCreate. Call resumeWebViewTimers
// to start the timer. As we won't switch tabs while an activity is in
// pause state, we can ensure calling resume and pause in pair.
if (mActivityPaused) {
resumeWebViewTimers(tab);
}
mLoadStopped = false;
if (!mNetworkHandler.isNetworkUp()) {
mNetworkHandler.createAndShowNetworkDialog();
}
endActionMode();
mUi.onTabDataChanged(tab);
String url = tab.getUrl();
// update the bookmark database for favicon
maybeUpdateFavicon(tab, null, url, favicon);
Performance.tracePageStart(url);
// Performance probe
if (false) {
Performance.onPageStarted();
}
}
@Override
public void onPageFinished(Tab tab) {
mUi.onTabDataChanged(tab);
if (!tab.isPrivateBrowsingEnabled()
&& !TextUtils.isEmpty(tab.getUrl())) {
if (tab.inForeground() && !didUserStopLoading()
|| !tab.inForeground()) {
// Only update the bookmark screenshot if the user did not
// cancel the load early.
mHandler.sendMessageDelayed(mHandler.obtainMessage(
UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
500);
}
}
// pause the WebView timer and release the wake lock if it is finished
// while BrowserActivity is in pause state.
if (mActivityPaused && pauseWebViewTimers(tab)) {
if (mWakeLock.isHeld()) {
mHandler.removeMessages(RELEASE_WAKELOCK);
mWakeLock.release();
}
}
// Performance probe
if (false) {
Performance.onPageFinished(tab.getUrl());
}
Performance.tracePageFinished();
}
@Override
public void onProgressChanged(Tab tab) {
int newProgress = tab.getLoadProgress();
if (newProgress == 100) {
CookieSyncManager.getInstance().sync();
// onProgressChanged() may continue to be called after the main
// frame has finished loading, as any remaining sub frames continue
// to load. We'll only get called once though with newProgress as
// 100 when everything is loaded. (onPageFinished is called once
// when the main frame completes loading regardless of the state of
// any sub frames so calls to onProgressChanges may continue after
// onPageFinished has executed)
if (mInLoad) {
mInLoad = false;
updateInLoadMenuItems(mCachedMenu);
}
} else {
if (!mInLoad) {
// onPageFinished may have already been called but a subframe is
// still loading and updating the progress. Reset mInLoad and
// update the menu items.
mInLoad = true;
updateInLoadMenuItems(mCachedMenu);
}
}
mUi.onProgressChanged(tab);
}
@Override
public void onUpdatedLockIcon(Tab tab) {
mUi.onTabDataChanged(tab);
}
@Override
public void onReceivedTitle(Tab tab, final String title) {
mUi.onTabDataChanged(tab);
final String pageUrl = tab.getOriginalUrl();
if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
>= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
return;
}
// Update the title in the history database if not in private browsing mode
if (!tab.isPrivateBrowsingEnabled()) {
mDataController.updateHistoryTitle(pageUrl, title);
}
}
@Override
public void onFavicon(Tab tab, WebView view, Bitmap icon) {
mUi.onTabDataChanged(tab);
maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
}
@Override
public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
}
@Override
public boolean shouldOverrideKeyEvent(KeyEvent event) {
if (mMenuIsDown) {
// only check shortcut key when MENU is held
return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
event);
} else {
return false;
}
}
@Override
public void onUnhandledKeyEvent(KeyEvent event) {
if (!isActivityPaused()) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
mActivity.onKeyDown(event.getKeyCode(), event);
} else {
mActivity.onKeyUp(event.getKeyCode(), event);
}
}
}
@Override
public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
// Don't save anything in private browsing mode
if (tab.isPrivateBrowsingEnabled()) return;
String url = tab.getOriginalUrl();
if (TextUtils.isEmpty(url)
|| url.regionMatches(true, 0, "about:", 0, 6)) {
return;
}
mDataController.updateVisitedHistory(url);
WebIconDatabase.getInstance().retainIconForPageUrl(url);
}
@Override
public void getVisitedHistory(final ValueCallback<String[]> callback) {
AsyncTask<Void, Void, String[]> task =
new AsyncTask<Void, Void, String[]>() {
@Override
public String[] doInBackground(Void... unused) {
return Browser.getVisitedHistory(mActivity.getContentResolver());
}
@Override
public void onPostExecute(String[] result) {
callback.onReceiveValue(result);
}
};
task.execute();
}
@Override
public void onReceivedHttpAuthRequest(Tab tab, WebView view,
final HttpAuthHandler handler, final String host,
final String realm) {
String username = null;
String password = null;
boolean reuseHttpAuthUsernamePassword
= handler.useHttpAuthUsernamePassword();
if (reuseHttpAuthUsernamePassword && view != null) {
String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
if (credentials != null && credentials.length == 2) {
username = credentials[0];
password = credentials[1];
}
}
if (username != null && password != null) {
handler.proceed(username, password);
} else {
if (tab.inForeground()) {
mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
} else {
handler.cancel();
}
}
}
@Override
public void onDownloadStart(Tab tab, String url, String userAgent,
String contentDisposition, String mimetype, long contentLength) {
WebView w = tab.getWebView();
DownloadHandler.onDownloadStart(mActivity, url, userAgent,
contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
if (w.copyBackForwardList().getSize() == 0) {
// This Tab was opened for the sole purpose of downloading a
// file. Remove it.
if (tab == mTabControl.getCurrentTab()) {
// In this case, the Tab is still on top.
goBackOnePageOrQuit();
} else {
// In this case, it is not.
closeTab(tab);
}
}
}
@Override
public Bitmap getDefaultVideoPoster() {
return mUi.getDefaultVideoPoster();
}
@Override
public View getVideoLoadingProgressView() {
return mUi.getVideoLoadingProgressView();
}
@Override
public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
SslError error) {
mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
}
// helper method
/*
* Update the favorites icon if the private browsing isn't enabled and the
* icon is valid.
*/
private void maybeUpdateFavicon(Tab tab, final String originalUrl,
final String url, Bitmap favicon) {
if (favicon == null) {
return;
}
if (!tab.isPrivateBrowsingEnabled()) {
Bookmarks.updateFavicon(mActivity
.getContentResolver(), originalUrl, url, favicon);
}
}
@Override
public void bookmarkedStatusHasChanged(Tab tab) {
// TODO: Switch to using onTabDataChanged after b/3262950 is fixed
mUi.bookmarkedStatusHasChanged(tab);
}
// end WebViewController
protected void pageUp() {
getCurrentTopWebView().pageUp(false);
}
protected void pageDown() {
getCurrentTopWebView().pageDown(false);
}
// callback from phone title bar
public void editUrl() {
if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
mUi.editUrl(false);
}
public void startVoiceSearch() {
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
mActivity.getComponentName().flattenToString());
intent.putExtra(SEND_APP_ID_EXTRA, false);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
mActivity.startActivity(intent);
}
public void activateVoiceSearchMode(String title) {
mUi.showVoiceTitleBar(title);
}
public void revertVoiceSearchMode(Tab tab) {
mUi.revertVoiceTitleBar(tab);
}
public void showCustomView(Tab tab, View view,
WebChromeClient.CustomViewCallback callback) {
if (tab.inForeground()) {
if (mUi.isCustomViewShowing()) {
callback.onCustomViewHidden();
return;
}
mUi.showCustomView(view, callback);
// Save the menu state and set it to empty while the custom
// view is showing.
mOldMenuState = mMenuState;
mMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
@Override
public void hideCustomView() {
if (mUi.isCustomViewShowing()) {
mUi.onHideCustomView();
// Reset the old menu state.
mMenuState = mOldMenuState;
mOldMenuState = EMPTY_MENU;
mActivity.invalidateOptionsMenu();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (getCurrentTopWebView() == null) return;
switch (requestCode) {
case PREFERENCES_PAGE:
if (resultCode == Activity.RESULT_OK && intent != null) {
String action = intent.getStringExtra(Intent.EXTRA_TEXT);
if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
mTabControl.removeParentChildRelationShips();
}
}
break;
case FILE_SELECTED:
// Chose a file from the file picker.
if (null == mUploadHandler) break;
mUploadHandler.onResult(resultCode, intent);
break;
case AUTOFILL_SETUP:
// Determine whether a profile was actually set up or not
// and if so, send the message back to the WebTextView to
// fill the form with the new profile.
if (getSettings().getAutoFillProfile() != null) {
mAutoFillSetupMessage.sendToTarget();
mAutoFillSetupMessage = null;
}
break;
default:
break;
}
getCurrentTopWebView().requestFocus();
}
/**
* Open the Go page.
* @param startWithHistory If true, open starting on the history tab.
* Otherwise, start with the bookmarks tab.
*/
@Override
public void bookmarksOrHistoryPicker(boolean startWithHistory) {
if (mTabControl.getCurrentWebView() == null) {
return;
}
// clear action mode
if (isInCustomActionMode()) {
endActionMode();
}
Bundle extras = new Bundle();
// Disable opening in a new window if we have maxed out the windows
extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
!mTabControl.canCreateNewTab());
mUi.showComboView(startWithHistory, extras);
}
// combo view callbacks
/**
* callback from ComboPage when clear history is requested
*/
public void onRemoveParentChildRelationships() {
mTabControl.removeParentChildRelationShips();
}
/**
* callback from ComboPage when bookmark/history selection
*/
@Override
public void onUrlSelected(String url, boolean newTab) {
removeComboView();
if (!TextUtils.isEmpty(url)) {
if (newTab) {
openTab(mTabControl.getCurrentTab(), url, false);
} else {
final Tab currentTab = mTabControl.getCurrentTab();
dismissSubWindow(currentTab);
loadUrl(getCurrentTopWebView(), url);
}
}
}
/**
* dismiss the ComboPage
*/
@Override
public void removeComboView() {
mUi.hideComboView();
}
// active tabs page handling
protected void showActiveTabsPage() {
mMenuState = EMPTY_MENU;
mUi.showActiveTabsPage();
}
/**
* Remove the active tabs page.
* @param needToAttach If true, the active tabs page did not attach a tab
* to the content view, so we need to do that here.
*/
@Override
public void removeActiveTabsPage(boolean needToAttach) {
mMenuState = R.id.MAIN_MENU;
mUi.removeActiveTabsPage();
if (needToAttach) {
setActiveTab(mTabControl.getCurrentTab());
}
getCurrentTopWebView().requestFocus();
}
// key handling
protected void onBackKey() {
if (!mUi.onBackKey()) {
WebView subwindow = mTabControl.getCurrentSubWindow();
if (subwindow != null) {
if (subwindow.canGoBack()) {
subwindow.goBack();
} else {
dismissSubWindow(mTabControl.getCurrentTab());
}
} else {
goBackOnePageOrQuit();
}
}
}
// menu handling and state
// TODO: maybe put into separate handler
protected boolean onCreateOptionsMenu(Menu menu) {
if (mOptionsMenuHandler != null) {
return mOptionsMenuHandler.onCreateOptionsMenu(menu);
}
if (mMenuState == EMPTY_MENU) {
return false;
}
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browser, menu);
updateInLoadMenuItems(menu);
// hold on to the menu reference here; it is used by the page callbacks
// to update the menu based on loading state
mCachedMenu = menu;
return true;
}
protected void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v instanceof TitleBarBase) {
return;
}
if (!(v instanceof WebView)) {
return;
}
final WebView webview = (WebView) v;
WebView.HitTestResult result = webview.getHitTestResult();
if (result == null) {
return;
}
int type = result.getType();
if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
Log.w(LOGTAG,
"We should not show context menu when nothing is touched");
return;
}
if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
// let TextView handles context menu
return;
}
// Note, http://b/issue?id=1106666 is requesting that
// an inflated menu can be used again. This is not available
// yet, so inflate each time (yuk!)
MenuInflater inflater = mActivity.getMenuInflater();
inflater.inflate(R.menu.browsercontext, menu);
// Show the correct menu group
final String extra = result.getExtra();
menu.setGroupVisible(R.id.PHONE_MENU,
type == WebView.HitTestResult.PHONE_TYPE);
menu.setGroupVisible(R.id.EMAIL_MENU,
type == WebView.HitTestResult.EMAIL_TYPE);
menu.setGroupVisible(R.id.GEO_MENU,
type == WebView.HitTestResult.GEO_TYPE);
menu.setGroupVisible(R.id.IMAGE_MENU,
type == WebView.HitTestResult.IMAGE_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
menu.setGroupVisible(R.id.ANCHOR_MENU,
type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
|| type == WebView.HitTestResult.PHONE_TYPE
|| type == WebView.HitTestResult.EMAIL_TYPE
|| type == WebView.HitTestResult.GEO_TYPE;
menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
if (hitText) {
menu.findItem(R.id.select_text_menu_id)
.setOnMenuItemClickListener(new SelectText(webview));
}
// Setup custom handling depending on the type
switch (type) {
case WebView.HitTestResult.PHONE_TYPE:
menu.setHeaderTitle(Uri.decode(extra));
menu.findItem(R.id.dial_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_TEL + extra)));
Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
menu.findItem(R.id.add_contact_context_menu_id).setIntent(
addIntent);
menu.findItem(R.id.copy_phone_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.EMAIL_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.email_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_MAILTO + extra)));
menu.findItem(R.id.copy_mail_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.GEO_TYPE:
menu.setHeaderTitle(extra);
menu.findItem(R.id.map_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri
.parse(WebView.SCHEME_GEO
+ URLEncoder.encode(extra))));
menu.findItem(R.id.copy_geo_context_menu_id)
.setOnMenuItemClickListener(
new Copy(extra));
break;
case WebView.HitTestResult.SRC_ANCHOR_TYPE:
case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
menu.setHeaderTitle(extra);
// decide whether to show the open link in new tab option
boolean showNewTab = mTabControl.canCreateNewTab();
MenuItem newTabItem
= menu.findItem(R.id.open_newtab_context_menu_id);
newTabItem.setTitle(
BrowserSettings.getInstance().openInBackground()
? R.string.contextmenu_openlink_newwindow_background
: R.string.contextmenu_openlink_newwindow);
newTabItem.setVisible(showNewTab);
if (showNewTab) {
if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webview);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF,
R.id.open_newtab_context_menu_id,
0, hrefMap);
webview.requestFocusNodeHref(msg);
return true;
}
});
} else {
newTabItem.setOnMenuItemClickListener(
new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
final Tab parent = mTabControl.getCurrentTab();
final Tab newTab = openTab(parent,
extra, false);
if (newTab != parent) {
parent.addChildTab(newTab);
}
return true;
}
});
}
}
if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
break;
}
// otherwise fall through to handle image part
case WebView.HitTestResult.IMAGE_TYPE:
if (type == WebView.HitTestResult.IMAGE_TYPE) {
menu.setHeaderTitle(extra);
}
menu.findItem(R.id.view_image_context_menu_id).setIntent(
new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
menu.findItem(R.id.download_context_menu_id).
setOnMenuItemClickListener(
new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
menu.findItem(R.id.set_wallpaper_context_menu_id).
setOnMenuItemClickListener(new WallpaperHandler(mActivity,
extra));
break;
default:
Log.w(LOGTAG, "We should not get here.");
break;
}
//update the ui
mUi.onContextMenuCreated(menu);
}
/**
* As the menu can be open when loading state changes
* we must manually update the state of the stop/reload menu
* item
*/
private void updateInLoadMenuItems(Menu menu) {
if (menu == null) {
return;
}
MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
MenuItem src = mInLoad ?
menu.findItem(R.id.stop_menu_id):
menu.findItem(R.id.reload_menu_id);
if (src != null) {
dest.setIcon(src.getIcon());
dest.setTitle(src.getTitle());
}
}
boolean onPrepareOptionsMenu(Menu menu) {
if (mOptionsMenuHandler != null) {
return mOptionsMenuHandler.onPrepareOptionsMenu(menu);
}
// This happens when the user begins to hold down the menu key, so
// allow them to chord to get a shortcut.
mCanChord = true;
// Note: setVisible will decide whether an item is visible; while
// setEnabled() will decide whether an item is enabled, which also means
// whether the matching shortcut key will function.
switch (mMenuState) {
case EMPTY_MENU:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_MENU, false);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
}
break;
default:
if (mCurrentMenuState != mMenuState) {
menu.setGroupVisible(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_MENU, true);
menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
}
final WebView w = getCurrentTopWebView();
boolean canGoBack = false;
boolean canGoForward = false;
boolean isHome = false;
if (w != null) {
canGoBack = w.canGoBack();
canGoForward = w.canGoForward();
isHome = mSettings.getHomePage().equals(w.getUrl());
}
final MenuItem back = menu.findItem(R.id.back_menu_id);
back.setEnabled(canGoBack);
final MenuItem home = menu.findItem(R.id.homepage_menu_id);
home.setEnabled(!isHome);
final MenuItem forward = menu.findItem(R.id.forward_menu_id);
forward.setEnabled(canGoForward);
// decide whether to show the share link option
PackageManager pm = mActivity.getPackageManager();
Intent send = new Intent(Intent.ACTION_SEND);
send.setType("text/plain");
ResolveInfo ri = pm.resolveActivity(send,
PackageManager.MATCH_DEFAULT_ONLY);
menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
boolean isNavDump = mSettings.isNavDump();
final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
nav.setVisible(isNavDump);
nav.setEnabled(isNavDump);
boolean showDebugSettings = mSettings.showDebugSettings();
final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
counter.setVisible(showDebugSettings);
counter.setEnabled(showDebugSettings);
final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id);
newtab.setEnabled(getTabControl().canCreateNewTab());
MenuItem archive = menu.findItem(R.id.save_webarchive_menu_id);
Tab tab = getTabControl().getCurrentTab();
String url = tab != null ? tab.getUrl() : null;
archive.setVisible(!TextUtils.isEmpty(url)
&& !url.endsWith(".webarchivexml"));
break;
}
mCurrentMenuState = mMenuState;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
if (mOptionsMenuHandler != null &&
mOptionsMenuHandler.onOptionsItemSelected(item)) {
return true;
}
if (item.getGroupId() != R.id.CONTEXT_MENU) {
// menu remains active, so ensure comboview is dismissed
// if main menu option is selected
removeComboView();
}
if (!mCanChord) {
// The user has already fired a shortcut with this hold down of the
// menu key.
return false;
}
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(false);
break;
case R.id.active_tabs_menu_id:
showActiveTabsPage();
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTopWebView().goBack();
break;
case R.id.forward_menu_id:
getCurrentTopWebView().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
if (current != null) {
dismissSubWindow(current);
loadUrl(current.getWebView(), mSettings.getHomePage());
}
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_webarchive_menu_id:
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(LOGTAG, "External storage not mounted");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final String directory = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + File.separator;
File dir = new File(directory);
if (!dir.exists() && !dir.mkdirs()) {
Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final WebView topWebView = getCurrentTopWebView();
final String title = topWebView.getTitle();
final String url = topWebView.getUrl();
topWebView.saveWebArchive(directory, true,
new ValueCallback<String>() {
@Override
public void onReceiveValue(final String value) {
if (value != null) {
File file = new File(value);
final long length = file.length();
if (file.exists() && length > 0) {
Toast.makeText(mActivity, R.string.webarchive_saved,
Toast.LENGTH_SHORT).show();
final DownloadManager manager = (DownloadManager) mActivity
.getSystemService(Context.DOWNLOAD_SERVICE);
new Thread("Add WebArchive to download manager") {
@Override
public void run() {
- manager.completedDownload(null == title ? value : title,
+ manager.addCompletedDownload(
+ null == title ? value : title,
value, true, "application/x-webarchive-xml",
value, length, true);
}
}.start();
return;
}
}
DownloadHandler.onDownloadStartNoStream(mActivity,
url, null, null, null, topWebView.isPrivateBrowsingEnabled());
}
});
break;
case R.id.page_info_menu_id:
mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
false);
break;
case R.id.classic_history_menu_id:
bookmarksOrHistoryPicker(true);
break;
case R.id.title_bar_share_page_url:
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
mCanChord = false;
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(id);
}
break;
}
}
}
break;
default:
return false;
}
mCanChord = false;
return true;
}
public boolean onContextItemSelected(MenuItem item) {
// Let the History and Bookmark fragments handle menus they created.
if (item.getGroupId() == R.id.CONTEXT_MENU) {
return false;
}
// chording is not an issue with context menus, but we use the same
// options selector, so set mCanChord to true so we can access them.
mCanChord = true;
int id = item.getItemId();
boolean result = true;
switch (id) {
// For the context menu from the title bar
case R.id.title_bar_copy_page_url:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
result = false;
break;
}
WebView mainView = currentTab.getWebView();
if (null == mainView) {
result = false;
break;
}
copy(mainView.getUrl());
break;
// -- Browser context menu
case R.id.open_context_menu_id:
case R.id.save_link_context_menu_id:
case R.id.copy_link_context_menu_id:
final WebView webView = getCurrentTopWebView();
if (null == webView) {
result = false;
break;
}
final HashMap<String, WebView> hrefMap =
new HashMap<String, WebView>();
hrefMap.put("webview", webView);
final Message msg = mHandler.obtainMessage(
FOCUS_NODE_HREF, id, 0, hrefMap);
webView.requestFocusNodeHref(msg);
break;
default:
// For other context menus
result = onOptionsItemSelected(item);
}
mCanChord = false;
return result;
}
/**
* support programmatically opening the context menu
*/
public void openContextMenu(View view) {
mActivity.openContextMenu(view);
}
/**
* programmatically open the options menu
*/
public void openOptionsMenu() {
mActivity.openOptionsMenu();
}
public boolean onMenuOpened(int featureId, Menu menu) {
if (mOptionsMenuOpen) {
if (mConfigChanged) {
// We do not need to make any changes to the state of the
// title bar, since the only thing that happened was a
// change in orientation
mConfigChanged = false;
} else {
if (!mExtendedMenuOpen) {
mExtendedMenuOpen = true;
mUi.onExtendedMenuOpened();
} else {
// Switching the menu back to icon view, so show the
// title bar once again.
mExtendedMenuOpen = false;
mUi.onExtendedMenuClosed(mInLoad);
mUi.onOptionsMenuOpened();
}
}
} else {
// The options menu is closed, so open it, and show the title
mOptionsMenuOpen = true;
mConfigChanged = false;
mExtendedMenuOpen = false;
mUi.onOptionsMenuOpened();
}
return true;
}
public void onOptionsMenuClosed(Menu menu) {
mOptionsMenuOpen = false;
mUi.onOptionsMenuClosed(mInLoad);
}
public void onContextMenuClosed(Menu menu) {
mUi.onContextMenuClosed(menu, mInLoad);
}
// Helper method for getting the top window.
@Override
public WebView getCurrentTopWebView() {
return mTabControl.getCurrentTopWebView();
}
@Override
public WebView getCurrentWebView() {
return mTabControl.getCurrentWebView();
}
/*
* This method is called as a result of the user selecting the options
* menu to see the download window. It shows the download window on top of
* the current window.
*/
void viewDownloads() {
Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
mActivity.startActivity(intent);
}
// action mode
void onActionModeStarted(ActionMode mode) {
mUi.onActionModeStarted(mode);
mActionMode = mode;
}
/*
* True if a custom ActionMode (i.e. find or select) is in use.
*/
@Override
public boolean isInCustomActionMode() {
return mActionMode != null;
}
/*
* End the current ActionMode.
*/
@Override
public void endActionMode() {
if (mActionMode != null) {
mActionMode.finish();
}
}
/*
* Called by find and select when they are finished. Replace title bars
* as necessary.
*/
public void onActionModeFinished(ActionMode mode) {
if (!isInCustomActionMode()) return;
mUi.onActionModeFinished(mInLoad);
mActionMode = null;
}
boolean isInLoad() {
return mInLoad;
}
// bookmark handling
/**
* add the current page as a bookmark to the given folder id
* @param folderId use -1 for the default folder
* @param canBeAnEdit If true, check to see whether the site is already
* bookmarked, and if it is, edit that bookmark. If false, and
* the site is already bookmarked, do not attempt to edit the
* existing bookmark.
*/
@Override
public void bookmarkCurrentPage(long folderId, boolean canBeAnEdit) {
Intent i = new Intent(mActivity,
AddBookmarkPage.class);
WebView w = getCurrentTopWebView();
i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
String touchIconUrl = w.getTouchIconUrl();
if (touchIconUrl != null) {
i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
WebSettings settings = w.getSettings();
if (settings != null) {
i.putExtra(AddBookmarkPage.USER_AGENT,
settings.getUserAgentString());
}
}
i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
createScreenshot(w, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity)));
i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
i.putExtra(BrowserContract.Bookmarks.PARENT,
folderId);
if (canBeAnEdit) {
i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
}
// Put the dialog at the upper right of the screen, covering the
// star on the title bar.
i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
mActivity.startActivity(i);
}
// file chooser
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadHandler = new UploadHandler(this);
mUploadHandler.openFileChooser(uploadMsg, acceptType);
}
// thumbnails
/**
* Return the desired width for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired width for thumbnail screenshot.
*/
static int getDesiredThumbnailWidth(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailWidth);
}
/**
* Return the desired height for thumbnail screenshots, which are stored in
* the database, and used on the bookmarks screen.
* @param context Context for finding out the density of the screen.
* @return desired height for thumbnail screenshot.
*/
static int getDesiredThumbnailHeight(Context context) {
return context.getResources().getDimensionPixelOffset(
R.dimen.bookmarkThumbnailHeight);
}
private static Bitmap createScreenshot(WebView view, int width, int height) {
// We render to a bitmap 2x the desired size so that we can then
// re-scale it with filtering since canvas.scale doesn't filter
// This helps reduce aliasing at the cost of being slightly blurry
final int filter_scale = 2;
Picture thumbnail = view.capturePicture();
if (thumbnail == null) {
return null;
}
width *= filter_scale;
height *= filter_scale;
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bm);
// May need to tweak these values to determine what is the
// best scale factor
int thumbnailWidth = thumbnail.getWidth();
int thumbnailHeight = thumbnail.getHeight();
float scaleFactor = 1.0f;
if (thumbnailWidth > 0) {
scaleFactor = (float) width / (float)thumbnailWidth;
} else {
return null;
}
if (view.getWidth() > view.getHeight() &&
thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
// If the device is in landscape and the page is shorter
// than the height of the view, center the thumnail and crop the sides
scaleFactor = (float) height / (float)thumbnailHeight;
float wx = (thumbnailWidth * scaleFactor) - width;
canvas.translate((int) -(wx / 2), 0);
}
canvas.scale(scaleFactor, scaleFactor);
thumbnail.draw(canvas);
Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
height / filter_scale, true);
bm.recycle();
return ret;
}
private void updateScreenshot(Tab tab) {
// If this is a bookmarked site, add a screenshot to the database.
// FIXME: Would like to make sure there is actually something to
// draw, but the API for that (WebViewCore.pictureReady()) is not
// currently accessible here.
WebView view = tab.getWebView();
if (view == null) {
// Tab was destroyed
return;
}
final String url = tab.getUrl();
final String originalUrl = view.getOriginalUrl();
if (TextUtils.isEmpty(url)) {
return;
}
// Only update thumbnails for web urls (http(s)://), not for
// about:, javascript:, data:, etc...
// Unless it is a bookmarked site, then always update
if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
return;
}
final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
getDesiredThumbnailHeight(mActivity));
if (bm == null) {
return;
}
final ContentResolver cr = mActivity.getContentResolver();
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... unused) {
Cursor cursor = null;
try {
// TODO: Clean this up
cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
if (cursor != null && cursor.moveToFirst()) {
final ByteArrayOutputStream os =
new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
ContentValues values = new ContentValues();
values.put(Images.THUMBNAIL, os.toByteArray());
do {
values.put(Images.URL, cursor.getString(0));
cr.update(Images.CONTENT_URI, values, null, null);
} while (cursor.moveToNext());
}
} catch (IllegalStateException e) {
// Ignore
} finally {
if (cursor != null) cursor.close();
}
return null;
}
}.execute();
}
private class Copy implements OnMenuItemClickListener {
private CharSequence mText;
public boolean onMenuItemClick(MenuItem item) {
copy(mText);
return true;
}
public Copy(CharSequence toCopy) {
mText = toCopy;
}
}
private static class Download implements OnMenuItemClickListener {
private Activity mActivity;
private String mText;
private boolean mPrivateBrowsing;
public boolean onMenuItemClick(MenuItem item) {
DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
null, null, mPrivateBrowsing);
return true;
}
public Download(Activity activity, String toDownload, boolean privateBrowsing) {
mActivity = activity;
mText = toDownload;
mPrivateBrowsing = privateBrowsing;
}
}
private static class SelectText implements OnMenuItemClickListener {
private WebView mWebView;
public boolean onMenuItemClick(MenuItem item) {
if (mWebView != null) {
return mWebView.selectText();
}
return false;
}
public SelectText(WebView webView) {
mWebView = webView;
}
}
/********************** TODO: UI stuff *****************************/
// these methods have been copied, they still need to be cleaned up
/****************** tabs ***************************************************/
// basic tab interactions:
// it is assumed that tabcontrol already knows about the tab
protected void addTab(Tab tab) {
mUi.addTab(tab);
}
protected void removeTab(Tab tab) {
mUi.removeTab(tab);
mTabControl.removeTab(tab);
}
protected void setActiveTab(Tab tab) {
// monkey protection against delayed start
if (tab != null) {
mTabControl.setCurrentTab(tab);
// the tab is guaranteed to have a webview after setCurrentTab
mUi.setActiveTab(tab);
}
}
protected void closeEmptyChildTab() {
Tab current = mTabControl.getCurrentTab();
if (current != null
&& current.getWebView().copyBackForwardList().getSize() == 0) {
Tab parent = current.getParentTab();
if (parent != null) {
switchToTab(mTabControl.getTabIndex(parent));
closeTab(current);
}
}
}
protected void reuseTab(Tab appTab, String appId, UrlData urlData) {
// Dismiss the subwindow if applicable.
dismissSubWindow(appTab);
// Since we might kill the WebView, remove it from the
// content view first.
mUi.detachTab(appTab);
// Recreate the main WebView after destroying the old one.
mTabControl.recreateWebView(appTab);
// TODO: analyze why the remove and add are necessary
mUi.attachTab(appTab);
if (mTabControl.getCurrentTab() != appTab) {
switchToTab(mTabControl.getTabIndex(appTab));
loadUrlDataIn(appTab, urlData);
} else {
// If the tab was the current tab, we have to attach
// it to the view system again.
setActiveTab(appTab);
loadUrlDataIn(appTab, urlData);
}
}
// Remove the sub window if it exists. Also called by TabControl when the
// user clicks the 'X' to dismiss a sub window.
public void dismissSubWindow(Tab tab) {
removeSubWindow(tab);
// dismiss the subwindow. This will destroy the WebView.
tab.dismissSubWindow();
getCurrentTopWebView().requestFocus();
}
@Override
public void removeSubWindow(Tab t) {
if (t.getSubWebView() != null) {
mUi.removeSubWindow(t.getSubViewContainer());
}
}
@Override
public void attachSubWindow(Tab tab) {
if (tab.getSubWebView() != null) {
mUi.attachSubWindow(tab.getSubViewContainer());
getCurrentTopWebView().requestFocus();
}
}
@Override
public Tab openTabToHomePage() {
// check for max tabs
if (mTabControl.canCreateNewTab()) {
return openTabAndShow(null, new UrlData(mSettings.getHomePage()),
false, null);
} else {
mUi.showMaxTabsWarning();
return null;
}
}
protected Tab openTab(Tab parent, String url, boolean forceForeground) {
if (mSettings.openInBackground() && !forceForeground) {
Tab tab = mTabControl.createNewTab(false, null, null,
(parent != null) && parent.isPrivateBrowsingEnabled());
if (tab != null) {
addTab(tab);
WebView view = tab.getWebView();
loadUrl(view, url);
}
return tab;
} else {
return openTabAndShow(parent, new UrlData(url), false, null);
}
}
// This method does a ton of stuff. It will attempt to create a new tab
// if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
// url isn't null, it will load the given url.
public Tab openTabAndShow(Tab parent, final UrlData urlData,
boolean closeOnExit, String appId) {
final Tab currentTab = mTabControl.getCurrentTab();
if (mTabControl.canCreateNewTab()) {
final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
urlData.mUrl,
(parent != null) && parent.isPrivateBrowsingEnabled());
WebView webview = tab.getWebView();
// We must set the new tab as the current tab to reflect the old
// animation behavior.
addTab(tab);
setActiveTab(tab);
// Callback to load the url data.
final Runnable load = new Runnable() {
@Override public void run() {
if (!urlData.isEmpty()) {
loadUrlDataIn(tab, urlData);
}
}
};
GoogleAccountLogin.startLoginIfNeeded(mActivity, mSettings, load);
return tab;
} else {
// Get rid of the subwindow if it exists
dismissSubWindow(currentTab);
if (!urlData.isEmpty()) {
// Load the given url.
loadUrlDataIn(currentTab, urlData);
}
return currentTab;
}
}
@Override
public Tab openIncognitoTab() {
if (mTabControl.canCreateNewTab()) {
Tab currentTab = mTabControl.getCurrentTab();
Tab tab = mTabControl.createNewTab(false, null,
null, true);
addTab(tab);
setActiveTab(tab);
loadUrlDataIn(tab, new UrlData("browser:incognito"));
return tab;
} else {
mUi.showMaxTabsWarning();
return null;
}
}
/**
* @param index Index of the tab to change to, as defined by
* mTabControl.getTabIndex(Tab t).
* @return boolean True if we successfully switched to a different tab. If
* the indexth tab is null, or if that tab is the same as
* the current one, return false.
*/
@Override
public boolean switchToTab(int index) {
// hide combo view if open
removeComboView();
Tab tab = mTabControl.getTab(index);
Tab currentTab = mTabControl.getCurrentTab();
if (tab == null || tab == currentTab) {
return false;
}
setActiveTab(tab);
return true;
}
@Override
public void closeCurrentTab() {
// hide combo view if open
removeComboView();
final Tab current = mTabControl.getCurrentTab();
if (mTabControl.getTabCount() == 1) {
mActivity.finish();
return;
}
final Tab parent = current.getParentTab();
int indexToShow = -1;
if (parent != null) {
indexToShow = mTabControl.getTabIndex(parent);
} else {
final int currentIndex = mTabControl.getCurrentIndex();
// Try to move to the tab to the right
indexToShow = currentIndex + 1;
if (indexToShow > mTabControl.getTabCount() - 1) {
// Try to move to the tab to the left
indexToShow = currentIndex - 1;
}
}
if (switchToTab(indexToShow)) {
// Close window
closeTab(current);
}
}
/**
* Close the tab, remove its associated title bar, and adjust mTabControl's
* current tab to a valid value.
*/
@Override
public void closeTab(Tab tab) {
// hide combo view if open
removeComboView();
int currentIndex = mTabControl.getCurrentIndex();
int removeIndex = mTabControl.getTabIndex(tab);
Tab newtab = mTabControl.getTab(currentIndex);
setActiveTab(newtab);
removeTab(tab);
}
/**************** TODO: Url loading clean up *******************************/
// Called when loading from context menu or LOAD_URL message
protected void loadUrlFromContext(WebView view, String url) {
// In case the user enters nothing.
if (url != null && url.length() != 0 && view != null) {
url = UrlUtils.smartUrlFilter(url);
if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
loadUrl(view, url);
}
}
}
/**
* Load the URL into the given WebView and update the title bar
* to reflect the new load. Call this instead of WebView.loadUrl
* directly.
* @param view The WebView used to load url.
* @param url The URL to load.
*/
protected void loadUrl(WebView view, String url) {
view.loadUrl(url);
}
/**
* Load UrlData into a Tab and update the title bar to reflect the new
* load. Call this instead of UrlData.loadIn directly.
* @param t The Tab used to load.
* @param data The UrlData being loaded.
*/
protected void loadUrlDataIn(Tab t, UrlData data) {
data.loadIn(t);
}
@Override
public void onUserCanceledSsl(Tab tab) {
WebView web = tab.getWebView();
// TODO: Figure out the "right" behavior
if (web.canGoBack()) {
web.goBack();
} else {
web.loadUrl(mSettings.getHomePage());
}
}
void goBackOnePageOrQuit() {
Tab current = mTabControl.getCurrentTab();
if (current == null) {
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
return;
}
WebView w = current.getWebView();
if (w.canGoBack()) {
w.goBack();
} else {
// Check to see if we are closing a window that was created by
// another window. If so, we switch back to that window.
Tab parent = current.getParentTab();
if (parent != null) {
switchToTab(mTabControl.getTabIndex(parent));
// Now we close the other tab
closeTab(current);
} else {
if (current.closeOnExit()) {
// This will finish the activity if there is only one tab
// open or it will switch to the next available tab if
// available.
closeCurrentTab();
}
/*
* Instead of finishing the activity, simply push this to the back
* of the stack and let ActivityManager to choose the foreground
* activity. As BrowserActivity is singleTask, it will be always the
* root of the task. So we can use either true or false for
* moveTaskToBack().
*/
mActivity.moveTaskToBack(true);
}
}
}
/**
* Feed the previously stored results strings to the BrowserProvider so that
* the SearchDialog will show them instead of the standard searches.
* @param result String to show on the editable line of the SearchDialog.
*/
@Override
public void showVoiceSearchResults(String result) {
ContentProviderClient client = mActivity.getContentResolver()
.acquireContentProviderClient(Browser.BOOKMARKS_URI);
ContentProvider prov = client.getLocalContentProvider();
BrowserProvider bp = (BrowserProvider) prov;
bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
client.release();
Bundle bundle = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_SEARCHKEY);
bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
startSearch(result, false, bundle, false);
}
@Override
public void startSearch(String url) {
startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
null, false);
}
private void startSearch(String initialQuery, boolean selectInitialQuery,
Bundle appSearchData, boolean globalSearch) {
if (appSearchData == null) {
appSearchData = createGoogleSearchSourceBundle(
GOOGLE_SEARCH_SOURCE_TYPE);
}
SearchEngine searchEngine = mSettings.getSearchEngine();
if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
}
mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
globalSearch);
}
private Bundle createGoogleSearchSourceBundle(String source) {
Bundle bundle = new Bundle();
bundle.putString(Search.SOURCE, source);
return bundle;
}
/**
* handle key events in browser
*
* @param keyCode
* @param event
* @return true if handled, false to pass to super
*/
boolean onKeyDown(int keyCode, KeyEvent event) {
boolean noModifiers = event.hasNoModifiers();
// Even if MENU is already held down, we need to call to super to open
// the IME on long press.
if (!noModifiers
&& ((KeyEvent.KEYCODE_MENU == keyCode)
|| (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
|| (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
mMenuIsDown = true;
return false;
}
WebView webView = getCurrentTopWebView();
if (webView == null) return false;
boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
switch(keyCode) {
case KeyEvent.KEYCODE_ESCAPE:
if (!noModifiers) break;
stopLoading();
return true;
case KeyEvent.KEYCODE_SPACE:
// WebView/WebTextView handle the keys in the KeyDown. As
// the Activity's shortcut keys are only handled when WebView
// doesn't, have to do it in onKeyDown instead of onKeyUp.
if (shift) {
pageUp();
} else if (noModifiers) {
pageDown();
}
return true;
case KeyEvent.KEYCODE_BACK:
if (!noModifiers) break;
event.startTracking();
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (ctrl) {
webView.goBack();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (ctrl) {
webView.goForward();
return true;
}
break;
case KeyEvent.KEYCODE_A:
if (ctrl) {
webView.selectAll();
return true;
}
break;
// case KeyEvent.KEYCODE_B: // menu
case KeyEvent.KEYCODE_C:
if (ctrl) {
webView.copySelection();
return true;
}
break;
// case KeyEvent.KEYCODE_D: // menu
// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_F: // menu
// case KeyEvent.KEYCODE_G: // in Chrome: finds next match
// case KeyEvent.KEYCODE_H: // menu
// case KeyEvent.KEYCODE_I: // unused
// case KeyEvent.KEYCODE_J: // menu
// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar
// case KeyEvent.KEYCODE_L: // menu
// case KeyEvent.KEYCODE_M: // unused
// case KeyEvent.KEYCODE_N: // in Chrome: new window
// case KeyEvent.KEYCODE_O: // in Chrome: open file
// case KeyEvent.KEYCODE_P: // in Chrome: print page
// case KeyEvent.KEYCODE_Q: // unused
// case KeyEvent.KEYCODE_R:
// case KeyEvent.KEYCODE_S: // in Chrome: saves page
case KeyEvent.KEYCODE_T:
// we can't use the ctrl/shift flags, they check for
// exclusive use of a modifier
if (event.isCtrlPressed()) {
if (event.isShiftPressed()) {
openIncognitoTab();
} else {
openTabToHomePage();
}
return true;
}
break;
// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page
// case KeyEvent.KEYCODE_V: // text view intercepts to paste
// case KeyEvent.KEYCODE_W: // menu
// case KeyEvent.KEYCODE_X: // text view intercepts to cut
// case KeyEvent.KEYCODE_Y: // unused
// case KeyEvent.KEYCODE_Z: // unused
}
// it is a regular key and webview is not null
return mUi.dispatchKey(keyCode, event);
}
boolean onKeyLongPress(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mUi.showsWeb()) {
bookmarksOrHistoryPicker(true);
return true;
}
break;
}
return false;
}
boolean onKeyUp(int keyCode, KeyEvent event) {
if (!event.hasNoModifiers()) return false;
switch(keyCode) {
case KeyEvent.KEYCODE_MENU:
mMenuIsDown = false;
break;
case KeyEvent.KEYCODE_BACK:
if (event.isTracking() && !event.isCanceled()) {
onBackKey();
return true;
}
break;
}
return false;
}
public boolean isMenuDown() {
return mMenuIsDown;
}
public void setupAutoFill(Message message) {
// Open the settings activity at the AutoFill profile fragment so that
// the user can create a new profile. When they return, we will dispatch
// the message so that we can autofill the form using their new profile.
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
AutoFillSettingsFragment.class.getName());
mAutoFillSetupMessage = message;
mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
}
@Override
public void registerOptionsMenuHandler(OptionsMenuHandler handler) {
mOptionsMenuHandler = handler;
}
@Override
public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) {
if (mOptionsMenuHandler == handler) {
mOptionsMenuHandler = null;
}
}
@Override
public void registerDropdownChangeListener(DropdownChangeListener d) {
mUi.registerDropdownChangeListener(d);
}
}
| true | true | public boolean onOptionsItemSelected(MenuItem item) {
if (mOptionsMenuHandler != null &&
mOptionsMenuHandler.onOptionsItemSelected(item)) {
return true;
}
if (item.getGroupId() != R.id.CONTEXT_MENU) {
// menu remains active, so ensure comboview is dismissed
// if main menu option is selected
removeComboView();
}
if (!mCanChord) {
// The user has already fired a shortcut with this hold down of the
// menu key.
return false;
}
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(false);
break;
case R.id.active_tabs_menu_id:
showActiveTabsPage();
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTopWebView().goBack();
break;
case R.id.forward_menu_id:
getCurrentTopWebView().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
if (current != null) {
dismissSubWindow(current);
loadUrl(current.getWebView(), mSettings.getHomePage());
}
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_webarchive_menu_id:
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(LOGTAG, "External storage not mounted");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final String directory = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + File.separator;
File dir = new File(directory);
if (!dir.exists() && !dir.mkdirs()) {
Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final WebView topWebView = getCurrentTopWebView();
final String title = topWebView.getTitle();
final String url = topWebView.getUrl();
topWebView.saveWebArchive(directory, true,
new ValueCallback<String>() {
@Override
public void onReceiveValue(final String value) {
if (value != null) {
File file = new File(value);
final long length = file.length();
if (file.exists() && length > 0) {
Toast.makeText(mActivity, R.string.webarchive_saved,
Toast.LENGTH_SHORT).show();
final DownloadManager manager = (DownloadManager) mActivity
.getSystemService(Context.DOWNLOAD_SERVICE);
new Thread("Add WebArchive to download manager") {
@Override
public void run() {
manager.completedDownload(null == title ? value : title,
value, true, "application/x-webarchive-xml",
value, length, true);
}
}.start();
return;
}
}
DownloadHandler.onDownloadStartNoStream(mActivity,
url, null, null, null, topWebView.isPrivateBrowsingEnabled());
}
});
break;
case R.id.page_info_menu_id:
mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
false);
break;
case R.id.classic_history_menu_id:
bookmarksOrHistoryPicker(true);
break;
case R.id.title_bar_share_page_url:
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
mCanChord = false;
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(id);
}
break;
}
}
}
break;
default:
return false;
}
mCanChord = false;
return true;
}
| public boolean onOptionsItemSelected(MenuItem item) {
if (mOptionsMenuHandler != null &&
mOptionsMenuHandler.onOptionsItemSelected(item)) {
return true;
}
if (item.getGroupId() != R.id.CONTEXT_MENU) {
// menu remains active, so ensure comboview is dismissed
// if main menu option is selected
removeComboView();
}
if (!mCanChord) {
// The user has already fired a shortcut with this hold down of the
// menu key.
return false;
}
if (null == getCurrentTopWebView()) {
return false;
}
if (mMenuIsDown) {
// The shortcut action consumes the MENU. Even if it is still down,
// it won't trigger the next shortcut action. In the case of the
// shortcut action triggering a new activity, like Bookmarks, we
// won't get onKeyUp for MENU. So it is important to reset it here.
mMenuIsDown = false;
}
switch (item.getItemId()) {
// -- Main menu
case R.id.new_tab_menu_id:
openTabToHomePage();
break;
case R.id.incognito_menu_id:
openIncognitoTab();
break;
case R.id.goto_menu_id:
editUrl();
break;
case R.id.bookmarks_menu_id:
bookmarksOrHistoryPicker(false);
break;
case R.id.active_tabs_menu_id:
showActiveTabsPage();
break;
case R.id.add_bookmark_menu_id:
bookmarkCurrentPage(AddBookmarkPage.DEFAULT_FOLDER_ID, false);
break;
case R.id.stop_reload_menu_id:
if (mInLoad) {
stopLoading();
} else {
getCurrentTopWebView().reload();
}
break;
case R.id.back_menu_id:
getCurrentTopWebView().goBack();
break;
case R.id.forward_menu_id:
getCurrentTopWebView().goForward();
break;
case R.id.close_menu_id:
// Close the subwindow if it exists.
if (mTabControl.getCurrentSubWindow() != null) {
dismissSubWindow(mTabControl.getCurrentTab());
break;
}
closeCurrentTab();
break;
case R.id.homepage_menu_id:
Tab current = mTabControl.getCurrentTab();
if (current != null) {
dismissSubWindow(current);
loadUrl(current.getWebView(), mSettings.getHomePage());
}
break;
case R.id.preferences_menu_id:
Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
getCurrentTopWebView().getUrl());
mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
break;
case R.id.find_menu_id:
getCurrentTopWebView().showFindDialog(null, true);
break;
case R.id.save_webarchive_menu_id:
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(LOGTAG, "External storage not mounted");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final String directory = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS) + File.separator;
File dir = new File(directory);
if (!dir.exists() && !dir.mkdirs()) {
Log.e(LOGTAG, "Save as Web Archive: mkdirs for " + directory + " failed!");
Toast.makeText(mActivity, R.string.webarchive_failed,
Toast.LENGTH_SHORT).show();
break;
}
final WebView topWebView = getCurrentTopWebView();
final String title = topWebView.getTitle();
final String url = topWebView.getUrl();
topWebView.saveWebArchive(directory, true,
new ValueCallback<String>() {
@Override
public void onReceiveValue(final String value) {
if (value != null) {
File file = new File(value);
final long length = file.length();
if (file.exists() && length > 0) {
Toast.makeText(mActivity, R.string.webarchive_saved,
Toast.LENGTH_SHORT).show();
final DownloadManager manager = (DownloadManager) mActivity
.getSystemService(Context.DOWNLOAD_SERVICE);
new Thread("Add WebArchive to download manager") {
@Override
public void run() {
manager.addCompletedDownload(
null == title ? value : title,
value, true, "application/x-webarchive-xml",
value, length, true);
}
}.start();
return;
}
}
DownloadHandler.onDownloadStartNoStream(mActivity,
url, null, null, null, topWebView.isPrivateBrowsingEnabled());
}
});
break;
case R.id.page_info_menu_id:
mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(),
false);
break;
case R.id.classic_history_menu_id:
bookmarksOrHistoryPicker(true);
break;
case R.id.title_bar_share_page_url:
case R.id.share_page_menu_id:
Tab currentTab = mTabControl.getCurrentTab();
if (null == currentTab) {
mCanChord = false;
return false;
}
shareCurrentPage(currentTab);
break;
case R.id.dump_nav_menu_id:
getCurrentTopWebView().debugDump();
break;
case R.id.dump_counters_menu_id:
getCurrentTopWebView().dumpV8Counters();
break;
case R.id.zoom_in_menu_id:
getCurrentTopWebView().zoomIn();
break;
case R.id.zoom_out_menu_id:
getCurrentTopWebView().zoomOut();
break;
case R.id.view_downloads_menu_id:
viewDownloads();
break;
case R.id.window_one_menu_id:
case R.id.window_two_menu_id:
case R.id.window_three_menu_id:
case R.id.window_four_menu_id:
case R.id.window_five_menu_id:
case R.id.window_six_menu_id:
case R.id.window_seven_menu_id:
case R.id.window_eight_menu_id:
{
int menuid = item.getItemId();
for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
Tab desiredTab = mTabControl.getTab(id);
if (desiredTab != null &&
desiredTab != mTabControl.getCurrentTab()) {
switchToTab(id);
}
break;
}
}
}
break;
default:
return false;
}
mCanChord = false;
return true;
}
|
diff --git a/Slick/src/org/newdawn/slick/Animation.java b/Slick/src/org/newdawn/slick/Animation.java
index eb81ff4..c42c475 100644
--- a/Slick/src/org/newdawn/slick/Animation.java
+++ b/Slick/src/org/newdawn/slick/Animation.java
@@ -1,614 +1,615 @@
package org.newdawn.slick;
import java.util.ArrayList;
import org.lwjgl.Sys;
import org.newdawn.slick.util.Log;
/**
* A utility to hold and render animations
*
* @author kevin
* @author DeX (speed updates)
*/
public class Animation implements Renderable {
/** The list of frames to render in this animation */
private ArrayList frames = new ArrayList();
/** The frame currently being displayed */
private int currentFrame = -1;
/** The time the next frame change should take place */
private long nextChange = 0;
/** True if the animation is stopped */
private boolean stopped = false;
/** The time left til the next frame */
private long timeLeft;
/** The current speed of the animation */
private float speed = 1.0f;
/** The frame to stop at */
private int stopAt = -2;
/** The last time the frame was automagically updated */
private long lastUpdate;
/** True if this is the first update */
private boolean firstUpdate = true;
/** True if we should auto update the animation - default true */
private boolean autoUpdate = true;
/** The direction the animation is running */
private int direction = 1;
/** True if the animation in ping ponging back and forth */
private boolean pingPong;
/** True if the animation should loop (default) */
private boolean loop = true;
/**
* Create an empty animation
*/
public Animation() {
this(true);
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param duration The duration to show each frame
*/
public Animation(Image[] frames, int duration) {
this(frames, duration, true);
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param durations The duration to show each frame
*/
public Animation(Image[] frames, int[] durations) {
this(frames, durations, true);
}
/**
* Create an empty animation
*
* @param autoUpdate True if this animation should automatically update. This means that the
* current frame will be caculated based on the time between renders
*/
public Animation(boolean autoUpdate) {
currentFrame = 0;
this.autoUpdate = autoUpdate;
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param duration The duration to show each frame
* @param autoUpdate True if this animation should automatically update. This means that the
* current frame will be caculated based on the time between renders
*/
public Animation(Image[] frames, int duration, boolean autoUpdate) {
for (int i=0;i<frames.length;i++) {
addFrame(frames[i], duration);
}
currentFrame = 0;
this.autoUpdate = autoUpdate;
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param durations The duration to show each frame
* @param autoUpdate True if this animation should automatically update. This means that the
* current frame will be caculated based on the time between renders
*/
public Animation(Image[] frames, int[] durations, boolean autoUpdate) {
this.autoUpdate = autoUpdate;
if (frames.length != durations.length) {
throw new RuntimeException("There must be one duration per frame");
}
for (int i=0;i<frames.length;i++) {
addFrame(frames[i], durations[i]);
}
currentFrame = 0;
}
/**
* Create a new animation based on the sprite from a sheet. It assumed that
* the sprites are organised on horizontal scan lines and that every sprite
* in the sheet should be used.
*
* @param frames The sprite sheet containing the frames
* @param duration The duration each frame should be displayed for
*/
public Animation(SpriteSheet frames, int duration) {
this(frames, 0,0,frames.getHorizontalCount()-1,frames.getVerticalCount()-1,true,duration,true);
}
/**
* Create a new animation based on a selection of sprites from a sheet
*
* @param frames The sprite sheet containing the frames
* @param duration The duration each frame should be displayed for
* @param x1 The x coordinate of the first sprite from the sheet to appear in the animation
* @param y1 The y coordinate of the first sprite from the sheet to appear in the animation
* @param x2 The x coordinate of the last sprite from the sheet to appear in the animation
* @param y2 The y coordinate of the last sprite from the sheet to appear in the animation
* @param horizontalScan True if the sprites are arranged in hoizontal scan lines. Otherwise
* vertical is assumed
* @param autoUpdate True if this animation should automatically update based on the render times
*/
public Animation(SpriteSheet frames, int x1, int y1, int x2, int y2, boolean horizontalScan, int duration, boolean autoUpdate) {
this.autoUpdate = autoUpdate;
if (!horizontalScan) {
for (int x=x1;x<=x2;x++) {
for (int y=y1;y<=y2;y++) {
addFrame(frames.getSprite(x, y), duration);
}
}
} else {
for (int y=y1;y<=y2;y++) {
for (int x=x1;x<=x2;x++) {
addFrame(frames.getSprite(x, y), duration);
}
}
}
}
/**
* Indicate if this animation should automatically update based on the
* time between renders or if it should need updating via the update()
* method.
*
* @param auto True if this animation should automatically update
*/
public void setAutoUpdate(boolean auto) {
this.autoUpdate = auto;
}
/**
* Indicate if this animation should ping pong back and forth
*
* @param pingPong True if the animation should ping pong
*/
public void setPingPong(boolean pingPong) {
this.pingPong = pingPong;
}
/**
* Check if this animation has stopped (either explictly or because it's reached its target frame)
*
* @see #stopAt
* @return True if the animation has stopped
*/
public boolean isStopped() {
return stopped;
}
/**
* Adjust the overall speed of the animation.
*
* @param spd The speed to run the animation. Default: 1.0
*/
public void setSpeed(float spd) {
if (spd > 0) {
// Adjust nextChange
nextChange = (long) (nextChange * speed / spd);
speed = spd;
}
}
/**
* Returns the current speed of the animation.
*
* @return The speed this animation is being played back at
*/
public float getSpeed() {
return speed;
}
/**
* Stop the animation
*/
public void stop() {
if (frames.size() == 0) {
return;
}
timeLeft = nextChange;
stopped = true;
}
/**
* Start the animation playing again
*/
public void start() {
if (!stopped) {
return;
}
if (frames.size() == 0) {
return;
}
stopped = false;
nextChange = timeLeft;
}
/**
* Restart the animation from the beginning
*/
public void restart() {
if (!stopped) {
return;
}
if (frames.size() == 0) {
return;
}
stopped = false;
currentFrame = 0;
nextChange = (int) (((Frame) frames.get(0)).duration / speed);
}
/**
* Add animation frame to the animation
*
* @param frame The image to display for the frame
* @param duration The duration to display the frame for
*/
public void addFrame(Image frame, int duration) {
if (duration == 0) {
Log.error("Invalid duration: "+duration);
throw new RuntimeException("Invalid duration: "+duration);
}
if (frames.isEmpty()) {
nextChange = (int) (duration / speed);
}
frames.add(new Frame(frame, duration));
currentFrame = 0;
}
/**
* Draw the animation to the screen
*/
public void draw() {
draw(0,0);
}
/**
* Draw the animation at a specific location
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
*/
public void draw(float x,float y) {
draw(x,y,getWidth(),getHeight());
}
/**
* Draw the animation at a specific location
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param filter The filter to apply
*/
public void draw(float x,float y, Color filter) {
draw(x,y,getWidth(),getHeight(), filter);
}
/**
* Draw the animation
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param width The width to draw the animation at
* @param height The height to draw the animation at
*/
public void draw(float x,float y,float width,float height) {
draw(x,y,width,height,Color.white);
}
/**
* Draw the animation
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param width The width to draw the animation at
* @param height The height to draw the animation at
* @param col The colour filter to use
*/
public void draw(float x,float y,float width,float height, Color col) {
if (frames.size() == 0) {
return;
}
if (autoUpdate) {
long now = getTime();
long delta = now - lastUpdate;
if (firstUpdate) {
delta = 0;
firstUpdate = false;
}
lastUpdate = now;
nextFrame(delta);
}
Frame frame = (Frame) frames.get(currentFrame);
frame.image.draw(x,y,width,height, col);
}
/**
* Get the width of the current frame
*
* @return The width of the current frame
*/
public int getWidth() {
return ((Frame) frames.get(currentFrame)).image.getWidth();
}
/**
* Get the height of the current frame
*
* @return The height of the current frame
*/
public int getHeight() {
return ((Frame) frames.get(currentFrame)).image.getHeight();
}
/**
* Draw the animation
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param width The width to draw the animation at
* @param height The height to draw the animation at
*/
public void drawFlash(float x,float y,float width,float height) {
drawFlash(x,y,width,height, Color.white);
}
/**
* Draw the animation
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param width The width to draw the animation at
* @param height The height to draw the animation at
* @param col The colour for the flash
*/
public void drawFlash(float x,float y,float width,float height, Color col) {
if (frames.size() == 0) {
return;
}
if (autoUpdate) {
long now = getTime();
long delta = now - lastUpdate;
if (firstUpdate) {
delta = 0;
firstUpdate = false;
}
lastUpdate = now;
nextFrame(delta);
}
Frame frame = (Frame) frames.get(currentFrame);
frame.image.drawFlash(x,y,width,height,col);
}
/**
* Update the animation cycle without draw the image, useful
* for keeping two animations in sync
*
* @deprecated
*/
public void updateNoDraw() {
if (autoUpdate) {
long now = getTime();
long delta = now - lastUpdate;
if (firstUpdate) {
delta = 0;
firstUpdate = false;
}
lastUpdate = now;
nextFrame(delta);
}
}
/**
* Update the animation, note that this will have odd effects if auto update
* is also turned on
*
* @see #autoUpdate
* @param delta The amount of time thats passed since last update
*/
public void update(long delta) {
nextFrame(delta);
}
/**
* Get the index of the current frame
*
* @return The index of the current frame
*/
public int getFrame() {
return currentFrame;
}
/**
* Set the current frame to be rendered
*
* @param index The index of the frame to rendered
*/
public void setCurrentFrame(int index) {
currentFrame = index;
}
/**
* Get the image assocaited with a given frame index
*
* @param index The index of the frame image to retrieve
* @return The image of the specified animation frame
*/
public Image getImage(int index) {
Frame frame = (Frame) frames.get(index);
return frame.image;
}
/**
* Get the number of frames that are in the animation
*
* @return The number of frames that are in the animation
*/
public int getFrameCount() {
return frames.size();
}
/**
* Get the image associated with the current animation frame
*
* @return The image associated with the current animation frame
*/
public Image getCurrentFrame() {
Frame frame = (Frame) frames.get(currentFrame);
return frame.image;
}
/**
* Check if we need to move to the next frame
*
* @param delta The amount of time thats passed since last update
*/
private void nextFrame(long delta) {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
nextChange -= delta;
while (nextChange < 0 && (!stopped)) {
if (currentFrame == stopAt) {
stopped = true;
break;
}
if ((currentFrame == frames.size() - 1) && (!loop)) {
+ stopped = true;
break;
}
currentFrame = (currentFrame + direction) % frames.size();
if (pingPong) {
if ((currentFrame == 0) || (currentFrame == frames.size()-1)) {
direction = -direction;
}
}
int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed);
nextChange = nextChange + realDuration;
}
}
/**
* Indicate if this animation should loop or stop at the last frame
*
* @param loop True if this animation should loop (true = default)
*/
public void setLooping(boolean loop) {
this.loop = loop;
}
/**
* Get the accurate system time
*
* @return The system time in milliseconds
*/
private long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
/**
* Indicate the animation should stop when it reaches the specified
* frame index (note, not frame number but index in the animation
*
* @param frameIndex The index of the frame to stop at
*/
public void stopAt(int frameIndex) {
stopAt = frameIndex;
}
/**
* Get the duration of a particular frame
*
* @param index The index of the given frame
* @return The duration in (ms) of the given frame
*/
public int getDuration(int index) {
return ((Frame) frames.get(index)).duration;
}
/**
* Set the duration of the given frame
*
* @param index The index of the given frame
* @param duration The duration in (ms) for the given frame
*/
public void setDuration(int index, int duration) {
((Frame) frames.get(index)).duration = duration;
}
/**
* Get the durations of all the frames in this animation
*
* @return The durations of all the frames in this animation
*/
public int[] getDurations() {
int[] durations = new int[frames.size()];
for (int i=0;i<frames.size();i++) {
durations[i] = getDuration(i);
}
return durations;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
String res = "[Animation ("+frames.size()+") ";
for (int i=0;i<frames.size();i++) {
Frame frame = (Frame) frames.get(i);
res += frame.duration+",";
}
res += "]";
return res;
}
/**
* A single frame within the animation
*
* @author kevin
*/
private class Frame {
/** The image to display for this frame */
public Image image;
/** The duration to display the image fro */
public int duration;
/**
* Create a new animation frame
*
* @param image The image to display for the frame
* @param duration The duration in millisecond to display the image for
*/
public Frame(Image image, int duration) {
this.image = image;
this.duration = duration;
}
}
}
| true | true | private void nextFrame(long delta) {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
nextChange -= delta;
while (nextChange < 0 && (!stopped)) {
if (currentFrame == stopAt) {
stopped = true;
break;
}
if ((currentFrame == frames.size() - 1) && (!loop)) {
break;
}
currentFrame = (currentFrame + direction) % frames.size();
if (pingPong) {
if ((currentFrame == 0) || (currentFrame == frames.size()-1)) {
direction = -direction;
}
}
int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed);
nextChange = nextChange + realDuration;
}
}
| private void nextFrame(long delta) {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
nextChange -= delta;
while (nextChange < 0 && (!stopped)) {
if (currentFrame == stopAt) {
stopped = true;
break;
}
if ((currentFrame == frames.size() - 1) && (!loop)) {
stopped = true;
break;
}
currentFrame = (currentFrame + direction) % frames.size();
if (pingPong) {
if ((currentFrame == 0) || (currentFrame == frames.size()-1)) {
direction = -direction;
}
}
int realDuration = (int) (((Frame) frames.get(currentFrame)).duration / speed);
nextChange = nextChange + realDuration;
}
}
|
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
index 001977d1e..db6f08786 100644
--- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
+++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFNodeExecContext.java
@@ -1,1591 +1,1595 @@
/*******************************************************************************
* Copyright (c) 2007, 2012 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.ui.model;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenCountUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IHasChildrenUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.ILabelUpdate;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IModelDelta;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerInputUpdate;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.memory.IMemoryRenderingSite;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.tcf.debug.ui.ITCFDebugUIConstants;
import org.eclipse.tcf.debug.ui.ITCFExecContext;
import org.eclipse.tcf.internal.debug.model.TCFContextState;
import org.eclipse.tcf.internal.debug.model.TCFFunctionRef;
import org.eclipse.tcf.internal.debug.model.TCFSourceRef;
import org.eclipse.tcf.internal.debug.model.TCFSymFileRef;
import org.eclipse.tcf.internal.debug.ui.ColorCache;
import org.eclipse.tcf.internal.debug.ui.ImageCache;
import org.eclipse.tcf.protocol.IToken;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.services.ILineNumbers;
import org.eclipse.tcf.services.IMemory;
import org.eclipse.tcf.services.IMemoryMap;
import org.eclipse.tcf.services.IProcesses;
import org.eclipse.tcf.services.IRunControl;
import org.eclipse.tcf.services.ISymbols;
import org.eclipse.tcf.util.TCFDataCache;
import org.eclipse.ui.IWorkbenchPart;
public class TCFNodeExecContext extends TCFNode implements ISymbolOwner, ITCFExecContext {
private final TCFChildrenExecContext children_exec;
private final TCFChildrenStackTrace children_stack;
private final TCFChildrenRegisters children_regs;
private final TCFChildrenExpressions children_exps;
private final TCFChildrenHoverExpressions children_hover_exps;
private final TCFChildrenLogExpressions children_log_exps;
private final TCFChildrenModules children_modules;
private final TCFChildrenContextQuery children_query;
private final TCFData<IMemory.MemoryContext> mem_context;
private final TCFData<IRunControl.RunControlContext> run_context;
private final TCFData<MemoryRegion[]> memory_map;
private final TCFData<IProcesses.ProcessContext> prs_context;
private final TCFData<TCFContextState> state;
private final TCFData<BigInteger> address; // Current PC as BigInteger
private final TCFData<Collection<Map<String,Object>>> signal_list;
private final TCFData<SignalMask[]> signal_mask;
private final TCFData<TCFNodeExecContext> memory_node;
private final TCFData<TCFNodeExecContext> symbols_node;
private final TCFData<String> full_name;
private LinkedHashMap<BigInteger,TCFDataCache<TCFSymFileRef>> syms_info_lookup_cache;
private LinkedHashMap<BigInteger,TCFDataCache<TCFSourceRef>> line_info_lookup_cache;
private LinkedHashMap<BigInteger,TCFDataCache<TCFFunctionRef>> func_info_lookup_cache;
private LookupCacheTimer lookup_cache_timer;
private int mem_seq_no;
private int exe_seq_no;
private static final TCFNode[] empty_node_array = new TCFNode[0];
/*
* LookupCacheTimer is executed periodically to dispose least-recently
* accessed entries in line_info_lookup_cache and func_info_lookup_cache.
* The timer disposes itself when both caches become empty.
*/
private class LookupCacheTimer implements Runnable {
LookupCacheTimer() {
Protocol.invokeLater(4000, this);
}
public void run() {
if (isDisposed()) return;
if (syms_info_lookup_cache != null) {
BigInteger addr = syms_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = syms_info_lookup_cache.get(addr);
if (!cache.isPending()) {
syms_info_lookup_cache.remove(addr).dispose();
if (syms_info_lookup_cache.size() == 0) syms_info_lookup_cache = null;
}
}
if (line_info_lookup_cache != null) {
BigInteger addr = line_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = line_info_lookup_cache.get(addr);
if (!cache.isPending()) {
line_info_lookup_cache.remove(addr).dispose();
if (line_info_lookup_cache.size() == 0) line_info_lookup_cache = null;
}
}
if (func_info_lookup_cache != null) {
BigInteger addr = func_info_lookup_cache.keySet().iterator().next();
TCFDataCache<?> cache = func_info_lookup_cache.get(addr);
if (!cache.isPending()) {
func_info_lookup_cache.remove(addr).dispose();
if (func_info_lookup_cache.size() == 0) func_info_lookup_cache = null;
}
}
if (syms_info_lookup_cache == null && line_info_lookup_cache == null && func_info_lookup_cache == null) {
lookup_cache_timer = null;
}
else {
Protocol.invokeLater(2500, this);
}
}
}
public static class ChildrenStateInfo {
public boolean running;
public boolean suspended;
public boolean not_active;
public boolean breakpoint;
}
private final Map<String,TCFNodeSymbol> symbols = new HashMap<String,TCFNodeSymbol>();
private int resumed_cnt;
private boolean resume_pending;
private boolean resumed_by_action;
private TCFNode[] last_stack_trace;
private TCFNode[] last_children_list;
private String last_label;
private ImageDescriptor last_image;
private ChildrenStateInfo last_children_state_info;
private boolean delayed_children_list_delta;
/**
* Wrapper class for IMemoryMap.MemoryRegion.
* The class help to search memory region by address by
* providing contains() method.
*/
public static class MemoryRegion {
private final BigInteger addr_start;
private final BigInteger addr_end;
public final IMemoryMap.MemoryRegion region;
private MemoryRegion(IMemoryMap.MemoryRegion region) {
this.region = region;
Number addr = region.getAddress();
Number size = region.getSize();
if (addr == null || size == null) {
addr_start = null;
addr_end = null;
}
else {
addr_start = JSON.toBigInteger(addr);
addr_end = addr_start.add(JSON.toBigInteger(size));
}
}
public boolean contains(BigInteger addr) {
return
addr_start != null && addr_end != null &&
addr_start.compareTo(addr) <= 0 &&
addr_end.compareTo(addr) > 0;
}
@Override
public String toString() {
return region.getProperties().toString();
}
}
public static class SignalMask {
protected Map<String,Object> props;
protected boolean dont_stop;
protected boolean dont_pass;
protected boolean pending;
public Number getIndex() {
return (Number)props.get(IProcesses.SIG_INDEX);
}
public Number getCode() {
return (Number)props.get(IProcesses.SIG_CODE);
}
public Map<String,Object> getProperties() {
return props;
}
public boolean isDontStop() {
return dont_stop;
}
public boolean isDontPass() {
return dont_pass;
}
public boolean isPending() {
return pending;
}
@Override
public String toString() {
StringBuffer bf = new StringBuffer();
bf.append("[attrs=");
bf.append(props.toString());
if (dont_stop) bf.append(",don't stop");
if (dont_pass) bf.append(",don't pass");
if (pending) bf.append(",pending");
bf.append(']');
return bf.toString();
}
}
TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
+ String name = lst.get(i - 1);
+ boolean quote = name.indexOf('/') >= 0;
bf.append('/');
- bf.append(lst.get(i - 1));
+ if (quote) bf.append('"');
+ bf.append(name);
+ if (quote) bf.append('"');
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
@Override
void dispose() {
assert !isDisposed();
ArrayList<TCFNodeSymbol> l = new ArrayList<TCFNodeSymbol>(symbols.values());
for (TCFNodeSymbol s : l) s.dispose();
assert symbols.size() == 0;
super.dispose();
}
void setMemSeqNo(int no) {
mem_seq_no = no;
}
void setExeSeqNo(int no) {
exe_seq_no = no;
}
TCFChildren getHoverExpressionCache(String expression) {
children_hover_exps.setExpression(expression);
return children_hover_exps;
}
public TCFChildrenLogExpressions getLogExpressionCache() {
return children_log_exps;
}
void setRunContext(IRunControl.RunControlContext ctx) {
run_context.reset(ctx);
}
void setProcessContext(IProcesses.ProcessContext ctx) {
prs_context.reset(ctx);
}
void setMemoryContext(IMemory.MemoryContext ctx) {
mem_context.reset(ctx);
}
public TCFDataCache<TCFNodeExecContext> getSymbolsNode() {
return symbols_node;
}
public TCFDataCache<TCFNodeExecContext> getMemoryNode() {
return memory_node;
}
public TCFDataCache<MemoryRegion[]> getMemoryMap() {
return memory_map;
}
public TCFDataCache<Collection<Map<String,Object>>> getSignalList() {
return signal_list;
}
public TCFDataCache<SignalMask[]> getSignalMask() {
return signal_mask;
}
public TCFDataCache<TCFSymFileRef> getSymFileInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFSymFileRef> ref_cache;
if (syms_info_lookup_cache != null) {
ref_cache = syms_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ISymbols syms = launch.getService(ISymbols.class);
if (syms == null) return null;
if (syms_info_lookup_cache == null) {
syms_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFSymFileRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
syms_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFSymFileRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFSymFileRef ref_data = new TCFSymFileRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = syms.getSymFileInfo(ref_data.context_id, addr, new ISymbols.DoneGetSymFileInfo() {
public void doneGetSymFileInfo(IToken token, Exception error, Map<String,Object> props) {
ref_data.address = addr;
ref_data.error = error;
ref_data.props = props;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
public TCFDataCache<TCFSourceRef> getLineInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFSourceRef> ref_cache;
if (line_info_lookup_cache != null) {
ref_cache = line_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ILineNumbers ln = launch.getService(ILineNumbers.class);
if (ln == null) return null;
final BigInteger n0 = addr;
final BigInteger n1 = n0.add(BigInteger.valueOf(1));
if (line_info_lookup_cache == null) {
line_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFSourceRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
line_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFSourceRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFSourceRef ref_data = new TCFSourceRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = ln.mapToSource(id, n0, n1, new ILineNumbers.DoneMapToSource() {
public void doneMapToSource(IToken token, Exception error, ILineNumbers.CodeArea[] areas) {
ref_data.address = addr;
if (error == null && areas != null && areas.length > 0) {
for (ILineNumbers.CodeArea area : areas) {
BigInteger a0 = JSON.toBigInteger(area.start_address);
BigInteger a1 = JSON.toBigInteger(area.end_address);
if (n0.compareTo(a0) >= 0 && n0.compareTo(a1) < 0) {
if (ref_data.area == null || area.start_line < ref_data.area.start_line) {
if (area.start_address != a0 || area.end_address != a1) {
area = new ILineNumbers.CodeArea(area.directory, area.file,
area.start_line, area.start_column,
area.end_line, area.end_column,
a0, a1, area.isa,
area.is_statement, area.basic_block,
area.prologue_end, area.epilogue_begin);
}
ref_data.area = area;
}
}
}
}
ref_data.error = error;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
public TCFDataCache<TCFFunctionRef> getFuncInfo(final BigInteger addr) {
if (isDisposed()) return null;
TCFDataCache<TCFFunctionRef> ref_cache;
if (func_info_lookup_cache != null) {
ref_cache = func_info_lookup_cache.get(addr);
if (ref_cache != null) return ref_cache;
}
final ISymbols syms = launch.getService(ISymbols.class);
if (syms == null) return null;
if (func_info_lookup_cache == null) {
func_info_lookup_cache = new LinkedHashMap<BigInteger,TCFDataCache<TCFFunctionRef>>(11, 0.75f, true);
if (lookup_cache_timer == null) lookup_cache_timer = new LookupCacheTimer();
}
func_info_lookup_cache.put(addr, ref_cache = new TCFData<TCFFunctionRef>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!memory_node.validate(this)) return false;
IMemory.MemoryContext mem_data = null;
TCFNodeExecContext mem = memory_node.getData();
if (mem != null) {
TCFDataCache<IMemory.MemoryContext> mem_cache = mem.mem_context;
if (!mem_cache.validate(this)) return false;
mem_data = mem_cache.getData();
}
final TCFFunctionRef ref_data = new TCFFunctionRef();
if (mem_data != null) {
ref_data.context_id = mem_data.getID();
ref_data.address_size = mem_data.getAddressSize();
}
command = syms.findByAddr(id, addr, new ISymbols.DoneFind() {
public void doneFind(IToken token, Exception error, String symbol_id) {
ref_data.address = addr;
ref_data.error = error;
ref_data.symbol_id = symbol_id;
set(token, null, ref_data);
}
});
return false;
}
});
return ref_cache;
}
private void clearLookupCaches() {
if (syms_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFSymFileRef>> i = syms_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFSymFileRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (syms_info_lookup_cache.size() == 0) syms_info_lookup_cache = null;
}
if (line_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFSourceRef>> i = line_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFSourceRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (line_info_lookup_cache.size() == 0) line_info_lookup_cache = null;
}
if (func_info_lookup_cache != null) {
Iterator<TCFDataCache<TCFFunctionRef>> i = func_info_lookup_cache.values().iterator();
while (i.hasNext()) {
TCFDataCache<TCFFunctionRef> cache = i.next();
if (cache.isPending()) continue;
cache.dispose();
i.remove();
}
if (func_info_lookup_cache.size() == 0) func_info_lookup_cache = null;
}
}
@Override
public TCFNode getParent(IPresentationContext ctx) {
assert Protocol.isDispatchThread();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(ctx.getId())) {
Set<String> ids = launch.getContextFilter();
if (ids != null) {
if (ids.contains(id)) return model.getRootNode();
if (parent instanceof TCFNodeLaunch) return null;
}
}
return parent;
}
public TCFDataCache<IRunControl.RunControlContext> getRunContext() {
return run_context;
}
public TCFDataCache<IProcesses.ProcessContext> getProcessContext() {
return prs_context;
}
public TCFDataCache<IMemory.MemoryContext> getMemoryContext() {
return mem_context;
}
public TCFDataCache<BigInteger> getAddress() {
return address;
}
public TCFDataCache<TCFContextState> getState() {
return state;
}
public TCFChildrenStackTrace getStackTrace() {
return children_stack;
}
public TCFChildren getRegisters() {
return children_regs;
}
public TCFChildren getModules() {
return children_modules;
}
public TCFChildren getChildren() {
return children_exec;
}
public TCFNodeStackFrame getLastTopFrame() {
if (!resume_pending) return null;
if (last_stack_trace == null || last_stack_trace.length == 0) return null;
return (TCFNodeStackFrame)last_stack_trace[0];
}
public TCFNodeStackFrame getViewBottomFrame() {
if (last_stack_trace == null || last_stack_trace.length == 0) return null;
return (TCFNodeStackFrame)last_stack_trace[last_stack_trace.length - 1];
}
/**
* Get context full name - including all ancestor names.
* Return context ID if the context does not have a name.
* @return cache item with the context full name.
*/
public TCFDataCache<String> getFullName() {
return full_name;
}
public void addSymbol(TCFNodeSymbol s) {
assert symbols.get(s.id) == null;
symbols.put(s.id, s);
}
public void removeSymbol(TCFNodeSymbol s) {
assert symbols.get(s.id) == s;
symbols.remove(s.id);
}
/**
* Return true if this context cannot be accessed because it is not active.
* Not active means the target is suspended, but this context is not one that is
* currently scheduled to run on a target CPU, and the debuggers don't support
* access to register values and other properties of such contexts.
*/
public boolean isNotActive() {
TCFContextState state_data = state.getData();
if (state_data != null) return state_data.isNotActive();
return false;
}
private boolean okToShowLastStack() {
return resume_pending && last_stack_trace != null;
}
private boolean okToHideStack() {
TCFContextState state_data = state.getData();
if (state_data == null) return true;
if (!state_data.is_suspended) return true;
if (state_data.isNotActive()) return true;
return false;
}
@Override
protected boolean getData(IChildrenCountUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
result.setChildCount(last_stack_trace.length);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
result.setChildCount(0);
return true;
}
children = children_stack;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
result.setChildCount(last_children_list.length);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children != null) {
if (!children.validate(done)) return false;
if (children == children_stack) last_stack_trace = children_stack.toArray();
if (children == children_exec) last_children_list = children_exec.toArray();
result.setChildCount(children.size());
}
else {
result.setChildCount(0);
}
return true;
}
private void setResultChildren(IChildrenUpdate result, TCFNode[] arr) {
int offset = 0;
int r_offset = result.getOffset();
int r_length = result.getLength();
for (TCFNode n : arr) {
if (offset >= r_offset && offset < r_offset + r_length) {
result.setChild(n, offset);
}
offset++;
}
}
@Override
protected boolean getData(IChildrenUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
setResultChildren(result, last_stack_trace);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
return true;
}
children = children_stack;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
setResultChildren(result, last_children_list);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children == null) return true;
if (children == children_stack) {
if (!children.validate(done)) return false;
last_stack_trace = children_stack.toArray();
}
if (children == children_exec) {
if (!children.validate(done)) return false;
last_children_list = children_exec.toArray();
}
return children.getData(result, done);
}
@Override
protected boolean getData(IHasChildrenUpdate result, Runnable done) {
TCFChildren children = null;
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) {
if (okToShowLastStack()) {
result.setHasChilren(last_stack_trace.length > 0);
return true;
}
if (!state.validate(done)) return false;
if (okToHideStack()) {
last_stack_trace = empty_node_array;
result.setHasChilren(false);
return true;
}
Boolean has_children = children_stack.checkHasChildren(done);
if (has_children == null) return false;
result.setHasChilren(has_children);
return true;
}
else {
if (!model.getAutoChildrenListUpdates() && last_children_list != null) {
result.setHasChilren(last_children_list.length > 0);
return true;
}
children = children_exec;
}
}
else if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id)) {
children = children_regs;
}
else if (IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) children = children_exps;
}
else if (TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (!run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && ctx.hasState()) children = children_hover_exps;
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
if (!mem_context.validate(done)) return false;
IMemory.MemoryContext ctx = mem_context.getData();
if (ctx != null) children = children_modules;
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
if (!children_query.setQuery(result, done)) return false;
children = children_query;
}
if (children != null) {
if (!children.validate(done)) return false;
if (children == children_stack) last_stack_trace = children_stack.toArray();
if (children == children_exec) last_children_list = children_exec.toArray();
result.setHasChilren(children.size() > 0);
}
else {
result.setHasChilren(false);
}
return true;
}
@Override
protected boolean getData(ILabelUpdate result, Runnable done) {
if (!run_context.validate(done)) return false;
String image_name = null;
boolean suspended_by_bp = false;
StringBuffer label = new StringBuffer();
Throwable error = run_context.getError();
if (error != null) {
result.setForeground(ColorCache.rgb_error, 0);
label.append(id);
label.append(": ");
label.append(TCFModel.getErrorMessage(error, false));
}
else {
String view_id = result.getPresentationContext().getId();
if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
TCFChildrenContextQuery.Descendants des = TCFChildrenContextQuery.getDescendants(this, result, done);
if (des == null) return false;
if (des.map != null && des.map.size() > 0) {
label.append("(");
label.append(des.map.size());
label.append(") ");
}
if (!des.include_parent) result.setForeground(ColorCache.rgb_disabled, 0);
}
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null) {
label.append(id);
}
else {
String nm = ctx.getName();
if (nm == null && !ctx.hasState()) {
String prs = ctx.getProcessID();
if (prs != null) {
if (!prs_context.validate(done)) return false;
IProcesses.ProcessContext pctx = prs_context.getData();
if (pctx != null) nm = pctx.getName();
}
}
label.append(nm != null ? nm : id);
Object info = ctx.getProperties().get("AdditionalInfo");
if (info != null) label.append(info.toString());
if (TCFModel.ID_PINNED_VIEW.equals(view_id) || ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
image_name = ctx.hasState() ? ImageCache.IMG_THREAD_UNKNOWN_STATE : ImageCache.IMG_PROCESS_RUNNING;
}
else if (ctx.hasState()) {
// Thread
if (resume_pending && resumed_by_action || model.getActiveAction(id) != null) {
if (!state.validate(done)) return false;
TCFContextState state_data = state.getData();
image_name = ImageCache.IMG_THREAD_UNKNOWN_STATE;
if (state_data != null && !state_data.is_suspended) {
if (state_data.isReversing()) {
image_name = ImageCache.IMG_THREAD_REVERSING;
label.append(" (Reversing)");
}
else {
image_name = ImageCache.IMG_THREAD_RUNNNIG;
label.append(" (Running)");
}
}
if (resume_pending && last_label != null) {
result.setImageDescriptor(ImageCache.getImageDescriptor(image_name), 0);
result.setLabel(last_label, 0);
return true;
}
}
else if (resume_pending && last_label != null && last_image != null) {
result.setImageDescriptor(last_image, 0);
result.setLabel(last_label, 0);
return true;
}
else {
if (!state.validate(done)) return false;
TCFContextState state_data = state.getData();
if (isNotActive()) {
image_name = ImageCache.IMG_THREAD_NOT_ACTIVE;
label.append(" (Not active)");
if (state_data.suspend_reason != null && !state_data.suspend_reason.equals(IRunControl.REASON_USER_REQUEST)) {
label.append(" - ");
label.append(state_data.suspend_reason);
}
}
else {
image_name = ImageCache.IMG_THREAD_UNKNOWN_STATE;
if (state_data != null) {
if (!state_data.is_suspended) {
if (state_data.isReversing()) {
image_name = ImageCache.IMG_THREAD_REVERSING;
label.append(" (Reversing)");
}
else {
image_name = ImageCache.IMG_THREAD_RUNNNIG;
label.append(" (Running)");
}
}
else {
image_name = ImageCache.IMG_THREAD_SUSPENDED;
String s = null;
String r = model.getContextActionResult(id);
if (r == null) {
r = state_data.suspend_reason;
if (state_data.suspend_params != null) {
s = (String)state_data.suspend_params.get(IRunControl.STATE_SIGNAL_DESCRIPTION);
if (s == null) s = (String)state_data.suspend_params.get(IRunControl.STATE_SIGNAL_NAME);
}
}
suspended_by_bp = IRunControl.REASON_BREAKPOINT.equals(r);
if (r == null) r = "Suspended";
if (s != null) r += ": " + s;
label.append(" (");
label.append(r);
if (state_data.suspend_params != null) {
String prs = (String)state_data.suspend_params.get("Context");
if (prs != null) {
label.append(", ");
label.append(prs);
}
String cpu = (String)state_data.suspend_params.get("CPU");
if (cpu != null) {
label.append(", ");
label.append(cpu);
}
}
label.append(")");
}
}
}
}
last_children_state_info = null;
}
else {
// Thread container (process)
ChildrenStateInfo i = new ChildrenStateInfo();
if (!hasSuspendedChildren(i, done)) return false;
if (i.suspended) image_name = ImageCache.IMG_PROCESS_SUSPENDED;
else image_name = ImageCache.IMG_PROCESS_RUNNING;
suspended_by_bp = i.breakpoint;
last_children_state_info = i;
}
}
}
last_image = ImageCache.getImageDescriptor(image_name);
if (suspended_by_bp) last_image = ImageCache.addOverlay(last_image, ImageCache.IMG_BREAKPOINT_OVERLAY);
result.setImageDescriptor(last_image, 0);
result.setLabel(last_label = label.toString(), 0);
return true;
}
@Override
protected boolean getData(IViewerInputUpdate result, Runnable done) {
result.setInputElement(this);
String view_id = result.getPresentationContext().getId();
if (IDebugUIConstants.ID_VARIABLE_VIEW.equals(view_id)) {
if (!children_stack.validate(done)) return false;
TCFNodeStackFrame frame = children_stack.getTopFrame();
if (frame != null) result.setInputElement(frame);
}
else if (IDebugUIConstants.ID_MODULE_VIEW.equals(view_id)) {
// TODO: need to post view input delta when memory context changes
TCFDataCache<TCFNodeExecContext> mem = model.searchMemoryContext(this);
if (mem == null) return true;
if (!mem.validate(done)) return false;
if (mem.getData() == null) return true;
result.setInputElement(mem.getData());
}
return true;
}
@Override
public void refresh(IWorkbenchPart part) {
if (part instanceof IMemoryRenderingSite) {
model.onMemoryChanged(id, false, false);
}
else {
last_children_list = null;
last_children_state_info = null;
last_stack_trace = null;
last_label = null;
last_image = null;
super.refresh(part);
}
}
void postAllChangedDelta() {
postContentChangedDelta();
postStateChangedDelta();
}
void postContextAddedDelta() {
if (parent instanceof TCFNodeExecContext) {
TCFNodeExecContext exe = (TCFNodeExecContext)parent;
ChildrenStateInfo info = exe.last_children_state_info;
if (info != null) {
if (!model.getAutoChildrenListUpdates()) {
// Manual manual updates.
return;
}
if (!info.suspended && !info.not_active && model.getDelayChildrenListUpdates()) {
// Delay content update until a child is suspended.
exe.delayed_children_list_delta = true;
return;
}
}
}
for (TCFModelProxy p : model.getModelProxies()) {
String view_id = p.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
/* Note: should use IModelDelta.INSERTED but it is broken in Eclipse 3.6 */
p.addDelta(this, IModelDelta.ADDED);
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
p.addDelta(parent, IModelDelta.CONTENT);
}
}
}
private void postContextRemovedDelta() {
if (parent instanceof TCFNodeExecContext) {
TCFNodeExecContext exe = (TCFNodeExecContext)parent;
ChildrenStateInfo info = exe.last_children_state_info;
if (info != null) {
if (!model.getAutoChildrenListUpdates()) {
// Manual manual updates.
return;
}
if (!info.suspended && !info.not_active && model.getDelayChildrenListUpdates()) {
// Delay content update until a child is suspended.
exe.delayed_children_list_delta = true;
return;
}
}
}
for (TCFModelProxy p : model.getModelProxies()) {
String view_id = p.getPresentationContext().getId();
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id)) {
p.addDelta(this, IModelDelta.REMOVED);
}
else if (ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) {
p.addDelta(parent, IModelDelta.CONTENT);
}
}
}
private void postContentChangedDelta() {
delayed_children_list_delta = false;
for (TCFModelProxy p : model.getModelProxies()) {
int flags = 0;
String view_id = p.getPresentationContext().getId();
if ( (IDebugUIConstants.ID_DEBUG_VIEW.equals(view_id) ||
ITCFDebugUIConstants.ID_CONTEXT_QUERY_VIEW.equals(view_id)) &&
(launch.getContextActionsCount(id) == 0 || !model.getDelayStackUpdateUtilLastStep()))
{
flags |= IModelDelta.CONTENT;
}
if (IDebugUIConstants.ID_REGISTER_VIEW.equals(view_id) ||
IDebugUIConstants.ID_EXPRESSION_VIEW.equals(view_id) ||
TCFModel.ID_EXPRESSION_HOVER.equals(view_id)) {
if (p.getInput() == this) flags |= IModelDelta.CONTENT;
}
if (flags == 0) continue;
p.addDelta(this, flags);
}
}
private void postAllAndParentsChangedDelta() {
postContentChangedDelta();
TCFNode n = this;
while (n instanceof TCFNodeExecContext) {
TCFNodeExecContext e = (TCFNodeExecContext)n;
if (e.delayed_children_list_delta) e.postContentChangedDelta();
e.postStateChangedDelta();
n = n.parent;
}
}
public void postStateChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.STATE);
}
}
}
private void postModulesChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_MODULE_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.CONTENT);
}
}
}
private void postStackChangedDelta() {
for (TCFModelProxy p : model.getModelProxies()) {
if (IDebugUIConstants.ID_DEBUG_VIEW.equals(p.getPresentationContext().getId())) {
p.addDelta(this, IModelDelta.CONTENT);
}
}
}
void onContextAdded(IRunControl.RunControlContext context) {
model.setDebugViewSelection(this, IRunControl.REASON_USER_REQUEST);
children_exec.onContextAdded(context);
}
void onContextChanged(IRunControl.RunControlContext context) {
assert !isDisposed();
full_name.reset();
run_context.reset(context);
symbols_node.reset();
memory_node.reset();
signal_mask.reset();
if (state.isValid()) {
TCFContextState s = state.getData();
if (s == null || s.is_suspended) state.reset();
}
children_stack.reset();
children_stack.onSourceMappingChange();
children_regs.reset();
children_exec.onAncestorContextChanged();
for (TCFNodeSymbol s : symbols.values()) s.onMemoryMapChanged();
postAllChangedDelta();
}
void onAncestorContextChanged() {
full_name.reset();
}
void onContextAdded(IMemory.MemoryContext context) {
children_exec.onContextAdded(context);
}
void onContextChanged(IMemory.MemoryContext context) {
assert !isDisposed();
clearLookupCaches();
mem_context.reset(context);
for (TCFNodeSymbol s : symbols.values()) s.onMemoryMapChanged();
postAllChangedDelta();
}
void onContextRemoved() {
assert !isDisposed();
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
dispose();
postContextRemovedDelta();
launch.removeContextActions(id);
}
void onExpressionAddedOrRemoved() {
children_exps.cancel();
children_stack.onExpressionAddedOrRemoved();
}
void onContainerSuspended(boolean func_call) {
assert !isDisposed();
if (run_context.isValid()) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && !ctx.hasState()) return;
}
onContextSuspended(null, null, null, func_call);
}
void onContainerResumed() {
assert !isDisposed();
if (run_context.isValid()) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null && !ctx.hasState()) return;
}
onContextResumed();
}
void onContextSuspended(String pc, String reason, Map<String,Object> params, boolean func_call) {
assert !isDisposed();
if (pc != null) {
TCFContextState s = new TCFContextState();
s.is_suspended = true;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
state.reset(s);
}
else {
state.reset();
}
address.reset();
signal_mask.reset();
children_stack.onSuspended(func_call);
children_exps.onSuspended(func_call);
children_hover_exps.onSuspended(func_call);
children_regs.onSuspended(func_call);
if (!func_call) {
children_log_exps.onSuspended();
}
for (TCFNodeSymbol s : symbols.values()) s.onExeStateChange();
if (model.getActiveAction(id) == null) {
boolean update_now = pc != null || resumed_by_action;
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
if (update_now) {
children_stack.postAllChangedDelta();
postAllAndParentsChangedDelta();
}
else {
final int cnt = resumed_cnt;
Protocol.invokeLater(500, new Runnable() {
public void run() {
if (cnt != resumed_cnt) return;
if (isDisposed()) return;
children_stack.postAllChangedDelta();
postAllAndParentsChangedDelta();
}
});
}
}
}
void onContextResumed() {
assert !isDisposed();
state.reset();
if (!resume_pending) {
final int cnt = ++resumed_cnt;
resume_pending = true;
resumed_by_action = model.getActiveAction(id) != null;
if (resumed_by_action) postAllChangedDelta();
Protocol.invokeLater(400, new Runnable() {
public void run() {
if (cnt != resumed_cnt) return;
if (isDisposed()) return;
resume_pending = false;
postAllAndParentsChangedDelta();
model.onContextRunning();
}
});
}
}
void onContextActionDone() {
assert state.isValid();
if (state.getData() == null || state.getData().is_suspended) {
resumed_cnt++;
resume_pending = false;
resumed_by_action = false;
}
postAllChangedDelta();
children_stack.postAllChangedDelta();
}
void onContextException(String msg) {
}
void onMemoryChanged(Number[] addr, long[] size) {
assert !isDisposed();
children_stack.onMemoryChanged();
children_exps.onMemoryChanged();
children_hover_exps.onMemoryChanged();
children_log_exps.onMemoryChanged();
postContentChangedDelta();
}
void onMemoryMapChanged() {
clearLookupCaches();
memory_map.reset();
children_modules.onMemoryMapChanged();
children_stack.onMemoryMapChanged();
children_exps.onMemoryMapChanged();
children_hover_exps.onMemoryMapChanged();
children_log_exps.onMemoryMapChanged();
postContentChangedDelta();
postModulesChangedDelta();
}
void onRegistersChanged() {
children_stack.onRegistersChanged();
postContentChangedDelta();
}
void onRegisterValueChanged() {
if (state.isValid()) {
TCFContextState s = state.getData();
if (s == null || s.is_suspended) state.reset();
}
address.reset();
children_stack.onRegisterValueChanged();
children_exps.onRegisterValueChanged();
children_hover_exps.onRegisterValueChanged();
children_log_exps.onRegisterValueChanged();
postContentChangedDelta();
}
void onPreferencesChanged() {
if (delayed_children_list_delta && !model.getDelayChildrenListUpdates() ||
model.getAutoChildrenListUpdates()) postContentChangedDelta();
children_stack.onPreferencesChanged();
postStackChangedDelta();
}
void riseTraceLimit() {
children_stack.riseTraceLimit();
postStackChangedDelta();
}
public boolean hasSuspendedChildren(ChildrenStateInfo info, Runnable done) {
if (!children_exec.validate(done)) return false;
Map<String,TCFNode> m = children_exec.getData();
if (m == null || m.size() == 0) return true;
for (TCFNode n : m.values()) {
if (!(n instanceof TCFNodeExecContext)) continue;
TCFNodeExecContext e = (TCFNodeExecContext)n;
if (!e.run_context.validate(done)) return false;
IRunControl.RunControlContext ctx = e.run_context.getData();
if (ctx != null && ctx.hasState()) {
TCFDataCache<TCFContextState> state_cache = e.getState();
if (!state_cache.validate(done)) return false;
TCFContextState state_data = state_cache.getData();
if (state_data != null) {
if (!state_data.is_suspended) {
info.running = true;
}
else if (e.isNotActive()) {
info.not_active = true;
}
else {
info.suspended = true;
String r = model.getContextActionResult(e.id);
if (r == null) r = state_data.suspend_reason;
if (IRunControl.REASON_BREAKPOINT.equals(r)) info.breakpoint = true;
}
}
}
else {
if (!e.hasSuspendedChildren(info, done)) return false;
}
if (info.breakpoint && info.running) break;
}
return true;
}
@Override
public int compareTo(TCFNode n) {
if (n instanceof TCFNodeExecContext) {
TCFNodeExecContext f = (TCFNodeExecContext)n;
if (mem_seq_no < f.mem_seq_no) return -1;
if (mem_seq_no > f.mem_seq_no) return +1;
if (exe_seq_no < f.exe_seq_no) return -1;
if (exe_seq_no > f.exe_seq_no) return +1;
}
return id.compareTo(n.id);
}
}
| false | true | TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
bf.append('/');
bf.append(lst.get(i - 1));
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
| TCFNodeExecContext(TCFNode parent, final String id) {
super(parent, id);
children_exec = new TCFChildrenExecContext(this);
children_stack = new TCFChildrenStackTrace(this);
children_regs = new TCFChildrenRegisters(this);
children_exps = new TCFChildrenExpressions(this);
children_hover_exps = new TCFChildrenHoverExpressions(this);
children_log_exps = new TCFChildrenLogExpressions(this);
children_modules = new TCFChildrenModules(this);
children_query = new TCFChildrenContextQuery(this);
mem_context = new TCFData<IMemory.MemoryContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemory mem = launch.getService(IMemory.class);
if (mem == null) {
set(null, null, null);
return true;
}
command = mem.getContext(id, new IMemory.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IMemory.MemoryContext context) {
set(token, error, context);
}
});
return false;
}
};
run_context = new TCFData<IRunControl.RunControlContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IRunControl run = launch.getService(IRunControl.class);
if (run == null) {
set(null, null, null);
return true;
}
command = run.getContext(id, new IRunControl.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IRunControl.RunControlContext context) {
if (context != null) model.getContextMap().put(id, context);
set(token, error, context);
}
});
return false;
}
};
prs_context = new TCFData<IProcesses.ProcessContext>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IProcesses prs = launch.getService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getContext(id, new IProcesses.DoneGetContext() {
public void doneGetContext(IToken token, Exception error, IProcesses.ProcessContext context) {
set(token, error, context);
}
});
return false;
}
};
memory_map = new TCFData<MemoryRegion[]>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
IMemoryMap mmap = launch.getService(IMemoryMap.class);
if (mmap == null) {
set(null, null, null);
return true;
}
command = mmap.get(id, new IMemoryMap.DoneGet() {
public void doneGet(IToken token, Exception error, IMemoryMap.MemoryRegion[] map) {
MemoryRegion[] arr = null;
if (map != null) {
int i = 0;
arr = new MemoryRegion[map.length];
for (IMemoryMap.MemoryRegion r : map) arr[i++] = new MemoryRegion(r);
}
set(token, error, arr);
}
});
return false;
}
};
state = new TCFData<TCFContextState>(channel) {
@Override
protected boolean startDataRetrieval() {
assert command == null;
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, null, null);
return true;
}
command = ctx.getState(new IRunControl.DoneGetState() {
public void doneGetState(IToken token, Exception error, boolean suspended, String pc, String reason, Map<String,Object> params) {
TCFContextState s = new TCFContextState();
s.is_suspended = suspended;
s.suspend_pc = pc;
s.suspend_reason = reason;
s.suspend_params = params;
set(token, error, s);
}
});
return false;
}
};
address = new TCFData<BigInteger>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx == null || !ctx.hasState()) {
set(null, run_context.getError(), null);
return true;
}
if (!state.validate(this)) return false;
TCFContextState s = state.getData();
if (s == null) {
set(null, state.getError(), null);
return true;
}
if (s.suspend_pc == null) {
set(null, null, null);
return true;
}
set(null, null, new BigInteger(s.suspend_pc));
return true;
}
};
signal_list = new TCFData<Collection<Map<String,Object>>>(channel) {
@Override
protected boolean startDataRetrieval() {
IProcesses prs = channel.getRemoteService(IProcesses.class);
if (prs == null) {
set(null, null, null);
return true;
}
command = prs.getSignalList(id, new IProcesses.DoneGetSignalList() {
public void doneGetSignalList(IToken token, Exception error, Collection<Map<String, Object>> list) {
set(token, error, list);
}
});
return false;
}
};
signal_mask = new TCFData<SignalMask[]>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!signal_list.validate(this)) return false;
IProcesses prs = channel.getRemoteService(IProcesses.class);
final Collection<Map<String,Object>> sigs = signal_list.getData();
if (prs == null || sigs == null) {
set(null, signal_list.getError(), null);
return true;
}
command = prs.getSignalMask(id, new IProcesses.DoneGetSignalMask() {
public void doneGetSignalMask(IToken token, Exception error, int dont_stop, int dont_pass, int pending) {
int n = 0;
SignalMask[] list = new SignalMask[sigs.size()];
for (Map<String,Object> m : sigs) {
SignalMask s = list[n++] = new SignalMask();
s.props = m;
int mask = 1 << s.getIndex().intValue();
s.dont_stop = (dont_stop & mask) != 0;
s.dont_pass = (dont_pass & mask) != 0;
s.pending = (pending & mask) != 0;
}
set(token, error, list);
}
});
return false;
}
};
memory_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String mem_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) mem_id = ctx.getProcessID();
}
if (err != null) {
set(null, err, null);
}
else if (mem_id == null) {
set(null, new Exception("Context does not provide memory access"), null);
}
else {
if (!model.createNode(mem_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(mem_id));
}
return true;
}
};
symbols_node = new TCFData<TCFNodeExecContext>(channel) {
@Override
protected boolean startDataRetrieval() {
String syms_id = null;
if (!run_context.validate(this)) return false;
Throwable err = run_context.getError();
if (err == null) {
IRunControl.RunControlContext ctx = run_context.getData();
if (ctx != null) {
syms_id = ctx.getSymbolsGroup();
if (syms_id == null) syms_id = ctx.getProcessID();
}
}
if (err != null) {
set(null, err, null);
}
else if (syms_id == null) {
set(null, new Exception("Context does not support symbol groups"), null);
}
else {
if (!model.createNode(syms_id, this)) return false;
if (!isValid()) set(null, null, (TCFNodeExecContext)model.getNode(syms_id));
}
return true;
}
};
full_name = new TCFData<String>(channel) {
@Override
protected boolean startDataRetrieval() {
if (!run_context.validate(this)) return false;
IRunControl.RunControlContext ctx = run_context.getData();
String res = null;
if (ctx != null) {
res = ctx.getName();
if (res == null) {
res = ctx.getID();
}
else {
// Add ancestor names
TCFNodeExecContext p = TCFNodeExecContext.this;
ArrayList<String> lst = new ArrayList<String>();
lst.add(res);
while (p.parent instanceof TCFNodeExecContext) {
p = (TCFNodeExecContext)p.parent;
TCFDataCache<IRunControl.RunControlContext> run_ctx_cache = p.run_context;
if (!run_ctx_cache.validate(this)) return false;
IRunControl.RunControlContext run_ctx_data = run_ctx_cache.getData();
String name = null;
if (run_ctx_data != null) name = run_ctx_data.getName();
if (name == null) name = "";
lst.add(name);
}
StringBuffer bf = new StringBuffer();
for (int i = lst.size(); i > 0; i--) {
String name = lst.get(i - 1);
boolean quote = name.indexOf('/') >= 0;
bf.append('/');
if (quote) bf.append('"');
bf.append(name);
if (quote) bf.append('"');
}
res = bf.toString();
}
}
set(null, null, res);
return true;
}
};
}
|
diff --git a/test/unit/edu/northwestern/bioinformatics/studycalendar/dao/StudyDaoTest.java b/test/unit/edu/northwestern/bioinformatics/studycalendar/dao/StudyDaoTest.java
index 370df9434..99e15ddd8 100644
--- a/test/unit/edu/northwestern/bioinformatics/studycalendar/dao/StudyDaoTest.java
+++ b/test/unit/edu/northwestern/bioinformatics/studycalendar/dao/StudyDaoTest.java
@@ -1,62 +1,62 @@
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.testing.DaoTestCase;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Arm;
/**
* @author Rhett Sutphin
*/
public class StudyDaoTest extends DaoTestCase {
private StudyDao dao = (StudyDao) getApplicationContext().getBean("studyDao");
public void testGetById() throws Exception {
Study study = dao.getById(100);
assertNotNull("Study 1 not found", study);
assertEquals("Wrong name", "First Study", study.getName());
}
public void testLoadingArms() throws Exception {
Study study = dao.getById(100);
assertNotNull("Study 1 not found", study);
assertEquals("Wrong number of arms", 2, study.getArms().size());
assertArm("Wrong arm 0", 201, 1, "Sinister", study.getArms().get(0));
assertArm("Wrong arm 1", 200, 2, "Dexter", study.getArms().get(1));
assertSame("Arm <=> Study relationship not bidirectional on load", study, study.getArms().get(0).getStudy());
}
public void testSaveNewStudy() throws Exception {
Integer savedId;
{
Study study = new Study();
study.setName("New study");
study.addArm(new Arm());
study.getArms().get(0).setName("First Arm");
dao.save(study);
savedId = study.getId();
assertNotNull("The saved study didn't get an id", savedId);
}
interruptSession();
{
Study loaded = dao.getById(savedId);
- assertNotNull("Could not reload study with id " + savedId);
+ assertNotNull("Could not reload study with id " + savedId, loaded);
assertEquals("Wrong name", "New study", loaded.getName());
// TODO: cascade saving arms
// assertEquals("Wrong number of arms", 1, loaded.getArms().size());
// assertEquals("Wrong name for arm 0", "First arm", loaded.getArms().get(0).getName());
// assertEquals("Wrong number for arm 0", (Integer) 1, loaded.getArms().get(0).getNumber());
}
}
private static void assertArm(
String message, Integer expectedId, Integer expectedNumber, String expectedName, Arm actualArm
) {
assertEquals(message + ": wrong id", expectedId, actualArm.getId());
assertEquals(message + ": wrong number", expectedNumber, actualArm.getNumber());
assertEquals(message + ": wrong name", expectedName, actualArm.getName());
}
}
| true | true | public void testSaveNewStudy() throws Exception {
Integer savedId;
{
Study study = new Study();
study.setName("New study");
study.addArm(new Arm());
study.getArms().get(0).setName("First Arm");
dao.save(study);
savedId = study.getId();
assertNotNull("The saved study didn't get an id", savedId);
}
interruptSession();
{
Study loaded = dao.getById(savedId);
assertNotNull("Could not reload study with id " + savedId);
assertEquals("Wrong name", "New study", loaded.getName());
// TODO: cascade saving arms
// assertEquals("Wrong number of arms", 1, loaded.getArms().size());
// assertEquals("Wrong name for arm 0", "First arm", loaded.getArms().get(0).getName());
// assertEquals("Wrong number for arm 0", (Integer) 1, loaded.getArms().get(0).getNumber());
}
}
| public void testSaveNewStudy() throws Exception {
Integer savedId;
{
Study study = new Study();
study.setName("New study");
study.addArm(new Arm());
study.getArms().get(0).setName("First Arm");
dao.save(study);
savedId = study.getId();
assertNotNull("The saved study didn't get an id", savedId);
}
interruptSession();
{
Study loaded = dao.getById(savedId);
assertNotNull("Could not reload study with id " + savedId, loaded);
assertEquals("Wrong name", "New study", loaded.getName());
// TODO: cascade saving arms
// assertEquals("Wrong number of arms", 1, loaded.getArms().size());
// assertEquals("Wrong name for arm 0", "First arm", loaded.getArms().get(0).getName());
// assertEquals("Wrong number for arm 0", (Integer) 1, loaded.getArms().get(0).getNumber());
}
}
|
diff --git a/src/main/java/org/scribe/up/profile/JsonHelper.java b/src/main/java/org/scribe/up/profile/JsonHelper.java
index 3d5ab755..b1518152 100644
--- a/src/main/java/org/scribe/up/profile/JsonHelper.java
+++ b/src/main/java/org/scribe/up/profile/JsonHelper.java
@@ -1,86 +1,86 @@
/*
Copyright 2012 Jerome Leleu
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.scribe.up.profile;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This class is an helper to work with JSON.
*
* @author Jerome Leleu
* @since 1.0.0
*/
public final class JsonHelper {
private static final Logger logger = LoggerFactory.getLogger(JsonHelper.class);
private static ObjectMapper mapper = new ObjectMapper();
private JsonHelper() {
}
/**
* Return the first node of a JSON response.
*
* @param text
* @return the first node of the JSON response or null if exception is thrown
*/
public static JsonNode getFirstNode(final String text) {
try {
return mapper.readValue(text, JsonNode.class);
} catch (JsonParseException e) {
logger.error("JsonParseException", e);
} catch (JsonMappingException e) {
logger.error("JsonMappingException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
return null;
}
/**
* Return the field with name in JSON (a string, a boolean, a number or a node).
*
* @param json
* @param name
* @return the field
*/
public static Object get(final JsonNode json, final String name) {
if (json != null) {
JsonNode node = json.get(name);
if (node != null) {
if (node.isNumber()) {
- return node.intValue();
+ return node.numberValue();
} else if (node.isBoolean()) {
return node.booleanValue();
} else if (node.isTextual()) {
return node.textValue();
} else {
return node;
}
}
}
return null;
}
}
| true | true | public static Object get(final JsonNode json, final String name) {
if (json != null) {
JsonNode node = json.get(name);
if (node != null) {
if (node.isNumber()) {
return node.intValue();
} else if (node.isBoolean()) {
return node.booleanValue();
} else if (node.isTextual()) {
return node.textValue();
} else {
return node;
}
}
}
return null;
}
| public static Object get(final JsonNode json, final String name) {
if (json != null) {
JsonNode node = json.get(name);
if (node != null) {
if (node.isNumber()) {
return node.numberValue();
} else if (node.isBoolean()) {
return node.booleanValue();
} else if (node.isTextual()) {
return node.textValue();
} else {
return node;
}
}
}
return null;
}
|
diff --git a/src/com/jidesoft/popup/JidePopup.java b/src/com/jidesoft/popup/JidePopup.java
index b381d456..dfbc13c8 100644
--- a/src/com/jidesoft/popup/JidePopup.java
+++ b/src/com/jidesoft/popup/JidePopup.java
@@ -1,2175 +1,2178 @@
/*
* @(#)JidePopup.java 2/24/2005
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.popup;
import com.jidesoft.plaf.LookAndFeelFactory;
import com.jidesoft.plaf.PopupUI;
import com.jidesoft.plaf.UIDefaultsLookup;
import com.jidesoft.swing.JideScrollPane;
import com.jidesoft.swing.JideSwingUtilities;
import com.jidesoft.swing.Resizable;
import com.jidesoft.swing.ResizableWindow;
import com.jidesoft.utils.PortingUtils;
import com.jidesoft.utils.SecurityUtils;
import sun.awt.EmbeddedFrame;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.accessibility.AccessibleValue;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
/**
* <code>JidePopup</code> is a popup window which can be resized, dragged and autohide if time out.
* <p/>
* JidePopup uses JWindow as the container in order to show itself. By default, JidePopup is not focusable which means
* no component in the JidePopup will get focus. For example, if you put a JTextField in JidePopup and the JTextField becomes not editable,
* this is a result of non-focusable JWindow. So if you want components in JidePopup to be able to receive focus, you can either
* call setFocusable(true) or you can call {@link #setDefaultFocusComponent(java.awt.Component)} to set a child component
* as the default focus component.
*/
public class JidePopup extends JComponent implements Accessible, WindowConstants {
/**
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "JidePopupUI";
/**
* The <code>JRootPane</code> instance that manages the
* content pane
* and optional menu bar for this Popup, as well as the
* glass pane.
*
* @see javax.swing.JRootPane
* @see javax.swing.RootPaneContainer
*/
private JRootPane rootPane;
/**
* If <code>true</code> then calls to <code>add</code> and <code>setLayout</code>
* cause an exception to be thrown.
*/
private boolean rootPaneCheckingEnabled = false;
/**
* Bound property name.
*/
public final static String CONTENT_PANE_PROPERTY = "contentPane";
/**
* Bound property name.
*/
public final static String MENU_BAR_PROPERTY = "JMenuBar";
/**
* Bound property name.
*/
public final static String LAYERED_PANE_PROPERTY = "layeredPane";
/**
* Bound property name.
*/
public final static String ROOT_PANE_PROPERTY = "rootPane";
/**
* Bound property name.
*/
public final static String GLASS_PANE_PROPERTY = "glassPane";
/**
* Bound property name.
*/
public final static String VISIBLE_PROPERTY = "visible";
public final static String TRANSIENT_PROPERTY = "transient";
/**
* Constrained property name indicated that this frame has
* selected status.
*/
/**
* Constrained property name indicating that the popup is attachable.
*/
public final static String ATTACHABLE_PROPERTY = "attachable";
private boolean _attachable = true;
/**
* Bound property name for gripper.
*/
public final static String MOVABLE_PROPERTY = "movable";
/**
* If the gripper should be shown. Gripper is something on divider to indicate it can be dragged.
*/
private boolean _movable = false;
/**
* Bound property name for if the popup is detached.
*/
public final static String DETACHED_PROPERTY = "detached";
protected boolean _detached;
protected ResizableWindow _window;
private ComponentAdapter _componentListener;
private WindowAdapter _windowListener;
private ComponentAdapter _ownerComponentListener;
private HierarchyListener _hierarchyListener;
/**
* Bound property name for resizable.
*/
public final static String RESIZABLE_PROPERTY = "resizable";
private boolean _resizable = true;
// /**
// * Bound property name for movable.
// */
// public final static String MOVABLE_PROPERTY = "movable";
//
// private boolean _movable;
/**
* Bound property name for owner.
*/
public final static String OWNER_PROPERTY = "owner";
private Component _owner;
private Border _popupBorder;
private boolean _transient = true;
private int _timeout = 0;
private Timer _timer;
private Component _defaultFocusComponent;
/**
* Hides the popup when the owner is moved.
*/
public static final int DO_NOTHING_ON_MOVED = -1;
/**
* Hides the popup when the owner is moved.
*/
public static final int HIDE_ON_MOVED = 0;
/**
* Moves the popup along with owner when the owner is moved.
*/
public static final int MOVE_ON_MOVED = 1;
private int _defaultMoveOperation = HIDE_ON_MOVED;
/**
* The distance between alert and screen border.
*/
public int DISTANCE_TO_SCREEN_BORDER = 10;
private List _excludedComponents;
private int _gripperLocation = SwingConstants.NORTH;
public static final String PROPERTY_GRIPPER_LOCATION = "gripperLocation";
private ComponentAdapter _popupResizeListener;
protected Dimension _previousSize;
/**
* Creates a Popup.
*/
public JidePopup() {
_excludedComponents = new ArrayList();
setRootPane(createRootPane());
setLayout(new BorderLayout());
setRootPaneCheckingEnabled(true);
setFocusable(false);
updateUI();
}
/**
* Called by the constructor to set up the <code>JRootPane</code>.
*
* @return a new <code>JRootPane</code>
* @see javax.swing.JRootPane
*/
protected JRootPane createRootPane() {
return new JRootPane();
}
/**
* Returns the look-and-feel object that renders this component.
*
* @return the <code>PopupUI</code> object that renders
* this component
*/
public PopupUI getUI() {
return (PopupUI) ui;
}
/**
* Sets the UI delegate for this <code>Popup</code>.
*
* @param ui the UI delegate
*/
public void setUI(PopupUI ui) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
super.setUI(ui);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
/**
* Notification from the <code>UIManager</code> that the look and feel
* has changed.
* Replaces the current UI object with the latest version from the
* <code>UIManager</code>.
*
* @see javax.swing.JComponent#updateUI
*/
public void updateUI() {
if (UIDefaultsLookup.get(uiClassID) == null) {
LookAndFeelFactory.installJideExtension();
}
setUI((PopupUI) UIManager.getUI(this));
invalidate();
}
/**
* Returns the name of the look-and-feel
* class that renders this component.
*
* @return the string "PopupUI"
* @see javax.swing.JComponent#getUIClassID
* @see javax.swing.UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/**
* Returns whether calls to <code>add</code> and
* <code>setLayout</code> cause an exception to be thrown.
*
* @return <code>true</code> if <code>add</code> and <code>setLayout</code>
* are checked
* @see #addImpl
* @see #setLayout
* @see #setRootPaneCheckingEnabled
*/
protected boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
/**
* Determines whether calls to <code>add</code> and
* <code>setLayout</code> cause an exception to be thrown.
*
* @param enabled a boolean value, <code>true</code> if checking is to be
* enabled, which cause the exceptions to be thrown
* @see #addImpl
* @see #setLayout
* @see #isRootPaneCheckingEnabled
*/
protected void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
/**
* Ensures that, by default, children cannot be added
* directly to this component.
* Instead, children must be added to its content pane.
* For example:
* <pre>
* thisComponent.getContentPane().add(child)
* </pre>
* An attempt to add to directly to this component will cause a
* runtime exception to be thrown. Subclasses can disable this
* behavior.
*
* @param comp the <code>Component</code> to be added
* @param constraints the object containing the constraints, if any
* @param index the index
* @throws Error if called with <code>isRootPaneChecking</code> <code>true</code>
* @see #setRootPaneCheckingEnabled
*/
protected void addImpl(Component comp, Object constraints, int index) {
if (isRootPaneCheckingEnabled()) {
getContentPane().add(comp, constraints, index);
}
else {
super.addImpl(comp, constraints, index);
}
}
/**
* Removes the specified component from this container.
*
* @param comp the component to be removed
* @see #add
*/
public void remove(Component comp) {
int oldCount = getComponentCount();
super.remove(comp);
if (oldCount == getComponentCount()) {
// Client mistake, but we need to handle it to avoid a
// common object leak in client applications.
getContentPane().remove(comp);
}
}
/**
* Ensures that, by default, the layout of this component cannot be set.
* Instead, the layout of its content pane should be set.
* For example:
* <pre>
* thisComponent.getContentPane().setLayout(new GridLayout(1,2))
* </pre>
* An attempt to set the layout of this component will cause an
* runtime exception to be thrown. Subclasses can disable this
* behavior.
*
* @param manager the <code>LayoutManager</code>
* @throws Error if called with <code>isRootPaneChecking</code> <code>true</code>
* @see #setRootPaneCheckingEnabled
*/
public void setLayout(LayoutManager manager) {
if (isRootPaneCheckingEnabled()) {
getContentPane().setLayout(manager);
}
else {
super.setLayout(manager);
}
}
//////////////////////////////////////////////////////////////////////////
/// Property Methods
//////////////////////////////////////////////////////////////////////////
/**
* Returns the current <code>JMenuBar</code> for this
* <code>Popup</code>, or <code>null</code>
* if no menu bar has been set.
*
* @return the <code>JMenuBar</code> used by this Popup.
* @see #setJMenuBar
*/
public JMenuBar getJMenuBar() {
return getRootPane().getJMenuBar();
}
/**
* Sets the <code>menuBar</code> property for this <code>Popup</code>.
*
* @param m the <code>JMenuBar</code> to use in this Popup.
* @see #getJMenuBar
*/
public void setJMenuBar(JMenuBar m) {
JMenuBar oldValue = getJMenuBar();
getRootPane().setJMenuBar(m);
firePropertyChange(MENU_BAR_PROPERTY, oldValue, m);
}
// implements javax.swing.RootPaneContainer
/**
* Returns the content pane for this Popup.
*
* @return the content pane
*/
public Container getContentPane() {
return getRootPane().getContentPane();
}
/**
* Sets this <code>Popup</code>'s <code>contentPane</code>
* property.
*
* @param c the content pane for this popup.
* @throws java.awt.IllegalComponentStateException
* (a runtime
* exception) if the content pane parameter is <code>null</code>
* @see javax.swing.RootPaneContainer#getContentPane
*/
public void setContentPane(Container c) {
Container oldValue = getContentPane();
getRootPane().setContentPane(c);
firePropertyChange(CONTENT_PANE_PROPERTY, oldValue, c);
}
/**
* Returns the layered pane for this popup.
*
* @return a <code>JLayeredPane</code> object
* @see javax.swing.RootPaneContainer#setLayeredPane
* @see javax.swing.RootPaneContainer#getLayeredPane
*/
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
/**
* Sets this <code>Popup</code>'s
* <code>layeredPane</code> property.
*
* @param layered the <code>JLayeredPane</code> for this popup
* @throws java.awt.IllegalComponentStateException
* (a runtime
* exception) if the layered pane parameter is <code>null</code>
* @see javax.swing.RootPaneContainer#setLayeredPane
*/
public void setLayeredPane(JLayeredPane layered) {
JLayeredPane oldValue = getLayeredPane();
getRootPane().setLayeredPane(layered);
firePropertyChange(LAYERED_PANE_PROPERTY, oldValue, layered);
}
/**
* Returns the glass pane for this popup.
*
* @return the glass pane
* @see javax.swing.RootPaneContainer#setGlassPane
*/
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
/**
* Sets this <code>Popup</code>'s
* <code>glassPane</code> property.
*
* @param glass the glass pane for this popup
* @see javax.swing.RootPaneContainer#getGlassPane
*/
public void setGlassPane(Component glass) {
Component oldValue = getGlassPane();
getRootPane().setGlassPane(glass);
firePropertyChange(GLASS_PANE_PROPERTY, oldValue, glass);
}
/**
* Returns the <code>rootPane</code> object for this popup.
*
* @return the <code>rootPane</code> property
* @see javax.swing.RootPaneContainer#getRootPane
*/
public JRootPane getRootPane() {
return rootPane;
}
/**
* Sets the <code>rootPane</code> property
* for this <code>Popup</code>.
* This method is called by the constructor.
*
* @param root the new <code>JRootPane</code> object
*/
protected void setRootPane(JRootPane root) {
if (rootPane != null) {
remove(rootPane);
}
JRootPane oldValue = getRootPane();
rootPane = root;
if (rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
}
finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
firePropertyChange(ROOT_PANE_PROPERTY, oldValue, root);
}
/**
* Makes the component visible or invisible.
* Overrides <code>Component.setVisible</code>.
*
* @param visible true to make the component visible; false to
* make it invisible
*/
public void setVisible(boolean visible) {
boolean old = isVisible();
if (visible != old) {
super.setVisible(visible);
firePropertyChange(VISIBLE_PROPERTY, old, visible);
}
}
/**
* Gets the <code>AccessibleContext</code> associated with this
* <code>Popup</code>.
* For popups, the <code>AccessibleContext</code>
* takes the form of an
* <code>AccessiblePopup</code> object.
* A new <code>AccessiblePopup</code> instance is created if necessary.
*
* @return an <code>AccessiblePopup</code> that serves as the
* <code>AccessibleContext</code> of this
* <code>Popup</code>
* @see com.jidesoft.popup.JidePopup.AccessiblePopup
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessiblePopup();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* <code>Popup</code> class. It provides an implementation of the
* Java Accessibility API appropriate to popup user-interface
* elements.
*/
protected class AccessiblePopup extends AccessibleJComponent
implements AccessibleValue {
/**
* Get the accessible name of this object.
*
* @return the localized name of the object -- can be <code>null</code> if this
* object does not have a name
* @see #setAccessibleName
*/
public String getAccessibleName() {
if (accessibleName != null) {
return accessibleName;
}
else {
return getName();
}
}
/**
* Get the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see javax.accessibility.AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.SWING_COMPONENT; // use a generic one since there is no specific one to choose
}
/**
* Gets the AccessibleValue associated with this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is responsible for implementing the
* <code>AccessibleValue</code> interface on behalf of itself.
*
* @return this object
*/
public AccessibleValue getAccessibleValue() {
return this;
}
//
// AccessibleValue methods
//
/**
* Get the value of this object as a Number.
*
* @return value of the object -- can be <code>null</code> if this object does not
* have a value
*/
public Number getCurrentAccessibleValue() {
if (isVisible()) {
return new Integer(1);
}
else {
return new Integer(0);
}
}
/**
* Set the value of this object as a Number.
*
* @return <code>true</code> if the value was set
*/
public boolean setCurrentAccessibleValue(Number n) {
if (n instanceof Integer) {
if (n.intValue() == 0)
setVisible(true);
else
setVisible(false);
return true;
}
else {
return false;
}
}
/**
* Get the minimum value of this object as a Number.
*
* @return Minimum value of the object; <code>null</code> if this object does not
* have a minimum value
*/
public Number getMinimumAccessibleValue() {
return new Integer(Integer.MIN_VALUE);
}
/**
* Get the maximum value of this object as a Number.
*
* @return Maximum value of the object; <code>null</code> if this object does not
* have a maximum value
*/
public Number getMaximumAccessibleValue() {
return new Integer(Integer.MAX_VALUE);
}
}
/**
* Shows the popup. By default, it will show right below the owner.
*/
public void showPopup() {
//David: To account for a popup within a popup, let the caller specify an owner
// different from the RootPaneContainer(Applet) or ContentContainer.
// showPopup(new Insets(0, 0, 0, 0));
showPopup(new Insets(0, 0, 0, 0), null);
}
/**
* Shows the popup. By default, it will show right below the owner after considering the insets.
*
* @param owner the popup window's owner; if unspecified, it will default to the
* RootPaneContainer(Applet) or ContentContainer
*/
public void showPopup(Component owner) {
showPopup(new Insets(0, 0, 0, 0), owner);
}
/**
* Shows the popup. By default, it will show right below the owner after considering the insets.
*
* @param insets the popup's insets
* RootPaneContainer(Applet) or ContentContainer
*/
public void showPopup(Insets insets) {
showPopup(insets, null);
}
protected Insets _insets = null;
/**
* Shows the popup. By default, it will show right below the owner after considering the insets. Please note, if the owner
* is not displayed (isShowing returns false), the popup will not be displayed either.
*
* @param insets the popup's insets
* @param owner the popup window's owner; if unspecified, it will default to the
* RootPaneContainer(Applet) or ContentContainer
*/
public void showPopup(Insets insets, Component owner) {
_insets = insets;
Component actualOwner = (owner != null) ? owner : getOwner();
Point point = null;
if (actualOwner != null && actualOwner.isShowing()) {
point = actualOwner.getLocationOnScreen();
internalShowPopup(point.x, point.y, actualOwner);
}
else {
showPopup(SwingConstants.CENTER);
}
}
/**
* Calculates the popup location.
*
* @param point owner is top-left coordinate relative to screen.
* @param size the size of the popup window.
* @param owner the owner
* @return new popup location. By default, it will return the coordinate of the bottom-left corner of owner.
*/
protected Point getPopupLocation(Point point, Dimension size, Component owner) {
Component actualOwner = (owner != null) ? owner : getOwner();
Dimension ownerSize = actualOwner != null ? actualOwner.getSize() : new Dimension(0, 0);
Dimension screenSize = PortingUtils.getScreenSize(owner);
if (size.width == 0) {
size = this.getPreferredSize();
}
Point p = new Point(point.x + _insets.left, point.y + ownerSize.height - _insets.bottom);
int left = p.x + size.width;
int bottom = p.y + size.height;
if (left > screenSize.width) {
p.x -= left - screenSize.width; // move left so that the whole popup can fit in
}
if (bottom > screenSize.height) {
p.y = point.y + _insets.top - size.height; // flip to upward
if (isResizable()) {
setupResizeCorner(Resizable.UPPER_RIGHT);
}
}
else {
if (isResizable()) {
setupResizeCorner(Resizable.LOWER_RIGHT);
}
}
return p;
}
/**
* Setup Resizable's ResizeCorner.
*
* @param corner the corner.
*/
public void setupResizeCorner(int corner) {
switch (corner) {
case Resizable.UPPER_RIGHT:
_window.getResizable().setResizableCorners(Resizable.UPPER_RIGHT);
JideSwingUtilities.setRecursively(this, new JideSwingUtilities.Handler() {
public boolean condition(Component c) {
return c instanceof JideScrollPane;
}
public void action(Component c) {
Resizable.ResizeCorner corner = new Resizable.ResizeCorner(Resizable.UPPER_RIGHT);
corner.addMouseListener(_window.getResizable().getMouseInputAdapter());
corner.addMouseMotionListener(_window.getResizable().getMouseInputAdapter());
((JideScrollPane) c).setScrollBarCorner(JideScrollPane.VERTICAL_TOP, corner);
((JideScrollPane) c).setScrollBarCorner(JideScrollPane.VERTICAL_BOTTOM, null);
}
public void postAction(Component c) {
}
});
break;
case Resizable.LOWER_RIGHT:
_window.getResizable().setResizableCorners(Resizable.LOWER_RIGHT);
JideSwingUtilities.setRecursively(this, new JideSwingUtilities.Handler() {
public boolean condition(Component c) {
return c instanceof JideScrollPane;
}
public void action(Component c) {
Resizable.ResizeCorner corner = new Resizable.ResizeCorner(Resizable.LOWER_RIGHT);
corner.addMouseListener(_window.getResizable().getMouseInputAdapter());
corner.addMouseMotionListener(_window.getResizable().getMouseInputAdapter());
((JideScrollPane) c).setScrollBarCorner(JideScrollPane.VERTICAL_BOTTOM, corner);
((JideScrollPane) c).setScrollBarCorner(JideScrollPane.VERTICAL_TOP, null);
}
public void postAction(Component c) {
}
});
break;
default:
_window.getResizable().setResizableCorners(corner);
break;
}
}
public static Component getTopLevelAncestor(Component component) {
if (component == null) {
return null;
}
for (Component p = component; p != null; p = p.getParent()) {
if (p instanceof Window || p instanceof Applet) {
return p;
}
}
return null;
}
/**
* Shows the popup at the specified location relative to the screen. The valid locations are:
* <ul>
* <li>{@link SwingConstants#CENTER}
* <li>{@link SwingConstants#SOUTH}
* <li>{@link SwingConstants#NORTH}
* <li>{@link SwingConstants#WEST}
* <li>{@link SwingConstants#EAST}
* <li>{@link SwingConstants#NORTH_EAST}
* <li>{@link SwingConstants#NORTH_WEST}
* <li>{@link SwingConstants#SOUTH_EAST}
* <li>{@link SwingConstants#SOUTH_WEST}
* </ul>
* The actual location will be based on the main screen bounds. Say if the location is SwingConstants.SOUTH_EAST,
* the popup will appear at the south west corner of main screen with 10 pixels to the border. The 10 pixel is the
* default value. You can change it by setting {@link #DISTANCE_TO_SCREEN_BORDER}.
*
* @param location the new location.
*/
public void showPopup(int location) {
showPopup(location, null);
}
/**
* Shows the popup at the specified location relative to the owner. The valid locations are:
* <ul>
* <li>{@link SwingConstants#CENTER}
* <li>{@link SwingConstants#SOUTH}
* <li>{@link SwingConstants#NORTH}
* <li>{@link SwingConstants#WEST}
* <li>{@link SwingConstants#EAST}
* <li>{@link SwingConstants#NORTH_EAST}
* <li>{@link SwingConstants#NORTH_WEST}
* <li>{@link SwingConstants#SOUTH_EAST}
* <li>{@link SwingConstants#SOUTH_WEST}
* </ul>
* The actual location will be based on the owner's bounds. Say if the location is SwingConstants.SOUTH_EAST,
* the popup will appear at the south west corner of owner with 10 pixels to the border. The 10 pixel is the
* default value. You can change it by setting {@link #DISTANCE_TO_SCREEN_BORDER}.
*
* @param location the new location
* @param owner the popup window's owner; if unspecified, it will default to the
* RootPaneContainer(Applet) or ContentContainer
*/
public void showPopup(int location, Component owner) {
setDetached(true);
Rectangle screenDim = getDisplayScreenBounds(owner);
// Get the bounds of the splash window
Dimension size = getPreferredSize();
Point displayLocation = getDisplayStartLocation(screenDim, size, location);
internalShowPopup(displayLocation.x, displayLocation.y, owner);
}
protected Point getDisplayStartLocation(Rectangle screenDim, Dimension size, int location) {
switch (location) {
case SwingConstants.CENTER:
return new Point(screenDim.x + (screenDim.width - size.width) / 2,
screenDim.y + (screenDim.height - size.height) / 2);
case SwingConstants.SOUTH:
return new Point(screenDim.x + (screenDim.width - size.width) / 2,
screenDim.y + screenDim.height - size.height - DISTANCE_TO_SCREEN_BORDER);
case SwingConstants.NORTH:
return new Point(screenDim.x + (screenDim.width - size.width) / 2,
screenDim.y + DISTANCE_TO_SCREEN_BORDER);
case SwingConstants.EAST:
return new Point(screenDim.x + screenDim.width - size.width - DISTANCE_TO_SCREEN_BORDER,
screenDim.y + (screenDim.height - size.height) / 2);
case SwingConstants.WEST:
return new Point(screenDim.x + DISTANCE_TO_SCREEN_BORDER,
screenDim.y + (screenDim.height - size.height) / 2);
case SwingConstants.SOUTH_WEST:
return new Point(screenDim.x + DISTANCE_TO_SCREEN_BORDER,
screenDim.y + screenDim.height - size.height - DISTANCE_TO_SCREEN_BORDER);
case SwingConstants.NORTH_EAST:
return new Point(screenDim.x + screenDim.width - size.width - DISTANCE_TO_SCREEN_BORDER,
screenDim.y + DISTANCE_TO_SCREEN_BORDER);
case SwingConstants.NORTH_WEST:
return new Point(screenDim.x + DISTANCE_TO_SCREEN_BORDER,
screenDim.y + DISTANCE_TO_SCREEN_BORDER);
case SwingConstants.SOUTH_EAST:
default:
return new Point(screenDim.x + screenDim.width - size.width - DISTANCE_TO_SCREEN_BORDER,
screenDim.y + screenDim.height - size.height - DISTANCE_TO_SCREEN_BORDER);
}
}
protected Rectangle getDisplayScreenBounds(Component owner) {
Rectangle screenDim;
if (owner != null && owner.isShowing()) {
screenDim = owner.getBounds();
Point p = owner.getLocationOnScreen();
screenDim.x = p.x;
screenDim.y = p.y;
}
else {
screenDim = PortingUtils.getLocalScreenBounds();
}
return screenDim;
}
public void packPopup() {
if (_window == null || !_window.isVisible()) {
return;
}
_window.pack();
}
//David: To account for a popup within a popup, let the caller specify an owner
// different from the RootPaneContainer(Applet) or ContentContainer.
protected void internalShowPopup(int x, int y) {
internalShowPopup(x, y, null);
}
protected void internalShowPopup(int x, int y, Component owner) {
createWindow(owner, x, y);
showPopupImmediately();
}
protected void createWindow(Component owner, int x, int y) {
if (_window == null) {
_window = createPopupContainer(owner);
installListeners();
installBorder();
}
if (_previousSize != null) {
_window.setSize(_previousSize);
_previousSize = null;
}
else {
_window.pack();
}
if (_insets != null) {
Point p = getPopupLocation(new Point(x, y), _window.getSize(), owner);
x = p.x;
y = p.y;
}
_window.setLocation(x, y);
}
/**
* Shows the popup at the specified x and y coordinates.
*
* @param x the x position.
* @param y the y position.
*/
public void showPopup(int x, int y) {
showPopup(x, y, null);
}
/**
* Shows the popup at the specified x and y coordinates.
*
* @param x the x position.
* @param y the y position.
* @param owner the popup window's owner; if unspecified, it will default to the
* RootPaneContainer(Applet) or ContentContainer
*/
public void showPopup(int x, int y, Component owner) {
internalShowPopup(x, y, owner);
}
protected ResizableWindow createPopupContainer() {
return createPopupContainer(null);
}
protected static Frame getFrame(Component c) {
Component w = c;
while (!(w instanceof Frame) && (w != null)) {
w = w.getParent();
}
return (Frame) w;
}
protected ResizableWindow createPopupContainer(Component owner) {
ResizableWindow container;
Component actualOwner = (owner != null) ? owner : getOwner();
Component topLevelAncestor = getTopLevelAncestor(actualOwner);
if (topLevelAncestor instanceof Frame) {
container = new ResizableWindow((Frame) topLevelAncestor);
}
else if (topLevelAncestor instanceof Window) {
container = new ResizableWindow((Window) topLevelAncestor);
}
else {
Frame frame = getFrame(actualOwner);
container = new ResizableWindow(frame);
}
container.getContentPane().add(this);
return container;
}
protected void installListeners() {
//David: Adding the MouseEventHandler synchronously causes a strange
// initialization sequence if the popup owner is a tree/table editor:
//
// - The editor gets moved to its initial location based on the cell location,
// generating a COMPONENT_MOVED ComponentEvent.
// - You add the MouseEventHandler, which includes a ComponentEvent listener on
// the owner's hierarcy, including the editor.
// - ComponentEvent is asynchronous. The ComponentEvent generated from moving
// the editor to its initial position was placed on the event queue. So the
// ComponentEvent gets handled by the MouseEventHandler's ComponentEvent
// listener, even though it happened before the listener was added.
//
// I fixed it by calling addMouseEventHandler asynchronously, guaranteeing that
// any previously-generated event it may listen for has been removed from the
// event queue before the listener is added.
//
// This causes a couple of minor problems:
//
// - It is possible that hidePopupImmediately can be called synchronously before
// the asynchronous call to addMouseEventHandler is executed. This can cause
// NPEs because the listener handler methods dereference _window, which is set
// to null in hidePopupImmediately. So I added null checks on _window in the
// listener handler methods.
//
// - The removeMouseEventHandler method is called from hidePopupImmediately.
// That means it could be called before addMouseEventHandler is executed
// asynchronously; that would result in the listener not getting removed. So
// I changed the removeMouseEventHandler to an asynchronous call, as well.
//
// This issue appeared in the 1.8.3 release because you changed the
// COMPONENT_MOVED handler to hide the popup instead of moving it. Since you
// made this an option in the 1.8.4 release, all of this asynchronous code is
// needed.
//
// addMouseEventHandler()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
addMouseEventHandler();
}
});
_componentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
hidePopup();
}
};
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePopupImmediately(true);
if (getOwner() != null) {
getOwner().requestFocus();
}
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
_window.addComponentListener(_componentListener);
_windowListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
hidePopup();
}
};
_window.addWindowListener(_windowListener);
if (getOwner() != null) {
_ownerComponentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
ancestorHidden();
}
public void componentMoved(ComponentEvent e) {
ancestorMoved();
}
};
getOwner().addComponentListener(_ownerComponentListener);
_hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
ancestorHidden();
}
};
getOwner().addHierarchyListener(_hierarchyListener);
}
_popupResizeListener = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
removeComponentListener(_popupResizeListener);
- Dimension size = getSize();
- if (getPopupBorder() != null) {
- Insets borderInsets = getPopupBorder().getBorderInsets(JidePopup.this);
- size.width += borderInsets.left + borderInsets.right;
- size.height += borderInsets.top + borderInsets.bottom;
- }
- else if (_window.getBorder() != null) {
- Insets borderInsets = _window.getBorder().getBorderInsets(_window);
- size.width += borderInsets.left + borderInsets.right;
- size.height += borderInsets.top + borderInsets.bottom;
- }
- _window.setSize(size);
+// Dimension size = getSize();
+// Dimension windowSize = new Dimension(size.width,size.height);
+// if (getPopupBorder() != null) {
+// Insets borderInsets = getPopupBorder().getBorderInsets(JidePopup.this);
+// windowSize.width += borderInsets.left + borderInsets.right;
+// windowSize.height += borderInsets.top + borderInsets.bottom;
+// }
+// else if (_window.getBorder() != null) {
+// Insets borderInsets = _window.getBorder().getBorderInsets(_window);
+// windowSize.width += borderInsets.left + borderInsets.right;
+// windowSize.height += borderInsets.top + borderInsets.bottom;
+// }
+// _window.setSize(windowSize);
+ // pack is good enough to replace all code above
+ _window.pack();
addComponentListener(_popupResizeListener);
}
};
addComponentListener(_popupResizeListener);
}
protected void installBorder() {
if (getPopupBorder() != null) {
if (isResizable()) {
_window.getResizable().setResizableCorners(Resizable.ALL);
}
else {
_window.getResizable().setResizableCorners(Resizable.NONE);
}
_window.setBorder(getPopupBorder());
}
else {
if (isDetached()) {
if (isResizable()) {
_window.getResizable().setResizableCorners(Resizable.ALL);
}
else {
_window.getResizable().setResizableCorners(Resizable.NONE);
}
_window.setBorder(UIDefaultsLookup.getBorder("Resizable.resizeBorder"));
}
else {
if (isResizable()) {
_window.getResizable().setResizableCorners(Resizable.RIGHT | Resizable.LOWER | Resizable.LOWER_RIGHT);
}
else {
_window.getResizable().setResizableCorners(Resizable.NONE);
}
_window.setBorder(UIDefaultsLookup.getBorder("PopupMenu.border"));
}
}
}
protected void showPopupImmediately() {
if (_window == null) {
return;
}
firePopupMenuWillBecomeVisible();
// only when the focus cycle root is true, the component in JidePopup won't request focus automatically.
if (!isFocusable() && getDefaultFocusComponent() == null) {
_window.setFocusableWindowState(false);
}
if (!_window.isVisible()) {
_window.pack();
_window.setVisible(true);
_window.toFront();
}
firePropertyChange("visible", Boolean.FALSE, Boolean.TRUE);
if (isFocusable() || getDefaultFocusComponent() != null) {
// only allow window to have focus when there is a default focus component.
_window.setFocusable(true);
if (getDefaultFocusComponent() != null) {
Runnable runnable = new Runnable() {
public void run() {
getDefaultFocusComponent().requestFocus();
}
};
SwingUtilities.invokeLater(runnable);
}
}
if (getTimeout() != 0) {
startTimeoutTimer();
}
}
protected void movePopup() {
if (!isDetached() && getOwner() != null) {
Point point = getOwner().getLocationOnScreen();
if (_insets != null) {
Point p = getPopupLocation(point, _window.getSize(), getOwner());
_window.setLocation(p.x, p.y);
}
else {
Dimension ownerSize = getOwner().getSize();
_window.setLocation(point.x, point.y + ownerSize.height);
}
}
}
private boolean _isDragging = false;
/**
* Mouse location related the frame it drags.
*/
private double _relativeX,
_relativeY;
private Point _startPoint;
private Window _currentWindow;
protected void endDragging() {
_isDragging = false;
if (_currentWindow instanceof JWindow && ((JWindow) _currentWindow).getGlassPane() != null) {
((JWindow) _currentWindow).getGlassPane().setVisible(false);
((JWindow) _currentWindow).getGlassPane().setCursor(Cursor.getDefaultCursor());
}
else if (_currentWindow instanceof JDialog && ((JDialog) _currentWindow).getGlassPane() != null) {
((JDialog) _currentWindow).getGlassPane().setVisible(false);
((JDialog) _currentWindow).getGlassPane().setCursor(Cursor.getDefaultCursor());
}
_currentWindow = null;
_relativeX = 0;
_relativeY = 0;
}
protected void beginDragging(JComponent f, int mouseX, int mouseY, double relativeX, double relativeY) {
_relativeX = relativeX;
_relativeY = relativeY;
if (f.getTopLevelAncestor() instanceof JWindow)
_currentWindow = (JWindow) f.getTopLevelAncestor();
if (f.getTopLevelAncestor() instanceof JDialog)
_currentWindow = (JDialog) f.getTopLevelAncestor();
if (_currentWindow instanceof JWindow && ((JWindow) _currentWindow).getGlassPane() != null) {
((JWindow) _currentWindow).getGlassPane().setVisible(true);
((JWindow) _currentWindow).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
else if (_currentWindow instanceof JDialog && ((JDialog) _currentWindow).getGlassPane() != null) {
((JDialog) _currentWindow).getGlassPane().setVisible(true);
((JDialog) _currentWindow).getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
_isDragging = true;
if (isDetached() && getOwner() != null) {
_startPoint = getOwner().getLocationOnScreen();
_startPoint.y += getOwner().getHeight();
}
else {
_startPoint = _currentWindow.getLocationOnScreen();
}
}
protected boolean isDragging() {
return _isDragging;
}
static void convertPointToScreen(Point p, Component c, boolean startInFloat) {
int x, y;
do {
if (c instanceof JComponent) {
x = c.getX();
y = c.getY();
}
else if (c instanceof java.applet.Applet || (startInFloat ? c instanceof Window : c instanceof JFrame)) {
try {
Point pp = c.getLocationOnScreen();
x = pp.x;
y = pp.y;
}
catch (IllegalComponentStateException icse) {
x = c.getX();
y = c.getY();
}
}
else {
x = c.getX();
y = c.getY();
}
p.x += x;
p.y += y;
if ((startInFloat ? c instanceof Window : c instanceof JFrame) || c instanceof java.applet.Applet)
break;
c = c.getParent();
}
while (c != null);
}
protected void drag(JComponent f, int newX, int newY, int mouseModifiers) {
int x = newX - (int) (_currentWindow.getWidth() * _relativeX);
int y = newY - (int) (_currentWindow.getHeight() * _relativeY);
Rectangle bounds = new Rectangle(x, y, _currentWindow.getWidth(), _currentWindow.getHeight());
Rectangle screenBounds = PortingUtils.getScreenBounds(_currentWindow);
if (bounds.y + bounds.height > screenBounds.y + screenBounds.height) {
bounds.y = screenBounds.y + screenBounds.height - bounds.height;
}
if (bounds.y < screenBounds.y) {
bounds.y = screenBounds.y;
}
if (isAttachable() && isWithinAroundArea(new Point(x, y), _startPoint)) {
_currentWindow.setLocation(_startPoint);
setDetached(false);
}
else {
_currentWindow.setLocation(x, y);
setDetached(true);
}
}
final int AROUND_SIZE = 10;
boolean isWithinAroundArea(Point p, Point newPoint) {
Rectangle rect = new Rectangle(p.x - AROUND_SIZE, p.y - AROUND_SIZE, p.x + AROUND_SIZE, p.y + AROUND_SIZE);
return rect.contains(newPoint);
}
static boolean isAncestorOf(Component component, Object ancester) {
if (component == null) {
return false;
}
for (Component p = component; p != null; p = p.getParent()) {
if (p == ancester) {
return true;
}
}
return false;
}
// private AWTEventListener _awtEventListener = new AWTEventListener() {
// public void eventDispatched(AWTEvent event) {
// if (event instanceof MouseEvent) {
// if (event.getID() == MouseEvent.MOUSE_PRESSED) {
// MouseEvent e = (MouseEvent) event;
// Object source = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY());
// if (!isAncestorOf((Container) source, JidePopup.this.getTopLevelAncestor())) { // todo: add a flag to not hidepopup in some cases
// hidePopup();
// }
// else {
// Point point = SwingUtilities.convertPoint((Component) e.getSource(), e.getPoint(), JidePopup.this);
//
// Rectangle startingBounds = JidePopup.this.getTopLevelAncestor().getBounds();
// _relativeX = (double) point.x / startingBounds.width;
// _relativeY = (double) point.y / startingBounds.height;
//
// Point screenPoint = new Point(e.getX(), e.getY());
// JidePopup.convertPointToScreen(screenPoint, (Component) e.getSource(), true);
//
// // drag on gripper
// if (source == JidePopup.this.getUI().getGripper()) {
// beginDragging(JidePopup.this, screenPoint.x, screenPoint.y, _relativeX, _relativeY);
// e.consume();
// }
// }
// }
// else if (event.getID() == MouseEvent.MOUSE_DRAGGED) {
// if (isDragging()) {
// MouseEvent e = (MouseEvent) event;
// Point screenPoint = e.getPoint();
// convertPointToScreen(screenPoint, ((Component) e.getSource()), true);
// drag(null, screenPoint.x, screenPoint.y, e.getModifiersEx());
// e.consume();
// }
// }
// else if (event.getID() == MouseEvent.MOUSE_RELEASED) {
// if (isDragging()) {
// MouseEvent e = (MouseEvent) event;
// endDragging();
// e.consume();
// }
// }
// else if (event.getID() == MouseEvent.MOUSE_ENTERED) {
// if (_window.isAncestorOf(((Component) event.getSource())) && getTimeout() != 0) {
// stopTimeoutTimer();
// }
// }
// else if (event.getID() == MouseEvent.MOUSE_EXITED) {
// if (_window.isAncestorOf(((Component) event.getSource())) && getTimeout() != 0) {
// startTimeoutTimer();
// }
// }
// }
// else if (event instanceof WindowEvent) {
// WindowEvent e = (WindowEvent) event;
// if (e.getSource() != JidePopup.this.getTopLevelAncestor() && isAncestorOf(getOwner(), e.getWindow())) {
// if (e.getID() == WindowEvent.WINDOW_CLOSING || e.getID() == WindowEvent.WINDOW_ICONIFIED) {
// hidePopup();
// }
// }
// }
// else if (event instanceof ComponentEvent) {
// ComponentEvent e = (ComponentEvent) event;
// if (e.getID() == ComponentEvent.COMPONENT_HIDDEN && isAncestorOf(getOwner(), e.getSource())) {
// hidePopup();
// }
// else if (e.getID() == ComponentEvent.COMPONENT_MOVED && isAncestorOf(getOwner(), e.getSource())) {
// movePopup();
// }
// }
// }
// };
private AWTEventListener _awtEventListener = new AWTEventListener() {
public void eventDispatched(AWTEvent event) {
if ("sun.awt.UngrabEvent".equals(event.getClass().getName())) {
// this is really a hack so that it can detect event when closing the windows in Eclise RCP env.
// Popup should be canceled in case of ungrab event
hidePopupImmediately(true);
return;
}
if (event instanceof MouseEvent) {
if (event.getID() == MouseEvent.MOUSE_PRESSED) {
handleMousePressed((MouseEvent) event);
}
else if (event.getID() == MouseEvent.MOUSE_DRAGGED) {
handleMouseDragged((MouseEvent) event);
}
else if (event.getID() == MouseEvent.MOUSE_RELEASED) {
handleMouseReleased((MouseEvent) event);
}
else if (event.getID() == MouseEvent.MOUSE_ENTERED) {
handleMouseEntered((MouseEvent) event);
}
else if (event.getID() == MouseEvent.MOUSE_EXITED) {
handleMouseExited((MouseEvent) event);
}
}
else if (event instanceof WindowEvent) {
handleWindowEvent((WindowEvent) event);
}
else if (event instanceof ComponentEvent) {
handleComponentEvent((ComponentEvent) event);
}
}
};
protected void handleMousePressed(MouseEvent e) {
Object source = SwingUtilities.getDeepestComponentAt(e.getComponent(), e.getX(), e.getY());
Component component = (Component) source;
if (!isAncestorOf(component, getTopLevelAncestor())) {
if (isExcludedComponent(component)) {
return;
}
ancestorHidden();
}
else {
Point point = SwingUtilities.convertPoint(component, e.getPoint(), this);
Rectangle startingBounds = getTopLevelAncestor().getBounds();
_relativeX = (double) point.x / startingBounds.width;
_relativeY = (double) point.y / startingBounds.height;
Point screenPoint = new Point(e.getX(), e.getY());
convertPointToScreen(screenPoint, component, true);
// drag on gripper
if (source == getUI().getGripper()) {
beginDragging(this, screenPoint.x, screenPoint.y, _relativeX, _relativeY);
e.consume();
}
}
}
protected void handleMouseReleased(MouseEvent e) {
if (isDragging()) {
endDragging();
e.consume();
}
}
protected void handleMouseDragged(MouseEvent e) {
if (isDragging()) {
Point screenPoint = e.getPoint();
convertPointToScreen(screenPoint, ((Component) e.getSource()), true);
drag(null, screenPoint.x, screenPoint.y, e.getModifiersEx());
e.consume();
}
}
protected void handleMouseEntered(MouseEvent e) {
if ((_window != null) &&
_window.isAncestorOf(((Component) e.getSource())) && getTimeout() != 0) {
stopTimeoutTimer();
}
}
protected void handleMouseExited(MouseEvent e) {
// if (_window.isAncestorOf(((Component) e.getSource())) && getTimeout() != 0) {
if ((_window != null) &&
_window.isAncestorOf(((Component) e.getSource())) && getTimeout() != 0) {
startTimeoutTimer();
}
}
private static boolean checkedUnpostPopup;
private static boolean unpostPopup;
private static boolean doUnpostPopupOnDeactivation() {
if (!checkedUnpostPopup) {
Boolean b = (Boolean) java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
String pKey = "sun.swing.unpostPopupsOnWindowDeactivation";
String value = System.getProperty(pKey, "true");
return Boolean.valueOf(value);
}
}
);
unpostPopup = b.booleanValue();
checkedUnpostPopup = true;
}
return unpostPopup;
}
protected void handleWindowEvent(WindowEvent e) {
if (e.getSource() != getTopLevelAncestor() && isAncestorOf(getOwner(), e.getWindow())) { // check if it's embeded in browser
if (e.getID() == WindowEvent.WINDOW_CLOSING || e.getID() == WindowEvent.WINDOW_ICONIFIED) {
hidePopup(true);
}
// The cases for window deactivated are too complex. Let's not consider it for now.
// One case the code below didn't consider is an dialog is shown while in another thread, alert is showing and the owner is the frame.
// At the end, frame received deactivated event and cause alert to hide immediately.
//
// 1/2/07: we have to put this code back because combobox's popup not hiding when the window is deactivated.
// But I also copied the code from MenuSelectionManager to check doUnpostPopupOnDeactivation. Hopefully that addresses the issue above.
else if (isTransient() && e.getID() == WindowEvent.WINDOW_DEACTIVATED
&& !(e.getWindow() instanceof EmbeddedFrame)) {
// TODO: don't why DEACTIVATED event is fired when popup is showing only if the applet is in browser mode.
// so the best solution is to find out why. For now just skip the case if the frame is a EmbeddedFrame.
if (doUnpostPopupOnDeactivation()) {
hidePopup(true);
}
}
}
}
/**
* This method will process component event. By default, if popup's ancestor is hidden, we will hide the popup as well
* if the popup is transient (isTransient returns true). If popup's ancestor is moved, we will either move or hide
* the popup depending on {@link #getDefaultMoveOperation()} value.
*
* @param e the ComponentEvent.
*/
protected void handleComponentEvent(ComponentEvent e) {
if (e.getID() == ComponentEvent.COMPONENT_HIDDEN && isAncestorOf(getOwner(), e.getSource())) {
ancestorHidden();
}
else if (e.getID() == ComponentEvent.COMPONENT_MOVED && isAncestorOf(getOwner(), e.getSource())) {
ancestorMoved();
}
}
/**
* This method will process component hidden event for the popup's ancestor.
* By default we will hide the popup immediately. You can override this to customize
* the behavior.
*/
protected void ancestorHidden() {
if (isTransient()) {
hidePopupImmediately(true);
}
}
/**
* This method will process component moved event for the popup's ancestor.
* By default we will move the popup if getDefaultMoveOperation() is MOVE_ON_MOVED,
* or hide the popup if getDefaultMoveOperation() is HIDE_ON_MOVED. You can override this to customize
* the behavior.
*/
protected void ancestorMoved() {
if (getDefaultMoveOperation() == MOVE_ON_MOVED) {
movePopup();
}
else if (getDefaultMoveOperation() == HIDE_ON_MOVED) {
if (isTransient()) {
hidePopupImmediately(true);
}
}
}
public void hidePopup() {
hidePopup(false);
}
public void hidePopup(boolean cancelled) {
if (_window == null || !_window.isShowing()) { // not showing. It must be closed already
return;
}
hidePopupImmediately(cancelled);
}
public boolean isPopupVisible() {
return _window != null;
}
public Rectangle getPopupBounds() {
return isPopupVisible() ? _window.getBounds() : null;
}
public void hidePopupImmediately(boolean cancelled) {
if (getOwner() != null) {
getOwner().removeHierarchyListener(_hierarchyListener);
getOwner().removeComponentListener(_ownerComponentListener);
}
if (_window != null) {
_window.removeWindowListener(_windowListener);
_window.removeComponentListener(_componentListener);
_window.getContentPane().remove(this);
if (cancelled) {
firePopupMenuCanceled(); // will cause hidePopupImmediately called again.
}
firePopupMenuWillBecomeInvisible();
}
if (_popupResizeListener != null) {
removeComponentListener(_popupResizeListener);
_popupResizeListener = null;
}
if (_window != null) {
_previousSize = _window.getSize();
_window.setVisible(false);
firePropertyChange("visible", Boolean.TRUE, Boolean.FALSE);
_window.dispose();
_window = null;
}
//<syd_0034>
//David: There are synchronous events which can result in a call to
// hidePopupImmediately. Because I made the call to addMouseEventHandler
// asynchronous, this can result in a situation where hidePopupImmediately
// gets called before addMouseEventHandler is executed. In that situation, the
// mouseEventHandler would be added after it was removed, resulting in the
// handler hanging around. So I call the removeMouseEventHandler method
// asynchronously, as well, to insure that it happens after
// addMouseEventHandler.
// removeMouseEventHandler();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
removeMouseEventHandler();
}
});
//</syd_0034>
// comment out because bug report on http://www.jidesoft.com/forum/viewtopic.php?p=10333#10333.
if (getOwner() != null && getOwner().isShowing()) {
Component owner = getOwner();
for (Container p = owner.getParent(); p != null; p = p.getParent()) {
if (p instanceof JPopupMenu) break;
if (p instanceof Window) {
if (!((Window) p).isFocused()) {
boolean success = owner.requestFocusInWindow();
if (!success) {
owner.requestFocus();
}
break;
}
}
}
}
}
/**
* Hides the popup immediately (compare to {@link #hidePopup()} could use animation to hide the popup).
*/
public void hidePopupImmediately() {
hidePopupImmediately(false);
}
/**
* Add an entry to global event queue.
*/
private void addMouseEventHandler() {
if (SecurityUtils.isAWTEventListenerDisabled() || "true".equals(SecurityUtils.getProperty("jide.disableAWTEventListener", "false"))) {
return;
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Toolkit.getDefaultToolkit().addAWTEventListener(_awtEventListener, AWTEvent.MOUSE_EVENT_MASK
| AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.WINDOW_EVENT_MASK | AWTEvent.COMPONENT_EVENT_MASK);
return null;
}
}
);
}
catch (SecurityException e) {
throw new RuntimeException(e);
}
}
/**
* Add an entry to global event queue.
*/
private void removeMouseEventHandler() {
if (SecurityUtils.isAWTEventListenerDisabled() || "true".equals(SecurityUtils.getProperty("jide.disableAWTEventListener", "false"))) {
return;
}
try {
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
Toolkit.getDefaultToolkit().removeAWTEventListener(_awtEventListener);
return null;
}
}
);
}
catch (SecurityException e) {
throw new RuntimeException(e);
}
}
public Component getOwner() {
return _owner;
}
public void setOwner(Component owner) {
if (_owner != owner) {
Component old = _owner;
_owner = owner;
firePropertyChange(OWNER_PROPERTY, old, _owner);
removeExcludedComponent(old);
addExcludedComponent(_owner);
}
}
/**
* Checks if the popup is movable. If yes, it will show the gripper
* so that user can grab it and move the popup. If the popup is attached to its owner,
* moving it will detach from the owner.
*
* @return true if gripper is visible
*/
public boolean isMovable() {
return _movable;
}
/**
* Sets the movable attribute.
*
* @param movable true or false.
*/
public void setMovable(boolean movable) {
boolean old = _movable;
if (old != movable) {
_movable = movable;
firePropertyChange(MOVABLE_PROPERTY, old, _movable);
}
}
/**
* Checks if the popup is resizable. By default, resizable option is true.
* <p/>
* Depending on the detached/attached mode, the resizing behavior
* may be different. If a popup is detached to a component, it only
* allows you to resize from bottom, bottom right and right
* It obviously doesn't make sense to resize from top and top side
* is aligned with the attached component.
* <p/>
* (Notes: in the future we will allow resize from different corner if the
* popup is shown above owner due to not enough space on the screen).
*
* @return if the popup is resizable.
*/
public boolean isResizable() {
return _resizable;
}
/**
* Sets the resizable option.
*
* @param resizable true or false.
*/
public void setResizable(boolean resizable) {
if (_resizable != resizable) {
boolean old = _resizable;
_resizable = resizable;
firePropertyChange(RESIZABLE_PROPERTY, old, _resizable);
}
}
/**
* Checks if the popup is attachable. By default, attachable option is true.
*
* @return if the popup is attachable.
*/
public boolean isAttachable() {
return _attachable;
}
/**
* Sets the attachable option.
*
* @param attachable true or false.
*/
public void setAttachable(boolean attachable) {
if (_attachable != attachable) {
boolean old = _attachable;
_attachable = attachable;
firePropertyChange(ATTACHABLE_PROPERTY, old, _attachable);
}
}
/**
* Checks if the popup is detached.
* <p/>
* A popup has detached and attached mode. When a popup is in attached,
* it will act like it's part of the owner (which can be set using {@link #setOwner(java.awt.Component)}.
* When owner is moved, the popup will be moved.
* If the owner is hidden, the popup will hidden.
* In the other word, it is attached with the owner.
* In detached mode, popup becomes an indenpendent floating window.
* It will stay at the same location regardless if owner is moved.
* It could still be visible when owner is hidden.
* <p/>
*
* @return true if it's detacted. Otherwise false.
*/
public boolean isDetached() {
return _detached;
}
/**
* Changes the popup's detached mode.
*
* @param detached true or false.
*/
public void setDetached(boolean detached) {
if (_detached != detached) {
boolean old = _detached;
_detached = detached;
firePropertyChange("detacted", old, _detached);
if (_window != null) { // todo: check property change
if (_detached) {
if (getPopupBorder() == null) {
_window.setBorder(UIDefaultsLookup.getBorder("Resizable.resizeBorder"));
}
else {
_window.setBorder(getPopupBorder());
}
if (isResizable()) {
_window.getResizable().setResizableCorners(Resizable.ALL);
}
else {
_window.getResizable().setResizableCorners(Resizable.NONE);
}
}
else {
if (getPopupBorder() == null) {
_window.setBorder(UIDefaultsLookup.getBorder("PopupMenu.border"));
}
else {
_window.setBorder(getPopupBorder());
}
if (isResizable()) {
_window.getResizable().setResizableCorners(Resizable.RIGHT | Resizable.LOWER | Resizable.LOWER_RIGHT);
}
else {
_window.getResizable().setResizableCorners(Resizable.NONE);
}
}
}
}
}
/**
* Gets the popup border set by {@link #setPopupBorder(javax.swing.border.Border)}.
*
* @return the border for this popup.
*/
public Border getPopupBorder() {
return _popupBorder;
}
/**
* Sets the border for this popup. Please note a non-empty border is needed if you want the popup to be
* resizable.
*
* @param popupBorder the border for the popup.
*/
public void setPopupBorder(Border popupBorder) {
_popupBorder = popupBorder;
}
/**
* Checks if the popup is transient.
*
* @return true if transient.
* @see #setTransient(boolean)
*/
public boolean isTransient() {
return _transient;
}
/**
* Sets the transient attribute. If a popup is transient, it will hide automatically when mouse is
* clicked outside the popup. Otherwise, it will stay visible until timeout or hidePopup() is called.
*
* @param isTransient true or false.
*/
public void setTransient(boolean isTransient) {
boolean old = _transient;
if (old != isTransient) {
_transient = isTransient;
firePropertyChange(TRANSIENT_PROPERTY, old, isTransient);
}
}
/**
* Gets the time out value, in milliseconds.
*
* @return the time out value, in milliseconds.
*/
public int getTimeout() {
return _timeout;
}
/**
* Sets the time out value, in milliseconds. If you don't want the popup hide
* after the time out, set the value to 0. By default it's 0 meaning it
* will never time out.
* <p/>
* Typically, you call setTimeOut before the popup is visible. But if you do call setTimeOut when popup is
* already visible (which means the timer is running), we will restart the timer using the new time out value you
* just set, even the new time out value is the same as the old one. In the other word, this setTimeOut call
* will always restart the timer if the timer is running.
*
* @param timeout new time out value, in milliseconds. 0 if you don't want popup automatically hides.
*/
public void setTimeout(int timeout) {
_timeout = timeout;
if (_timer != null && _timer.isRunning()) {
startTimeoutTimer(); // this call will restart the timer.
}
}
private void stopTimeoutTimer() {
if (_timer != null) {
_timer.stop();
_timer = null;
// System.out.println("stop");
}
}
private void startTimeoutTimer() {
stopTimeoutTimer();
_timer = new Timer(getTimeout(), new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePopup();
}
});
_timer.setRepeats(false);
_timer.start();
// System.out.println("start");
}
/**
* Gets the default focus component.
*
* @return the default focus component.
*/
public Component getDefaultFocusComponent() {
return _defaultFocusComponent;
}
/**
* Sets the default focus component. Default focus component should be a child component on this popup. It will
* get focus when popup is shown. By setting a non-null component as default focus component, the JWindow that contains the JidePopup will be
* set focusable. Otherwise the JWindow will be non-focusable.
*
* @param defaultFocusComponent the default focus component.
*/
public void setDefaultFocusComponent(Component defaultFocusComponent) {
_defaultFocusComponent = defaultFocusComponent;
}
/**
* Adds a <code>PopupMenu</code> listener which will listen to notification
* messages from the popup portion of the combo box.
* <p/>
* For all standard look and feels shipped with Java 2, the popup list
* portion of combo box is implemented as a <code>JPopupMenu</code>.
* A custom look and feel may not implement it this way and will
* therefore not receive the notification.
*
* @param l the <code>PopupMenuListener</code> to add
*/
public void addPopupMenuListener(PopupMenuListener l) {
listenerList.add(PopupMenuListener.class, l);
}
/**
* Removes a <code>PopupMenuListener</code>.
*
* @param l the <code>PopupMenuListener</code> to remove
* @see #addPopupMenuListener
* @since 1.4
*/
public void removePopupMenuListener(PopupMenuListener l) {
listenerList.remove(PopupMenuListener.class, l);
}
/**
* Returns an array of all the <code>PopupMenuListener</code>s added
* to this JComboBox with addPopupMenuListener().
*
* @return all of the <code>PopupMenuListener</code>s added or an empty
* array if no listeners have been added
* @since 1.4
*/
public PopupMenuListener[] getPopupMenuListeners() {
return (PopupMenuListener[]) listenerList.getListeners(PopupMenuListener.class);
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box will become visible.
* <p/>
* This method is public but should not be called by anything other than
* the UI delegate.
*
* @see #addPopupMenuListener
*/
public void firePopupMenuWillBecomeVisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener) listeners[i + 1]).popupMenuWillBecomeVisible(e);
}
}
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has become invisible.
* <p/>
* This method is public but should not be called by anything other than
* the UI delegate.
*
* @see #addPopupMenuListener
*/
public void firePopupMenuWillBecomeInvisible() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener) listeners[i + 1]).popupMenuWillBecomeInvisible(e);
}
}
}
/**
* Notifies <code>PopupMenuListener</code>s that the popup portion of the
* combo box has been canceled.
* <p/>
* This method is public but should not be called by anything other than
* the UI delegate.
*
* @see #addPopupMenuListener
*/
public void firePopupMenuCanceled() {
Object[] listeners = listenerList.getListenerList();
PopupMenuEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == PopupMenuListener.class) {
if (e == null)
e = new PopupMenuEvent(this);
((PopupMenuListener) listeners[i + 1]).popupMenuCanceled(e);
}
}
}
/**
* Gets the default operation when the owner is moved. The valid values are either {@link #HIDE_ON_MOVED},
* {@link #MOVE_ON_MOVED} or {@link #DO_NOTHING_ON_MOVED}.
*
* @return the default operation when the owner is moved.
*/
public int getDefaultMoveOperation() {
return _defaultMoveOperation;
}
/**
* Sets the default operation when the owner is moved. The valid could be either {@link #HIDE_ON_MOVED},
* {@link #MOVE_ON_MOVED} or {@link #DO_NOTHING_ON_MOVED}.
*
* @param defaultMoveOperation the default operation when the owner is moved.
*/
public void setDefaultMoveOperation(int defaultMoveOperation) {
_defaultMoveOperation = defaultMoveOperation;
}
/**
* Adds a component as excluded component. If a component is an excluded component or descendant of an excluded component, clicking on it will not
* hide the popup.
* <p/>
* For example, AbstractComboBox uses JidePopup to display the popup. If you want to show a JDialog from the popup, you will
* have to add the dialog as excluded component. See below for an example.
* <pre><code>
* JDialog dialog =new JDialog((Frame) JideSwingUtilities.getWindowForComponent(this), true);
* dialog.add(new JTable(10, 4));
* dialog.pack();
* Container ancestorOfClass = SwingUtilities.getAncestorOfClass(JidePopup.class, this); // try to find the JidePopup
* if(ancestorOfClass instanceof JidePopup) {
* ((JidePopup) ancestorOfClass).addExcludedComponent(dialog);
* }
* dialog.setVisible(true);
* if(ancestorOfClass instanceof JidePopup) {
* ((JidePopup) ancestorOfClass).removeExcludedComponent(dialog);
* }
* </code></pre>
*
* @param component the component should be excluded.
*/
public void addExcludedComponent(Component component) {
if (component != null && !_excludedComponents.contains(component)) {
_excludedComponents.add(component);
}
}
/**
* Removes a component from the excluded component list. If a component is an excluded component, clicking on it will not
* hide the popup.
*
* @param component the component was excluded before.
*/
public void removeExcludedComponent(Component component) {
_excludedComponents.remove(component);
}
/**
* Checks if a component is an excluded component. If a component is an excluded component, clicking on it will not
* hide the popup. By default, owner is always the excluded component.
*
* @param component a component.
* @return true if the component is an excluded component.
*/
public boolean isExcludedComponent(Component component) {
boolean contain = _excludedComponents.contains(component);
if (!contain) {
for (int i = 0; i < _excludedComponents.size(); i++) {
Component c = (Component) _excludedComponents.get(i);
if (c instanceof Container) {
if (((Container) c).isAncestorOf(component)) {
return true;
}
}
}
}
return contain;
}
public int getGripperLocation() {
return _gripperLocation;
}
/**
* Sets the gripper location. The valid values are {@link SwingConstants#NORTH},
* {@link SwingConstants#SOUTH}, {@link SwingConstants#EAST}, and {@link SwingConstants#WEST}.
*
* @param gripperLocation the new gripper location.
*/
public void setGripperLocation(int gripperLocation) {
int old = _gripperLocation;
if (old != gripperLocation) {
_gripperLocation = gripperLocation;
firePropertyChange(PROPERTY_GRIPPER_LOCATION, old, gripperLocation);
}
}
}
| true | true | protected void installListeners() {
//David: Adding the MouseEventHandler synchronously causes a strange
// initialization sequence if the popup owner is a tree/table editor:
//
// - The editor gets moved to its initial location based on the cell location,
// generating a COMPONENT_MOVED ComponentEvent.
// - You add the MouseEventHandler, which includes a ComponentEvent listener on
// the owner's hierarcy, including the editor.
// - ComponentEvent is asynchronous. The ComponentEvent generated from moving
// the editor to its initial position was placed on the event queue. So the
// ComponentEvent gets handled by the MouseEventHandler's ComponentEvent
// listener, even though it happened before the listener was added.
//
// I fixed it by calling addMouseEventHandler asynchronously, guaranteeing that
// any previously-generated event it may listen for has been removed from the
// event queue before the listener is added.
//
// This causes a couple of minor problems:
//
// - It is possible that hidePopupImmediately can be called synchronously before
// the asynchronous call to addMouseEventHandler is executed. This can cause
// NPEs because the listener handler methods dereference _window, which is set
// to null in hidePopupImmediately. So I added null checks on _window in the
// listener handler methods.
//
// - The removeMouseEventHandler method is called from hidePopupImmediately.
// That means it could be called before addMouseEventHandler is executed
// asynchronously; that would result in the listener not getting removed. So
// I changed the removeMouseEventHandler to an asynchronous call, as well.
//
// This issue appeared in the 1.8.3 release because you changed the
// COMPONENT_MOVED handler to hide the popup instead of moving it. Since you
// made this an option in the 1.8.4 release, all of this asynchronous code is
// needed.
//
// addMouseEventHandler()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
addMouseEventHandler();
}
});
_componentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
hidePopup();
}
};
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePopupImmediately(true);
if (getOwner() != null) {
getOwner().requestFocus();
}
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
_window.addComponentListener(_componentListener);
_windowListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
hidePopup();
}
};
_window.addWindowListener(_windowListener);
if (getOwner() != null) {
_ownerComponentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
ancestorHidden();
}
public void componentMoved(ComponentEvent e) {
ancestorMoved();
}
};
getOwner().addComponentListener(_ownerComponentListener);
_hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
ancestorHidden();
}
};
getOwner().addHierarchyListener(_hierarchyListener);
}
_popupResizeListener = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
removeComponentListener(_popupResizeListener);
Dimension size = getSize();
if (getPopupBorder() != null) {
Insets borderInsets = getPopupBorder().getBorderInsets(JidePopup.this);
size.width += borderInsets.left + borderInsets.right;
size.height += borderInsets.top + borderInsets.bottom;
}
else if (_window.getBorder() != null) {
Insets borderInsets = _window.getBorder().getBorderInsets(_window);
size.width += borderInsets.left + borderInsets.right;
size.height += borderInsets.top + borderInsets.bottom;
}
_window.setSize(size);
addComponentListener(_popupResizeListener);
}
};
addComponentListener(_popupResizeListener);
}
| protected void installListeners() {
//David: Adding the MouseEventHandler synchronously causes a strange
// initialization sequence if the popup owner is a tree/table editor:
//
// - The editor gets moved to its initial location based on the cell location,
// generating a COMPONENT_MOVED ComponentEvent.
// - You add the MouseEventHandler, which includes a ComponentEvent listener on
// the owner's hierarcy, including the editor.
// - ComponentEvent is asynchronous. The ComponentEvent generated from moving
// the editor to its initial position was placed on the event queue. So the
// ComponentEvent gets handled by the MouseEventHandler's ComponentEvent
// listener, even though it happened before the listener was added.
//
// I fixed it by calling addMouseEventHandler asynchronously, guaranteeing that
// any previously-generated event it may listen for has been removed from the
// event queue before the listener is added.
//
// This causes a couple of minor problems:
//
// - It is possible that hidePopupImmediately can be called synchronously before
// the asynchronous call to addMouseEventHandler is executed. This can cause
// NPEs because the listener handler methods dereference _window, which is set
// to null in hidePopupImmediately. So I added null checks on _window in the
// listener handler methods.
//
// - The removeMouseEventHandler method is called from hidePopupImmediately.
// That means it could be called before addMouseEventHandler is executed
// asynchronously; that would result in the listener not getting removed. So
// I changed the removeMouseEventHandler to an asynchronous call, as well.
//
// This issue appeared in the 1.8.3 release because you changed the
// COMPONENT_MOVED handler to hide the popup instead of moving it. Since you
// made this an option in the 1.8.4 release, all of this asynchronous code is
// needed.
//
// addMouseEventHandler()
SwingUtilities.invokeLater(new Runnable() {
public void run() {
addMouseEventHandler();
}
});
_componentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
hidePopup();
}
};
registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePopupImmediately(true);
if (getOwner() != null) {
getOwner().requestFocus();
}
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
_window.addComponentListener(_componentListener);
_windowListener = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
hidePopup();
}
};
_window.addWindowListener(_windowListener);
if (getOwner() != null) {
_ownerComponentListener = new ComponentAdapter() {
public void componentHidden(ComponentEvent e) {
ancestorHidden();
}
public void componentMoved(ComponentEvent e) {
ancestorMoved();
}
};
getOwner().addComponentListener(_ownerComponentListener);
_hierarchyListener = new HierarchyListener() {
public void hierarchyChanged(HierarchyEvent e) {
ancestorHidden();
}
};
getOwner().addHierarchyListener(_hierarchyListener);
}
_popupResizeListener = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
removeComponentListener(_popupResizeListener);
// Dimension size = getSize();
// Dimension windowSize = new Dimension(size.width,size.height);
// if (getPopupBorder() != null) {
// Insets borderInsets = getPopupBorder().getBorderInsets(JidePopup.this);
// windowSize.width += borderInsets.left + borderInsets.right;
// windowSize.height += borderInsets.top + borderInsets.bottom;
// }
// else if (_window.getBorder() != null) {
// Insets borderInsets = _window.getBorder().getBorderInsets(_window);
// windowSize.width += borderInsets.left + borderInsets.right;
// windowSize.height += borderInsets.top + borderInsets.bottom;
// }
// _window.setSize(windowSize);
// pack is good enough to replace all code above
_window.pack();
addComponentListener(_popupResizeListener);
}
};
addComponentListener(_popupResizeListener);
}
|
diff --git a/org.promasi.client/src/org/promasi/client/playmode/multiplayer/client/clientstate/WaitingGameClientState.java b/org.promasi.client/src/org/promasi/client/playmode/multiplayer/client/clientstate/WaitingGameClientState.java
index 4979931a..3aff0895 100644
--- a/org.promasi.client/src/org/promasi/client/playmode/multiplayer/client/clientstate/WaitingGameClientState.java
+++ b/org.promasi.client/src/org/promasi/client/playmode/multiplayer/client/clientstate/WaitingGameClientState.java
@@ -1,201 +1,202 @@
/**
*
*/
package org.promasi.client.playmode.multiplayer.client.clientstate;
import java.beans.XMLDecoder;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.joda.time.DateTime;
import org.promasi.client.gui.IWaitingGameDialogListener;
import org.promasi.client.gui.WaitingGameDialog;
import org.promasi.client.playmode.multiplayer.AbstractClientState;
import org.promasi.client.playmode.multiplayer.MultiPlayerGame;
import org.promasi.client.playmode.multiplayer.ProMaSiClient;
import org.promasi.protocol.messages.GameCanceledRequest;
import org.promasi.protocol.messages.GameCanceledResponse;
import org.promasi.protocol.messages.GameStartedRequest;
import org.promasi.protocol.messages.GameStartedResponse;
import org.promasi.protocol.messages.LeaveGameRequest;
import org.promasi.protocol.messages.LeaveGameResponse;
import org.promasi.protocol.messages.MessageRequest;
import org.promasi.protocol.messages.UpdateGameListRequest;
import org.promasi.protocol.messages.UpdateGamePlayersListRequest;
import org.promasi.protocol.messages.WrongProtocolResponse;
import org.promasi.utilities.exceptions.NullArgumentException;
/**
* @author m1cRo
*
*/
public class WaitingGameClientState extends AbstractClientState implements IWaitingGameDialogListener
{
/**
*
*/
private WaitingGameDialog _waitingGameDialog;
/**
*
*/
private ProMaSiClient _client;
/**
*
*/
private Shell _shell;
/**
*
*/
private String _gameName;
/**
*
*/
private String _gameDescription;
/**
*
*/
private List<String> _players;
/**
*
* @param client
* @throws NullArgumentException
*/
public WaitingGameClientState(Shell shell,ProMaSiClient client, String gameName, String gameDescription,List<String> players)throws NullArgumentException{
if(client==null){
throw new NullArgumentException("Wrong argument client==null");
}
if(players==null){
throw new NullArgumentException("Wrong argument players==null");
}
if(gameName==null){
throw new NullArgumentException("Wrong argument gameName==null");
}
if(gameDescription==null){
throw new NullArgumentException("Wrong argument gameDescription==null");
}
_client=client;
_shell=shell;
_gameName=gameName;
_gameDescription=gameDescription;
_players=players;
}
/* (non-Javadoc)
* @see org.promasi.playmode.multiplayer.IClientState#onReceive(org.promasi.playmode.multiplayer.ProMaSiClient, java.lang.String)
*/
@Override
public void onReceive(ProMaSiClient client, String recData) {
try{
Object object=new XMLDecoder(new ByteArrayInputStream(recData.getBytes())).readObject();
if(object instanceof GameStartedRequest){
GameStartedRequest request=(GameStartedRequest)object;
if(request.getGameModel()==null || request.getDateTime()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
return;
}
PlayingGameClientState state=new PlayingGameClientState(_shell, new MultiPlayerGame(client),client, request.getGameModel(),new DateTime(request.getDateTime()));
changeClientState(client, state);
client.sendMessage(new GameStartedResponse().serialize());
_waitingGameDialog.close();
}else if(object instanceof UpdateGamePlayersListRequest){
UpdateGamePlayersListRequest request=(UpdateGamePlayersListRequest)object;
_waitingGameDialog.updatePlayersList(request.getPlayers());
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof GameCanceledRequest){
ChooseGameClientState clientState=new ChooseGameClientState(client, _shell, new HashMap<String,String>());
client.sendMessage(new GameCanceledResponse().serialize());
changeClientState(client, clientState);
+ _waitingGameDialog.close();
}else if(object instanceof UpdateGameListRequest){
}else if(object instanceof LeaveGameResponse){
changeClientState(client, new ChooseGameClientState(client, _shell, new HashMap<String,String>()));
}else{
_client.sendMessage(new WrongProtocolResponse().serialize());
_waitingGameDialog.close();
}
}catch(NullArgumentException e){
client.disconnect();
}catch(IllegalArgumentException e){
client.disconnect();
}
}
/* (non-Javadoc)
* @see org.promasi.playmode.multiplayer.IClientState#onSetState(org.promasi.playmode.multiplayer.ProMaSiClient)
*/
@Override
public void onSetState(ProMaSiClient client) {
if(!_shell.isDisposed() && !_shell.getDisplay().isDisposed()){
_shell.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
try {
_waitingGameDialog=new WaitingGameDialog(_shell, SWT.DIALOG_TRIM, _gameName, _gameDescription, WaitingGameClientState.this,_players);
_waitingGameDialog.open();
} catch (NullArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
@Override
public void sendButtonPressed(String messageText) {
_client.sendMessage(new MessageRequest(null, messageText).serialize());
}
@Override
public void onDisconnect(ProMaSiClient client) {
// TODO Auto-generated method stub
}
@Override
public void onConnect(ProMaSiClient client) {
// TODO Auto-generated method stub
}
@Override
public void onConnectionError(ProMaSiClient client) {
// TODO Auto-generated method stub
}
@Override
public void dialogClosed(WaitingGameDialog dialog) {
_client.sendMessage(new LeaveGameRequest().serialize());
}
}
| true | true | public void onReceive(ProMaSiClient client, String recData) {
try{
Object object=new XMLDecoder(new ByteArrayInputStream(recData.getBytes())).readObject();
if(object instanceof GameStartedRequest){
GameStartedRequest request=(GameStartedRequest)object;
if(request.getGameModel()==null || request.getDateTime()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
return;
}
PlayingGameClientState state=new PlayingGameClientState(_shell, new MultiPlayerGame(client),client, request.getGameModel(),new DateTime(request.getDateTime()));
changeClientState(client, state);
client.sendMessage(new GameStartedResponse().serialize());
_waitingGameDialog.close();
}else if(object instanceof UpdateGamePlayersListRequest){
UpdateGamePlayersListRequest request=(UpdateGamePlayersListRequest)object;
_waitingGameDialog.updatePlayersList(request.getPlayers());
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof GameCanceledRequest){
ChooseGameClientState clientState=new ChooseGameClientState(client, _shell, new HashMap<String,String>());
client.sendMessage(new GameCanceledResponse().serialize());
changeClientState(client, clientState);
}else if(object instanceof UpdateGameListRequest){
}else if(object instanceof LeaveGameResponse){
changeClientState(client, new ChooseGameClientState(client, _shell, new HashMap<String,String>()));
}else{
_client.sendMessage(new WrongProtocolResponse().serialize());
_waitingGameDialog.close();
}
}catch(NullArgumentException e){
client.disconnect();
}catch(IllegalArgumentException e){
client.disconnect();
}
}
| public void onReceive(ProMaSiClient client, String recData) {
try{
Object object=new XMLDecoder(new ByteArrayInputStream(recData.getBytes())).readObject();
if(object instanceof GameStartedRequest){
GameStartedRequest request=(GameStartedRequest)object;
if(request.getGameModel()==null || request.getDateTime()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
return;
}
PlayingGameClientState state=new PlayingGameClientState(_shell, new MultiPlayerGame(client),client, request.getGameModel(),new DateTime(request.getDateTime()));
changeClientState(client, state);
client.sendMessage(new GameStartedResponse().serialize());
_waitingGameDialog.close();
}else if(object instanceof UpdateGamePlayersListRequest){
UpdateGamePlayersListRequest request=(UpdateGamePlayersListRequest)object;
_waitingGameDialog.updatePlayersList(request.getPlayers());
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof MessageRequest){
MessageRequest request=(MessageRequest)object;
if(request.getClientId()==null || request.getMessage()==null){
client.sendMessage(new WrongProtocolResponse().serialize());
client.disconnect();
}else{
_waitingGameDialog.messageReceived(request.getClientId(), request.getMessage());
}
}else if(object instanceof GameCanceledRequest){
ChooseGameClientState clientState=new ChooseGameClientState(client, _shell, new HashMap<String,String>());
client.sendMessage(new GameCanceledResponse().serialize());
changeClientState(client, clientState);
_waitingGameDialog.close();
}else if(object instanceof UpdateGameListRequest){
}else if(object instanceof LeaveGameResponse){
changeClientState(client, new ChooseGameClientState(client, _shell, new HashMap<String,String>()));
}else{
_client.sendMessage(new WrongProtocolResponse().serialize());
_waitingGameDialog.close();
}
}catch(NullArgumentException e){
client.disconnect();
}catch(IllegalArgumentException e){
client.disconnect();
}
}
|
diff --git a/NetBeansProjects/LoginScreen/src/loginscreen/EditAccount.java b/NetBeansProjects/LoginScreen/src/loginscreen/EditAccount.java
index 380ca37..f14cab7 100644
--- a/NetBeansProjects/LoginScreen/src/loginscreen/EditAccount.java
+++ b/NetBeansProjects/LoginScreen/src/loginscreen/EditAccount.java
@@ -1,344 +1,344 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package loginscreen;
import java.sql.Connection;
import java.util.Calendar;
/**
*
* @author Chris
*/
public class EditAccount extends javax.swing.JFrame {
/**
* Creates new form EditAccount
*/
Mediator mediator;
Connection conn;
String loginName;
public EditAccount(Mediator m, String l, Connection c) {
mediator = m;
loginName = l;
conn = c;
initComponents();
}
/**
* 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() {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
LeftJPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
RICImgLabel = new javax.swing.JLabel();
RightInnerJpanel = new javax.swing.JPanel();
yearLabel = new javax.swing.JLabel();
semesterLabel = new javax.swing.JLabel();
confirmLabel = new javax.swing.JLabel();
lastNameText = new javax.swing.JTextField();
passwordTextField = new javax.swing.JTextField();
confirmTextField = new javax.swing.JTextField();
firstNameText = new javax.swing.JTextField();
passwordLabel = new javax.swing.JLabel();
firstNameLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
editAccountLabel = new javax.swing.JLabel();
editAccountButton = new javax.swing.JButton();
majorLabel = new javax.swing.JLabel();
yearComboBox = new javax.swing.JComboBox();
lastNameLabel = new javax.swing.JLabel();
emailLabel = new javax.swing.JLabel();
majorComboBox = new javax.swing.JComboBox();
semesterComboBox = new javax.swing.JComboBox();
emailTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
LeftJPanel.setBackground(new java.awt.Color(255, 255, 255));
LeftJPanel.setPreferredSize(new java.awt.Dimension(361, 468));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
RICImgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/index.jpg"))); // NOI18N
RightInnerJpanel.setBackground(new java.awt.Color(255, 255, 255));
RightInnerJpanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
yearLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
//yearLabel.setText("Year:");
yearLabel.setText("Start Year:");
semesterLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
semesterLabel.setText("Semester:");
confirmLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
confirmLabel.setText("Confirm Password:");
passwordLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
passwordLabel.setText("Password:");
firstNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
firstNameLabel.setText("First Name:");
cancelButton.setBackground(new java.awt.Color(255, 0, 0));
cancelButton.setForeground(new java.awt.Color(255, 255, 255));
cancelButton.setText("Cancel");
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelButtonMouseClicked(evt);
}
});
editAccountLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
editAccountLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
editAccountLabel.setText("Edit Account");
editAccountButton.setBackground(new java.awt.Color(0, 0, 255));
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Save Changes");
majorLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
majorLabel.setText("Major:");
lastNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lastNameLabel.setText("Last Name");
emailLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
emailLabel.setText("Email:");
majorComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Computer Science - BA", "Computer Science - BS" }));
semesterComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Fall", "Spring", "Summer" }));
yearComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { Integer.toString(year), Integer.toString(year+1), Integer.toString(year+2), Integer.toString(year+3) }));
firstNameText.setText(Student.getFirstName(loginName, conn));
lastNameText.setText(Student.getLastName(loginName, conn));
emailTextField.setText(Student.getEmail(loginName, conn));
passwordTextField.setText(Student.getPassword(loginName, conn));
confirmTextField.setText(Student.getConfirmPassword(loginName, conn));
semesterComboBox.setSelectedIndex((Integer.parseInt(Student.getSemester(loginName, conn)) - 1));
majorComboBox.setSelectedIndex(18 - Integer.parseInt(Student.getMajorNum(loginName, conn)));
- yearComboBox.setSelectedIndex(Integer.parseInt(Student.getYear(loginName, conn)) - year);
+ //yearComboBox.setSelectedIndex(Integer.parseInt(Student.getYear(loginName, conn)) - year);
javax.swing.GroupLayout RightInnerJpanelLayout = new javax.swing.GroupLayout(RightInnerJpanel);
RightInnerJpanel.setLayout(RightInnerJpanelLayout);
RightInnerJpanelLayout.setHorizontalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lastNameLabel)
.addComponent(majorLabel)
.addComponent(semesterLabel)
.addComponent(yearLabel)
.addComponent(firstNameLabel)
.addComponent(confirmLabel)
.addComponent(passwordLabel))
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(63, 63, 63)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(majorComboBox, 0, 136, Short.MAX_VALUE)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(firstNameText)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastNameText)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, RightInnerJpanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(confirmTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(emailTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(emailLabel))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(editAccountButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)))
.addContainerGap(42, Short.MAX_VALUE))
);
RightInnerJpanelLayout.setVerticalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNameLabel)
.addComponent(firstNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lastNameLabel)
.addComponent(lastNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(majorLabel)
.addComponent(majorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(semesterLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(yearLabel)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(emailLabel)
.addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passwordLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(confirmLabel)
.addComponent(confirmTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(editAccountButton)
.addComponent(cancelButton))
.addGap(61, 61, 61))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(RICImgLabel)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(RICImgLabel)
.addGap(18, 18, 18)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout LeftJPanelLayout = new javax.swing.GroupLayout(LeftJPanel);
LeftJPanel.setLayout(LeftJPanelLayout);
LeftJPanelLayout.setHorizontalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LeftJPanelLayout.createSequentialGroup()
.addContainerGap(153, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(124, Short.MAX_VALUE))
);
LeftJPanelLayout.setVerticalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LeftJPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(46, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 652, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cancelButtonMouseClicked
mediator.showStartup();
}//GEN-LAST:event_cancelButtonMouseClicked
/**
* @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(EditAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(EditAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(EditAccount.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(EditAccount.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() {
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel LeftJPanel;
private javax.swing.JLabel RICImgLabel;
private javax.swing.JPanel RightInnerJpanel;
private javax.swing.JButton cancelButton;
private javax.swing.JLabel confirmLabel;
private javax.swing.JTextField confirmTextField;
private javax.swing.JButton editAccountButton;
private javax.swing.JLabel editAccountLabel;
private javax.swing.JLabel emailLabel;
private javax.swing.JTextField emailTextField;
private javax.swing.JLabel firstNameLabel;
private javax.swing.JTextField firstNameText;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lastNameLabel;
private javax.swing.JTextField lastNameText;
private javax.swing.JComboBox majorComboBox;
private javax.swing.JLabel majorLabel;
private javax.swing.JLabel passwordLabel;
private javax.swing.JTextField passwordTextField;
private javax.swing.JComboBox semesterComboBox;
private javax.swing.JLabel semesterLabel;
private javax.swing.JComboBox yearComboBox;
private javax.swing.JComboBox yearComboBox1;
private javax.swing.JComboBox yearComboBox2;
private javax.swing.JLabel yearLabel;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
LeftJPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
RICImgLabel = new javax.swing.JLabel();
RightInnerJpanel = new javax.swing.JPanel();
yearLabel = new javax.swing.JLabel();
semesterLabel = new javax.swing.JLabel();
confirmLabel = new javax.swing.JLabel();
lastNameText = new javax.swing.JTextField();
passwordTextField = new javax.swing.JTextField();
confirmTextField = new javax.swing.JTextField();
firstNameText = new javax.swing.JTextField();
passwordLabel = new javax.swing.JLabel();
firstNameLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
editAccountLabel = new javax.swing.JLabel();
editAccountButton = new javax.swing.JButton();
majorLabel = new javax.swing.JLabel();
yearComboBox = new javax.swing.JComboBox();
lastNameLabel = new javax.swing.JLabel();
emailLabel = new javax.swing.JLabel();
majorComboBox = new javax.swing.JComboBox();
semesterComboBox = new javax.swing.JComboBox();
emailTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
LeftJPanel.setBackground(new java.awt.Color(255, 255, 255));
LeftJPanel.setPreferredSize(new java.awt.Dimension(361, 468));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
RICImgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/index.jpg"))); // NOI18N
RightInnerJpanel.setBackground(new java.awt.Color(255, 255, 255));
RightInnerJpanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
yearLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
//yearLabel.setText("Year:");
yearLabel.setText("Start Year:");
semesterLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
semesterLabel.setText("Semester:");
confirmLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
confirmLabel.setText("Confirm Password:");
passwordLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
passwordLabel.setText("Password:");
firstNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
firstNameLabel.setText("First Name:");
cancelButton.setBackground(new java.awt.Color(255, 0, 0));
cancelButton.setForeground(new java.awt.Color(255, 255, 255));
cancelButton.setText("Cancel");
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelButtonMouseClicked(evt);
}
});
editAccountLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
editAccountLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
editAccountLabel.setText("Edit Account");
editAccountButton.setBackground(new java.awt.Color(0, 0, 255));
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Save Changes");
majorLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
majorLabel.setText("Major:");
lastNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lastNameLabel.setText("Last Name");
emailLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
emailLabel.setText("Email:");
majorComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Computer Science - BA", "Computer Science - BS" }));
semesterComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Fall", "Spring", "Summer" }));
yearComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { Integer.toString(year), Integer.toString(year+1), Integer.toString(year+2), Integer.toString(year+3) }));
firstNameText.setText(Student.getFirstName(loginName, conn));
lastNameText.setText(Student.getLastName(loginName, conn));
emailTextField.setText(Student.getEmail(loginName, conn));
passwordTextField.setText(Student.getPassword(loginName, conn));
confirmTextField.setText(Student.getConfirmPassword(loginName, conn));
semesterComboBox.setSelectedIndex((Integer.parseInt(Student.getSemester(loginName, conn)) - 1));
majorComboBox.setSelectedIndex(18 - Integer.parseInt(Student.getMajorNum(loginName, conn)));
yearComboBox.setSelectedIndex(Integer.parseInt(Student.getYear(loginName, conn)) - year);
javax.swing.GroupLayout RightInnerJpanelLayout = new javax.swing.GroupLayout(RightInnerJpanel);
RightInnerJpanel.setLayout(RightInnerJpanelLayout);
RightInnerJpanelLayout.setHorizontalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lastNameLabel)
.addComponent(majorLabel)
.addComponent(semesterLabel)
.addComponent(yearLabel)
.addComponent(firstNameLabel)
.addComponent(confirmLabel)
.addComponent(passwordLabel))
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(63, 63, 63)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(majorComboBox, 0, 136, Short.MAX_VALUE)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(firstNameText)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastNameText)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, RightInnerJpanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(confirmTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(emailTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(emailLabel))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(editAccountButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)))
.addContainerGap(42, Short.MAX_VALUE))
);
RightInnerJpanelLayout.setVerticalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNameLabel)
.addComponent(firstNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lastNameLabel)
.addComponent(lastNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(majorLabel)
.addComponent(majorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(semesterLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(yearLabel)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(emailLabel)
.addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passwordLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(confirmLabel)
.addComponent(confirmTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(editAccountButton)
.addComponent(cancelButton))
.addGap(61, 61, 61))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(RICImgLabel)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(RICImgLabel)
.addGap(18, 18, 18)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout LeftJPanelLayout = new javax.swing.GroupLayout(LeftJPanel);
LeftJPanel.setLayout(LeftJPanelLayout);
LeftJPanelLayout.setHorizontalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LeftJPanelLayout.createSequentialGroup()
.addContainerGap(153, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(124, Short.MAX_VALUE))
);
LeftJPanelLayout.setVerticalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LeftJPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(46, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 652, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
LeftJPanel = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
RICImgLabel = new javax.swing.JLabel();
RightInnerJpanel = new javax.swing.JPanel();
yearLabel = new javax.swing.JLabel();
semesterLabel = new javax.swing.JLabel();
confirmLabel = new javax.swing.JLabel();
lastNameText = new javax.swing.JTextField();
passwordTextField = new javax.swing.JTextField();
confirmTextField = new javax.swing.JTextField();
firstNameText = new javax.swing.JTextField();
passwordLabel = new javax.swing.JLabel();
firstNameLabel = new javax.swing.JLabel();
cancelButton = new javax.swing.JButton();
editAccountLabel = new javax.swing.JLabel();
editAccountButton = new javax.swing.JButton();
majorLabel = new javax.swing.JLabel();
yearComboBox = new javax.swing.JComboBox();
lastNameLabel = new javax.swing.JLabel();
emailLabel = new javax.swing.JLabel();
majorComboBox = new javax.swing.JComboBox();
semesterComboBox = new javax.swing.JComboBox();
emailTextField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
LeftJPanel.setBackground(new java.awt.Color(255, 255, 255));
LeftJPanel.setPreferredSize(new java.awt.Dimension(361, 468));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
RICImgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/loginscreen/resources/index.jpg"))); // NOI18N
RightInnerJpanel.setBackground(new java.awt.Color(255, 255, 255));
RightInnerJpanel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
yearLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
//yearLabel.setText("Year:");
yearLabel.setText("Start Year:");
semesterLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
semesterLabel.setText("Semester:");
confirmLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
confirmLabel.setText("Confirm Password:");
passwordLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
passwordLabel.setText("Password:");
firstNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
firstNameLabel.setText("First Name:");
cancelButton.setBackground(new java.awt.Color(255, 0, 0));
cancelButton.setForeground(new java.awt.Color(255, 255, 255));
cancelButton.setText("Cancel");
cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
cancelButtonMouseClicked(evt);
}
});
editAccountLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
editAccountLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
editAccountLabel.setText("Edit Account");
editAccountButton.setBackground(new java.awt.Color(0, 0, 255));
editAccountButton.setForeground(new java.awt.Color(255, 255, 255));
editAccountButton.setText("Save Changes");
majorLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
majorLabel.setText("Major:");
lastNameLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lastNameLabel.setText("Last Name");
emailLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
emailLabel.setText("Email:");
majorComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Computer Science - BA", "Computer Science - BS" }));
semesterComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Fall", "Spring", "Summer" }));
yearComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { Integer.toString(year), Integer.toString(year+1), Integer.toString(year+2), Integer.toString(year+3) }));
firstNameText.setText(Student.getFirstName(loginName, conn));
lastNameText.setText(Student.getLastName(loginName, conn));
emailTextField.setText(Student.getEmail(loginName, conn));
passwordTextField.setText(Student.getPassword(loginName, conn));
confirmTextField.setText(Student.getConfirmPassword(loginName, conn));
semesterComboBox.setSelectedIndex((Integer.parseInt(Student.getSemester(loginName, conn)) - 1));
majorComboBox.setSelectedIndex(18 - Integer.parseInt(Student.getMajorNum(loginName, conn)));
//yearComboBox.setSelectedIndex(Integer.parseInt(Student.getYear(loginName, conn)) - year);
javax.swing.GroupLayout RightInnerJpanelLayout = new javax.swing.GroupLayout(RightInnerJpanel);
RightInnerJpanel.setLayout(RightInnerJpanelLayout);
RightInnerJpanelLayout.setHorizontalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lastNameLabel)
.addComponent(majorLabel)
.addComponent(semesterLabel)
.addComponent(yearLabel)
.addComponent(firstNameLabel)
.addComponent(confirmLabel)
.addComponent(passwordLabel))
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(63, 63, 63)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(majorComboBox, 0, 136, Short.MAX_VALUE)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(firstNameText)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lastNameText)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, RightInnerJpanelLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(passwordTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(confirmTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(emailTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(85, 85, 85)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(emailLabel))
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(editAccountButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton)))
.addContainerGap(42, Short.MAX_VALUE))
);
RightInnerJpanelLayout.setVerticalGroup(
RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(RightInnerJpanelLayout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(editAccountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNameLabel)
.addComponent(firstNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lastNameLabel)
.addComponent(lastNameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(majorLabel)
.addComponent(majorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(semesterLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(semesterComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(yearLabel)
.addComponent(yearComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(emailLabel)
.addComponent(emailTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(passwordLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(confirmLabel)
.addComponent(confirmTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(RightInnerJpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(editAccountButton)
.addComponent(cancelButton))
.addGap(61, 61, 61))
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(79, 79, 79)
.addComponent(RICImgLabel)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(RICImgLabel)
.addGap(18, 18, 18)
.addComponent(RightInnerJpanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout LeftJPanelLayout = new javax.swing.GroupLayout(LeftJPanel);
LeftJPanel.setLayout(LeftJPanelLayout);
LeftJPanelLayout.setHorizontalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LeftJPanelLayout.createSequentialGroup()
.addContainerGap(153, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(124, Short.MAX_VALUE))
);
LeftJPanelLayout.setVerticalGroup(
LeftJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(LeftJPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(46, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 652, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LeftJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/imports/Publisher.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/imports/Publisher.java
index c3126981..8d15635f 100644
--- a/javafx.editor/src/org/netbeans/modules/javafx/editor/imports/Publisher.java
+++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/imports/Publisher.java
@@ -1,180 +1,177 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* Portions Copyrighted 1997-2008 Sun Microsystems, Inc.
*/
package org.netbeans.modules.javafx.editor.imports;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
import org.netbeans.api.javafx.lexer.JFXTokenId;
import org.netbeans.api.lexer.TokenHierarchy;
import org.netbeans.api.lexer.TokenId;
import org.netbeans.api.lexer.TokenSequence;
import org.netbeans.modules.editor.indent.api.Reformat;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.util.logging.Logger;
import javax.swing.text.Caret;
import org.netbeans.api.javafx.editor.Cancellable;
import org.netbeans.api.javafx.editor.SafeTokenSequence;
import org.netbeans.modules.javafx.editor.imports.ImportsModel.Declared;
/**
* The publisher will use the information stored in the {@linkplain ImportsModel} instance
* to modify the given {@linkplain Document} accordingly
* After modification the document will contain only used and valid imports
*
* @author Rastislav Komara (<a href="mailto:moonko@netbeans.orgm">RKo</a>)
* @author Jaroslav Bachorik
* @todo documentation
*/
class Publisher implements Runnable {
private static final class PositionComparator implements Comparator<Declared> {
public int compare(Declared o1, Declared o2) {
if (o1.getStart() < o2.getStart()) return 1;
else if (o1.getStart() > o2.getStart()) return -1;
else return 0;
}
}
private final Document doc;
private static Logger log = Logger.getLogger(Publisher.class.getName());
private final ImportsModel model;
private int origCaret;
private Caret currentCaret;
private Comparator<Declared> importsComparator = new PositionComparator();
public Publisher(Document doc, ImportsModel model, Caret currentCaret, int origCaret) {
this.doc = doc;
this.model = model;
this.origCaret = origCaret;
this.currentCaret = currentCaret;
}
@SuppressWarnings("empty-statement")
public void run() {
SafeTokenSequence<JFXTokenId> ts = getTokenSequence(doc, 0);
// reformat not used for now
Reformat reformat = null;
int offsetDiff = 0;
try {
int offset = (int)(model.getImportsEnd() + 1);
if (offset < 0) {
offset = moveBehindPackage(ts);
}
if (!model.getUnresolved().isEmpty()) {
StringBuilder newImports = new StringBuilder();
ImportsModel.Unresolved[] unresolvedArr = model.getUnresolved().toArray(new ImportsModel.Unresolved[0]);
Arrays.sort(unresolvedArr);
for(ImportsModel.Unresolved unresolved : unresolvedArr) {
if (unresolved.getResolvedName() != null) {
newImports.append("\nimport ").append(unresolved.getResolvedName()).append(";");
}
}
if (newImports.length() > 0) {
- if (offset > 0) {
- newImports.insert(0, '\n');
- }
offsetDiff += newImports.toString().length();
doc.insertString(offset, newImports.toString(), null);
}
}
Set<ImportsModel.Declared> unusedSet = new TreeSet<ImportsModel.Declared>(importsComparator);
unusedSet.addAll(model.getUnusedImports());
for(ImportsModel.Declared unused : unusedSet) {
int end = (int)unused.getEnd();
while (!doc.getText(end++, 1).equals("\n"));
offsetDiff -= (int)(end - unused.getStart());
doc.remove((int)unused.getStart(), (int)(end - unused.getStart()));
}
// reformat = Reformat.get(doc);
// reformat.lock();
// reformat.reformat(0, end.getOffset());
} catch (BadLocationException e) {
log.severe(e.getLocalizedMessage());
} finally {
if (origCaret > model.getImportsEnd()) {
currentCaret.setDot(origCaret + offsetDiff);
}
// if (reformat != null) {
// reformat.unlock();
// }
}
}
@SuppressWarnings({"MethodWithMultipleLoops"})
private int moveBehindPackage(SafeTokenSequence<JFXTokenId> ts) {
boolean wasWS = false;
int lastNonWSOffset = 0;
while (ts.moveNext()) {
JFXTokenId id = ts.token().id();
if (JFXTokenId.isComment(id)
|| id == JFXTokenId.WS) {
if (id == JFXTokenId.WS) {
if (!wasWS) {
lastNonWSOffset = ts.offset() - 1;
wasWS = true;
}
} else {
wasWS= false;
}
continue;
} else if (id == JFXTokenId.PACKAGE) {
moveTo(ts, JFXTokenId.SEMI);
return ts.offset() + 1;
}
break;
}
return lastNonWSOffset;
}
private void moveTo(SafeTokenSequence<JFXTokenId> ts, JFXTokenId id) {
while (ts.moveNext()) {
if (ts.token().id() == id) break;
}
}
@SuppressWarnings({"unchecked"})
private static <JFXTokenId extends TokenId> SafeTokenSequence<JFXTokenId> getTokenSequence(Document doc, int dotPos) {
TokenHierarchy<Document> th = TokenHierarchy.get(doc);
TokenSequence<JFXTokenId> ts_ = (TokenSequence<JFXTokenId>) th.tokenSequence();
SafeTokenSequence<JFXTokenId> ts = new SafeTokenSequence<JFXTokenId>(ts_, doc, Cancellable.Dummy.getInstance());
ts.move(dotPos);
return ts;
}
}
| true | true | public void run() {
SafeTokenSequence<JFXTokenId> ts = getTokenSequence(doc, 0);
// reformat not used for now
Reformat reformat = null;
int offsetDiff = 0;
try {
int offset = (int)(model.getImportsEnd() + 1);
if (offset < 0) {
offset = moveBehindPackage(ts);
}
if (!model.getUnresolved().isEmpty()) {
StringBuilder newImports = new StringBuilder();
ImportsModel.Unresolved[] unresolvedArr = model.getUnresolved().toArray(new ImportsModel.Unresolved[0]);
Arrays.sort(unresolvedArr);
for(ImportsModel.Unresolved unresolved : unresolvedArr) {
if (unresolved.getResolvedName() != null) {
newImports.append("\nimport ").append(unresolved.getResolvedName()).append(";");
}
}
if (newImports.length() > 0) {
if (offset > 0) {
newImports.insert(0, '\n');
}
offsetDiff += newImports.toString().length();
doc.insertString(offset, newImports.toString(), null);
}
}
Set<ImportsModel.Declared> unusedSet = new TreeSet<ImportsModel.Declared>(importsComparator);
unusedSet.addAll(model.getUnusedImports());
for(ImportsModel.Declared unused : unusedSet) {
int end = (int)unused.getEnd();
while (!doc.getText(end++, 1).equals("\n"));
offsetDiff -= (int)(end - unused.getStart());
doc.remove((int)unused.getStart(), (int)(end - unused.getStart()));
}
// reformat = Reformat.get(doc);
// reformat.lock();
// reformat.reformat(0, end.getOffset());
} catch (BadLocationException e) {
log.severe(e.getLocalizedMessage());
} finally {
if (origCaret > model.getImportsEnd()) {
currentCaret.setDot(origCaret + offsetDiff);
}
// if (reformat != null) {
// reformat.unlock();
// }
}
}
| public void run() {
SafeTokenSequence<JFXTokenId> ts = getTokenSequence(doc, 0);
// reformat not used for now
Reformat reformat = null;
int offsetDiff = 0;
try {
int offset = (int)(model.getImportsEnd() + 1);
if (offset < 0) {
offset = moveBehindPackage(ts);
}
if (!model.getUnresolved().isEmpty()) {
StringBuilder newImports = new StringBuilder();
ImportsModel.Unresolved[] unresolvedArr = model.getUnresolved().toArray(new ImportsModel.Unresolved[0]);
Arrays.sort(unresolvedArr);
for(ImportsModel.Unresolved unresolved : unresolvedArr) {
if (unresolved.getResolvedName() != null) {
newImports.append("\nimport ").append(unresolved.getResolvedName()).append(";");
}
}
if (newImports.length() > 0) {
offsetDiff += newImports.toString().length();
doc.insertString(offset, newImports.toString(), null);
}
}
Set<ImportsModel.Declared> unusedSet = new TreeSet<ImportsModel.Declared>(importsComparator);
unusedSet.addAll(model.getUnusedImports());
for(ImportsModel.Declared unused : unusedSet) {
int end = (int)unused.getEnd();
while (!doc.getText(end++, 1).equals("\n"));
offsetDiff -= (int)(end - unused.getStart());
doc.remove((int)unused.getStart(), (int)(end - unused.getStart()));
}
// reformat = Reformat.get(doc);
// reformat.lock();
// reformat.reformat(0, end.getOffset());
} catch (BadLocationException e) {
log.severe(e.getLocalizedMessage());
} finally {
if (origCaret > model.getImportsEnd()) {
currentCaret.setDot(origCaret + offsetDiff);
}
// if (reformat != null) {
// reformat.unlock();
// }
}
}
|
diff --git a/beast-tool/src/main/java/es/upm/dit/gsi/beast/story/testCase/Scenario.java b/beast-tool/src/main/java/es/upm/dit/gsi/beast/story/testCase/Scenario.java
index e9dcee4..645d1d6 100644
--- a/beast-tool/src/main/java/es/upm/dit/gsi/beast/story/testCase/Scenario.java
+++ b/beast-tool/src/main/java/es/upm/dit/gsi/beast/story/testCase/Scenario.java
@@ -1,93 +1,94 @@
package es.upm.dit.gsi.beast.story.testCase;
import jadex.commons.Tuple;
import java.util.ArrayList;
import es.upm.dit.gsi.beast.platform.Connector;
import es.upm.dit.gsi.beast.platform.Messenger;
import es.upm.dit.gsi.beast.platform.PlatformSelector;
/**
* Launches the platform and creates its agents.
* It is related with the GIVEN part of BDD.
*
* @author Jorge Solitario
*/
public abstract class Scenario {
abstract public void startAgents();
Connector connector;
String platform;
Messenger messenger;
/**
* Main constructor of the class, launches the platform
*/
public void startPlatform(String platform){
+ this.platform = platform;
connector = PlatformSelector.getConnector(platform);
connector.launchPlatform();
messenger = PlatformSelector.getMessenger(platform);
startAgents();
}
/**
* Creates a real agent in the platform
*
* @param agent_name The name that the agent is gonna have in the platform
* @param path The path of the description (xml) of the agent
*/
protected void startAgent(String agent_name, String path) {
connector.createAgent(agent_name,path);
}
/**
* It sends one message of requested type to an agent
*
* @param agent_name The name of the agent that receives the message
* @param msgtype The type of the message (SFipa.INFORM - SFipa.REQUEST)
* @param message_content The content of the message
*/
public void sendMessageToAgent(String agent_name, String msgtype, Object message_content) {
String[] names = new String[1];
names[0] = agent_name;
messenger.sendMessageToAgents(names, msgtype, message_content, connector);
}
/**
* The same as above, but this method sends the same message to many agents.
*
* @param agent_name The name of the agent that receives the message
* @param msgtype The type of the message (SFipa.INFORM - SFipa.REQUEST)
* @param message_content The content of the message
*/
public void sendMessageToAgents(String[] agent_name, String msgtype, Object message_content) {
messenger.sendMessageToAgents(agent_name, msgtype, message_content, connector);
}
/**
* It sends one message of requested type to an agent, including some extra
* parameters in the message event, such as ontology or language.
*
* @param agent_name The name of the agent that receives the message
* @param msgtype The type of the message (SFipa.INFORM - SFipa.REQUEST)
* @param message_content The content of the message
* @param properties to add to the message
*/
public void sendMessageToAgentsWithExtraProperties(String agent_name, String msgtype, Object message_content, ArrayList<Tuple> properties) {
String[] names = new String[1];
names[0] = agent_name;
messenger.sendMessageToAgentsWithExtraProperties(names, msgtype, message_content, properties, connector);
}
}
| true | true | public void startPlatform(String platform){
connector = PlatformSelector.getConnector(platform);
connector.launchPlatform();
messenger = PlatformSelector.getMessenger(platform);
startAgents();
}
| public void startPlatform(String platform){
this.platform = platform;
connector = PlatformSelector.getConnector(platform);
connector.launchPlatform();
messenger = PlatformSelector.getMessenger(platform);
startAgents();
}
|
diff --git a/source/RMG/CheckForwardAndReverseRateCoefficients.java b/source/RMG/CheckForwardAndReverseRateCoefficients.java
index e80dab36..1f437f44 100644
--- a/source/RMG/CheckForwardAndReverseRateCoefficients.java
+++ b/source/RMG/CheckForwardAndReverseRateCoefficients.java
@@ -1,433 +1,433 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import jing.chemParser.ChemParser;
public class CheckForwardAndReverseRateCoefficients {
// Assumes less than 401 species are present in the mechanism
static String[] names = new String[400];
static double[][] coeffs = new double[400][14];
static int numR = 0;
static int numP = 0;
static StringBuilder reverseRateCoefficients = new StringBuilder();
public static void main(String args[]) {
// Specify (immediately) to the user what the class assumes
System.out.println("The CheckForwardAndReverseRateCoefficients class makes the following assumptions:\n" +
"\t1) The thermodynamics data for each species (NASA-7 polynomials) is contained in the input file\n" +
"\t2) There are <= 400 species in the entire mechanism\n" +
"\t3) Pressure-dependent reactions, with Chebyshev polynomial (CHEB) or pressure-dependent Arrhenius parameters (PLOG)\n" +
"\t\thave a 1.0\t0.0\t0.0 string in the reaction string line (i.e. A+B(+m)=C(+m) 1.0\t0.0\t0.0\n" +
"\t4) Reverse rate coefficients are calculated for all high-P limit reactions and\n" +
"\t\tfor pressure-dependent reactions with CHEB or PLOG pressure-dependent kinetics only\n");
// Temperature is assumed to have units in Kelvin
String temperatureString = "";
double[] T = new double [10];
for (int i=0; i<10; i++) {
double temp = (1000.0/3000.0) + ((double)i/9.0) * (1000.0/300.0 - 1000.0/3000.0);
T[i] = 1000.0 / temp;
temperatureString += Double.toString(T[i])+"\t";
}
reverseRateCoefficients.append(temperatureString+"\n");
// double[] T = {614.0,614.0,614.0,614.0,614.0,629.0,643.0,678.0,713.0,749.0,784.0,854.0,930.0,1010.0,1100.0,1250.0,1350.0,1440.0,1510.0,1570.0,1640.0,1790.0,1970.0,2030.0,2090.0,2110.0,2130.0,2170.0,2180.0,2210.0,2220.0,2220.0,2220.0,2220.0,2210.0,2210.0,2210.0,2200.0,2190.0,2180.0,2170.0,2160.0,2150.0,2150.0,2140.0,2140.0,2140.0,2140.0,2130.0,2130.0,2130.0,2120.0,2120.0,2120.0,2120.0,2110.0,2110.0,2110.0,2110.0,2110.0,2100.0,2100.0,2100.0,2090.0,2080.0,2080.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2000.0,2000.0,1990.0,1980.0,1970.0,1970.0,1960.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0};
// double[] T = {681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,682.0,683.0,684.0,687.0,693.0,703.0,712.0,730.0,749.0,767.0,786.0,823.0,860.0,897.0,934.0,1000.0,1060.0,1120.0,1170.0,1230.0,1320.0,1370.0,1410.0,1440.0,1480.0,1550.0,1660.0,1760.0,1850.0,1920.0,1960.0,2060.0,2110.0,2150.0,2200.0,2240.0,2260.0,2260.0,2250.0,2250.0,2240.0,2240.0,2230.0,2220.0,2210.0,2200.0,2190.0,2180.0,2180.0,2180.0,2180.0,2180.0,2180.0,2170.0,2170.0,2170.0,2170.0,2170.0,2170.0,2160.0,2160.0,2150.0,2150.0,2140.0,2140.0,2130.0,2130.0,2120.0,2120.0,2110.0,2110.0,2100.0,2100.0,2090.0,2090.0,2080.0,2080.0,2070.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2010.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0};
// double[] T = {2.95E+02, 2.95E+02, 2.95E+02, 2.95E+02, 6.12E+02, 9.28E+02, 1.24E+03, 1.56E+03, 1.88E+03, 2.19E+03, 2.19E+03, 2.19E+03};
// Pressure is assumed to have units in atm
// double[] Pressure = {0.03947692};
double[] Pressure = {1};
// Read in the chem.inp file
try {
FileReader fr_thermodat = new FileReader(args[0]);
BufferedReader br_thermodat = new BufferedReader(fr_thermodat);
String line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Continue reading in the file until "THERMO" is read in
boolean foundThermo = false;
while (!foundThermo) {
line = ChemParser.readMeaningfulLine(br_thermodat, true);
if (line.startsWith("THERMO")) {
foundThermo = true;
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line contains the global Tmin, Tmax, Tmid
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line should have thermo (or comments)
}
}
int counter = 0;
// Read in all information
while (line != null && !line.equals("END")) {
if (!line.startsWith("!")) {
// Thermo data for each species stored in 4 consecutive lines
String speciesName = line.substring(0,16);
StringTokenizer st_chemkinname = new StringTokenizer(speciesName);
names[counter] = st_chemkinname.nextToken().trim();
// String lowTstring = line.substring(46,56);
// double lowT = Double.parseDouble(lowTstring.trim());
// String highTstring = line.substring(56,66);
// double highT = Double.parseDouble(highTstring.trim());
// String midTstring = line.substring(66,74);
// double midT = Double.parseDouble(midTstring.trim());
// Read in the coefficients
for (int numLines=0; numLines<2; ++numLines) {
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<5; ++numcoeffs) {
coeffs[counter][5*numLines+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<4; ++numcoeffs) {
coeffs[counter][10+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
++counter;
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
// line should be END; next line should be REACTIONS
line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Determine what units Ea is in
StringTokenizer st = new StringTokenizer(line);
double R = 1.987;
while (st.hasMoreTokens()) {
String nextToken = st.nextToken().toLowerCase();
if (nextToken.equals("kcal/mol")) R = 1.987e-3;
else if (nextToken.equals("kj/mol")) R = 8.314e-3;
else if (nextToken.equals("j/mol")) R = 8.314;
}
// next line should have kinetic info
line = ChemParser.readMeaningfulLine(br_thermodat, true);
while (line != null && !line.equals("END")) {
boolean reversible = true;
if (!line.startsWith("!")&& !line.toLowerCase().contains("low") && !line.toLowerCase().contains("troe") && !line.toLowerCase().contains("dup") && !line.toLowerCase().contains("plog") && !line.contains("CHEB")) {
String rxnString = "";
String fullRxnString = line;
int[] reactsIndex = new int[3];
int[] prodsIndex = new int[3];
String shortRxnString = "";
double A = 0.0;
double n = 0.0;
double E = 0.0;
double[] logk = new double[T.length];
boolean chebyshevRate = false;
boolean rmgRate = false;
boolean plogRate = false;
// Find all Chebyshev rate coefficients
- if (line.contains("1.0E0 0.0 0.0")) {
+ if (line.contains("1.0E0 0.0 0.0") || line.contains("1.000e+00 0.00 0.00")) {
st = new StringTokenizer(line);
rxnString = st.nextToken();
shortRxnString = rxnString;
String[] reactsANDprods = rxnString.split("=");
if (shortRxnString.contains("(+m)")) {
chebyshevRate = true;
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
numR = determineNumberOfSpecies(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
numP = determineNumberOfSpecies(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
line = ChemParser.readUncommentLine(br_thermodat); // TCHEB & PCHEB info
while (line.startsWith("!")) {
line = ChemParser.readUncommentLine(br_thermodat);
}
StringTokenizer st_cheb = new StringTokenizer(line,"/");
String currentToken = st_cheb.nextToken(); // TCHEB
StringTokenizer st_values = new StringTokenizer(st_cheb.nextToken());
double Tmin = Double.parseDouble(st_values.nextToken());
double Tmax = Double.parseDouble(st_values.nextToken());
double[] Ttilda = computeTtilda(T,Tmin,Tmax);
currentToken = st_cheb.nextToken(); // PCHEB
st_values = new StringTokenizer(st_cheb.nextToken());
double Pmin = Double.parseDouble(st_values.nextToken());
double Pmax = Double.parseDouble(st_values.nextToken());
double[] Ptilda = computePtilda(Pressure,Pmin,Pmax);
line = ChemParser.readUncommentLine(br_thermodat); // # of basis set info
st_cheb = new StringTokenizer(line,"/");
currentToken = st_cheb.nextToken();
st_values = new StringTokenizer(st_cheb.nextToken());
int nT = Integer.parseInt(st_values.nextToken());
int nP = Integer.parseInt(st_values.nextToken());
// Extract the coefficients
double[] coeffs = new double[nT*nP];
int coeffCounter = 0;
while (coeffCounter < nT*nP) {
line = ChemParser.readUncommentLine(br_thermodat);
String[] splitSlashes = line.split("/");
StringTokenizer st_coeffs = new StringTokenizer(splitSlashes[1]);
while (st_coeffs.hasMoreTokens()) {
coeffs[coeffCounter] = Double.parseDouble(st_coeffs.nextToken().trim());
++coeffCounter;
}
}
double[][] phiT = computephi(Ttilda,nT);
double[][] phiP = computephi(Ptilda,nP);
// Compute k(T,P)
for (int k=0; k<T.length; k++) {
for (int i=0; i<nT; i++) {
for (int j=0; j<nP; j++) {
logk[k] += coeffs[i*nP+j] * phiT[i][k] * phiP[j][0];
}
}
}
String output = "";
for (int k=0; k<T.length; k++) {
output += logk[k] + "\t";
}
// System.out.println(output + rxnString);
for (int k=0; k<T.length; k++) {
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
} else {
plogRate = true; // Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
line = ChemParser.readUncommentLine(br_thermodat); // Begin reading PLOG line
while (line != null && line.startsWith("PLOG")) {
StringTokenizer st_plog = new StringTokenizer(line,"/");
String temporaryString = st_plog.nextToken();
StringTokenizer st_plog_info = new StringTokenizer(st_plog.nextToken());
String plog_pressure = st_plog_info.nextToken();
double plog_A = Double.parseDouble(st_plog_info.nextToken());
double plog_n = Double.parseDouble(st_plog_info.nextToken());
double plog_E = Double.parseDouble(st_plog_info.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(plog_A * Math.pow(T[k],plog_n) * Math.exp(-plog_E/R/T[k]));//***note: PLOG uses the same units for Ea and A as Arrhenius expressions; see https://github.com/GreenGroup/RMG-Java/commit/2947e7b8d5b1e3e19543f2489990fa42e43ecad2#commitcomment-844009
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], (fullRxnString+"\t"+plog_pressure));
}
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,(fullRxnString+"\t"+plog_pressure),(shortRxnString+"\t"+plog_pressure));
line = ChemParser.readUncommentLine(br_thermodat);
}
}
}
else if (line.contains("(+m)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+m\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("(+M)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+M\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+m")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+m");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+M=")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+M\\=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
StringTokenizer removeComments = new StringTokenizer(sepStrings[1]);
String inputString = removeComments.nextToken();
prodsIndex = determineSpeciesIndex(inputString.substring(0,inputString.length()-2));
}
else if (line.contains("=")) {
rmgRate = true;
shortRxnString = line;
st = new StringTokenizer(line);
shortRxnString = st.nextToken();
if (shortRxnString.contains("=>")) reversible = false;
A = Double.parseDouble(st.nextToken());
n = Double.parseDouble(st.nextToken());
E = Double.parseDouble(st.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
output += logk[k] + "\t";
}
// System.out.println(output + shortRxnString);
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
String[] reactsANDprods = shortRxnString.split("=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
}
// Calculate G_RT
if (rmgRate || chebyshevRate) {
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,fullRxnString,shortRxnString);
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
} catch (FileNotFoundException e) {
System.err.println("File was not found: " + args[0] + "\n");
}
try {
File reversek = new File("reverseRateCoefficients.txt");
FileWriter fw_rxns = new FileWriter(reversek);
fw_rxns.write(reverseRateCoefficients.toString());
fw_rxns.close();
}
catch (IOException e) {
System.out.println("Could not write reverseRateCoefficients.txt files");
System.exit(0);
}
}
public static int[] determineSpeciesIndex(String reactsORprods) {
if (reactsORprods.startsWith(">"))
reactsORprods = reactsORprods.substring(1,reactsORprods.length());
int[] speciesIndex = new int[3];
int speciesCounter = 0;
StringTokenizer st_reacts = new StringTokenizer(reactsORprods,"+");
while (st_reacts.hasMoreTokens()) {
String reactantString = st_reacts.nextToken();
boolean groupedSpecies = false;
if (reactantString.startsWith("2")) {
reactantString = reactantString.substring(1,reactantString.length());
groupedSpecies = true;
}
boolean found = false;
for (int numSpecies=0; numSpecies<names.length; numSpecies++) {
if (reactantString.equals(names[numSpecies])) {
speciesIndex[speciesCounter]=numSpecies;
++speciesCounter;
if (groupedSpecies) {
speciesIndex[speciesCounter]=numSpecies;
++speciesCounter;
}
found = true;
break;
}
}
if (!found) {
System.err.println("Could not find thermo for species: " + reactantString);
// System.exit(0);
}
}
return speciesIndex;
}
public static int determineNumberOfSpecies(String reactsORprods) {
StringTokenizer st_reacts = new StringTokenizer(reactsORprods,"+");
int numSpecies = 0;
while (st_reacts.hasMoreTokens()) {
++numSpecies;
String tempString = st_reacts.nextToken();
if (tempString.startsWith("2")) ++numSpecies;
}
return numSpecies;
}
public static double[] computeTtilda(double[] T, double Tmin, double Tmax) {
double[] Ttilda = new double[T.length];
for (int i=0; i<T.length; i++) {
if (T[i] > Tmax) T[i] = Tmax;
Ttilda[i] = (2/T[i] - 1/Tmin - 1/Tmax) / (1/Tmax - 1/Tmin);
}
return Ttilda;
}
public static double[] computePtilda(double[] P, double Pmin, double Pmax) {
double[] Ptilda = new double[P.length];
for (int i=0; i<P.length; i++) {
Ptilda[i] = (2*Math.log10(P[i]) - Math.log10(Pmin) - Math.log10(Pmax)) / (Math.log10(Pmax) - Math.log10(Pmin));
}
return Ptilda;
}
public static double[][] computephi(double[] argumentX, int maxCounter) {
if (argumentX[0] > 1.0) argumentX[0] = 1.0;
double[][] phi = new double[maxCounter][argumentX.length];
for (int j=0; j<argumentX.length; j++) {
for (int i=0; i<maxCounter; i++) {
phi[i][j] = Math.cos(i*Math.acos(argumentX[j]));
}
}
return phi;
}
public static void calculate_G_RT(double[] T, int[] reactsIndex, int[] prodsIndex, boolean reversible, double[] logk, String fullRxnString, String shortRxnString) {
double[] logKeq = new double[T.length];
for (int iii=0; iii<T.length; iii++) {
double H_RT = 0; double S_R = 0; int coeffsCounter = 0;
double Temperature = T[iii];
if (Temperature < 1000.0) coeffsCounter = 0;
else coeffsCounter = -7;
for (int numReacts=0; numReacts<numR; numReacts++) {
H_RT -= coeffs[reactsIndex[numReacts]][coeffsCounter+7] +
coeffs[reactsIndex[numReacts]][coeffsCounter+8]*Temperature/2 +
coeffs[reactsIndex[numReacts]][coeffsCounter+9]*Temperature*Temperature/3 +
coeffs[reactsIndex[numReacts]][coeffsCounter+10]*Temperature*Temperature*Temperature/4 +
coeffs[reactsIndex[numReacts]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/5 +
coeffs[reactsIndex[numReacts]][coeffsCounter+12]/Temperature;
S_R -= coeffs[reactsIndex[numReacts]][coeffsCounter+7]*Math.log(Temperature) +
coeffs[reactsIndex[numReacts]][coeffsCounter+8]*Temperature +
coeffs[reactsIndex[numReacts]][coeffsCounter+9]*Temperature*Temperature/2 +
coeffs[reactsIndex[numReacts]][coeffsCounter+10]*Temperature*Temperature*Temperature/3 +
coeffs[reactsIndex[numReacts]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/4 +
coeffs[reactsIndex[numReacts]][coeffsCounter+13];
}
for (int numProds=0; numProds<numP; numProds++) {
H_RT += coeffs[prodsIndex[numProds]][coeffsCounter+7] +
coeffs[prodsIndex[numProds]][coeffsCounter+8]*Temperature/2 +
coeffs[prodsIndex[numProds]][coeffsCounter+9]*Temperature*Temperature/3 +
coeffs[prodsIndex[numProds]][coeffsCounter+10]*Temperature*Temperature*Temperature/4 +
coeffs[prodsIndex[numProds]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/5 +
coeffs[prodsIndex[numProds]][coeffsCounter+12]/Temperature;
S_R += coeffs[prodsIndex[numProds]][coeffsCounter+7]*Math.log(Temperature) +
coeffs[prodsIndex[numProds]][coeffsCounter+8]*Temperature +
coeffs[prodsIndex[numProds]][coeffsCounter+9]*Temperature*Temperature/2 +
coeffs[prodsIndex[numProds]][coeffsCounter+10]*Temperature*Temperature*Temperature/3 +
coeffs[prodsIndex[numProds]][coeffsCounter+11]*Temperature*Temperature*Temperature*Temperature/4 +
coeffs[prodsIndex[numProds]][coeffsCounter+13];
}
logKeq[iii] = Math.log10(Math.exp(1))*(-H_RT + S_R) + (numP-numR)*Math.log10(1.0/82.06/Temperature);
if (reversible) {
if (logk[iii] - logKeq[iii] > 15)
System.out.format("logkr = %4.2f at T = %4.0fK for %s\n", (logk[iii]-logKeq[iii]), T[iii], fullRxnString);
}
// Check if Ea is sensible
// if (rmgRate && iii==T.length-1) {
// double deltaHrxn = H_RT * R * T[iii];
// double sensible = E - deltaHrxn;
// if (sensible < 0.0)
// System.out.println("Ea - deltaHrxn = " + sensible + " for " + shortRxnString);
// }
}
String output = "";
for (int iii=0; iii<T.length; iii++) {
output += (logk[iii] - logKeq[iii]) + "\t";
}
// System.out.println(output + shortRxnString);
reverseRateCoefficients.append(output + shortRxnString + "\n");
}
}
| true | true | public static void main(String args[]) {
// Specify (immediately) to the user what the class assumes
System.out.println("The CheckForwardAndReverseRateCoefficients class makes the following assumptions:\n" +
"\t1) The thermodynamics data for each species (NASA-7 polynomials) is contained in the input file\n" +
"\t2) There are <= 400 species in the entire mechanism\n" +
"\t3) Pressure-dependent reactions, with Chebyshev polynomial (CHEB) or pressure-dependent Arrhenius parameters (PLOG)\n" +
"\t\thave a 1.0\t0.0\t0.0 string in the reaction string line (i.e. A+B(+m)=C(+m) 1.0\t0.0\t0.0\n" +
"\t4) Reverse rate coefficients are calculated for all high-P limit reactions and\n" +
"\t\tfor pressure-dependent reactions with CHEB or PLOG pressure-dependent kinetics only\n");
// Temperature is assumed to have units in Kelvin
String temperatureString = "";
double[] T = new double [10];
for (int i=0; i<10; i++) {
double temp = (1000.0/3000.0) + ((double)i/9.0) * (1000.0/300.0 - 1000.0/3000.0);
T[i] = 1000.0 / temp;
temperatureString += Double.toString(T[i])+"\t";
}
reverseRateCoefficients.append(temperatureString+"\n");
// double[] T = {614.0,614.0,614.0,614.0,614.0,629.0,643.0,678.0,713.0,749.0,784.0,854.0,930.0,1010.0,1100.0,1250.0,1350.0,1440.0,1510.0,1570.0,1640.0,1790.0,1970.0,2030.0,2090.0,2110.0,2130.0,2170.0,2180.0,2210.0,2220.0,2220.0,2220.0,2220.0,2210.0,2210.0,2210.0,2200.0,2190.0,2180.0,2170.0,2160.0,2150.0,2150.0,2140.0,2140.0,2140.0,2140.0,2130.0,2130.0,2130.0,2120.0,2120.0,2120.0,2120.0,2110.0,2110.0,2110.0,2110.0,2110.0,2100.0,2100.0,2100.0,2090.0,2080.0,2080.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2000.0,2000.0,1990.0,1980.0,1970.0,1970.0,1960.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0};
// double[] T = {681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,682.0,683.0,684.0,687.0,693.0,703.0,712.0,730.0,749.0,767.0,786.0,823.0,860.0,897.0,934.0,1000.0,1060.0,1120.0,1170.0,1230.0,1320.0,1370.0,1410.0,1440.0,1480.0,1550.0,1660.0,1760.0,1850.0,1920.0,1960.0,2060.0,2110.0,2150.0,2200.0,2240.0,2260.0,2260.0,2250.0,2250.0,2240.0,2240.0,2230.0,2220.0,2210.0,2200.0,2190.0,2180.0,2180.0,2180.0,2180.0,2180.0,2180.0,2170.0,2170.0,2170.0,2170.0,2170.0,2170.0,2160.0,2160.0,2150.0,2150.0,2140.0,2140.0,2130.0,2130.0,2120.0,2120.0,2110.0,2110.0,2100.0,2100.0,2090.0,2090.0,2080.0,2080.0,2070.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2010.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0};
// double[] T = {2.95E+02, 2.95E+02, 2.95E+02, 2.95E+02, 6.12E+02, 9.28E+02, 1.24E+03, 1.56E+03, 1.88E+03, 2.19E+03, 2.19E+03, 2.19E+03};
// Pressure is assumed to have units in atm
// double[] Pressure = {0.03947692};
double[] Pressure = {1};
// Read in the chem.inp file
try {
FileReader fr_thermodat = new FileReader(args[0]);
BufferedReader br_thermodat = new BufferedReader(fr_thermodat);
String line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Continue reading in the file until "THERMO" is read in
boolean foundThermo = false;
while (!foundThermo) {
line = ChemParser.readMeaningfulLine(br_thermodat, true);
if (line.startsWith("THERMO")) {
foundThermo = true;
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line contains the global Tmin, Tmax, Tmid
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line should have thermo (or comments)
}
}
int counter = 0;
// Read in all information
while (line != null && !line.equals("END")) {
if (!line.startsWith("!")) {
// Thermo data for each species stored in 4 consecutive lines
String speciesName = line.substring(0,16);
StringTokenizer st_chemkinname = new StringTokenizer(speciesName);
names[counter] = st_chemkinname.nextToken().trim();
// String lowTstring = line.substring(46,56);
// double lowT = Double.parseDouble(lowTstring.trim());
// String highTstring = line.substring(56,66);
// double highT = Double.parseDouble(highTstring.trim());
// String midTstring = line.substring(66,74);
// double midT = Double.parseDouble(midTstring.trim());
// Read in the coefficients
for (int numLines=0; numLines<2; ++numLines) {
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<5; ++numcoeffs) {
coeffs[counter][5*numLines+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<4; ++numcoeffs) {
coeffs[counter][10+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
++counter;
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
// line should be END; next line should be REACTIONS
line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Determine what units Ea is in
StringTokenizer st = new StringTokenizer(line);
double R = 1.987;
while (st.hasMoreTokens()) {
String nextToken = st.nextToken().toLowerCase();
if (nextToken.equals("kcal/mol")) R = 1.987e-3;
else if (nextToken.equals("kj/mol")) R = 8.314e-3;
else if (nextToken.equals("j/mol")) R = 8.314;
}
// next line should have kinetic info
line = ChemParser.readMeaningfulLine(br_thermodat, true);
while (line != null && !line.equals("END")) {
boolean reversible = true;
if (!line.startsWith("!")&& !line.toLowerCase().contains("low") && !line.toLowerCase().contains("troe") && !line.toLowerCase().contains("dup") && !line.toLowerCase().contains("plog") && !line.contains("CHEB")) {
String rxnString = "";
String fullRxnString = line;
int[] reactsIndex = new int[3];
int[] prodsIndex = new int[3];
String shortRxnString = "";
double A = 0.0;
double n = 0.0;
double E = 0.0;
double[] logk = new double[T.length];
boolean chebyshevRate = false;
boolean rmgRate = false;
boolean plogRate = false;
// Find all Chebyshev rate coefficients
if (line.contains("1.0E0 0.0 0.0")) {
st = new StringTokenizer(line);
rxnString = st.nextToken();
shortRxnString = rxnString;
String[] reactsANDprods = rxnString.split("=");
if (shortRxnString.contains("(+m)")) {
chebyshevRate = true;
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
numR = determineNumberOfSpecies(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
numP = determineNumberOfSpecies(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
line = ChemParser.readUncommentLine(br_thermodat); // TCHEB & PCHEB info
while (line.startsWith("!")) {
line = ChemParser.readUncommentLine(br_thermodat);
}
StringTokenizer st_cheb = new StringTokenizer(line,"/");
String currentToken = st_cheb.nextToken(); // TCHEB
StringTokenizer st_values = new StringTokenizer(st_cheb.nextToken());
double Tmin = Double.parseDouble(st_values.nextToken());
double Tmax = Double.parseDouble(st_values.nextToken());
double[] Ttilda = computeTtilda(T,Tmin,Tmax);
currentToken = st_cheb.nextToken(); // PCHEB
st_values = new StringTokenizer(st_cheb.nextToken());
double Pmin = Double.parseDouble(st_values.nextToken());
double Pmax = Double.parseDouble(st_values.nextToken());
double[] Ptilda = computePtilda(Pressure,Pmin,Pmax);
line = ChemParser.readUncommentLine(br_thermodat); // # of basis set info
st_cheb = new StringTokenizer(line,"/");
currentToken = st_cheb.nextToken();
st_values = new StringTokenizer(st_cheb.nextToken());
int nT = Integer.parseInt(st_values.nextToken());
int nP = Integer.parseInt(st_values.nextToken());
// Extract the coefficients
double[] coeffs = new double[nT*nP];
int coeffCounter = 0;
while (coeffCounter < nT*nP) {
line = ChemParser.readUncommentLine(br_thermodat);
String[] splitSlashes = line.split("/");
StringTokenizer st_coeffs = new StringTokenizer(splitSlashes[1]);
while (st_coeffs.hasMoreTokens()) {
coeffs[coeffCounter] = Double.parseDouble(st_coeffs.nextToken().trim());
++coeffCounter;
}
}
double[][] phiT = computephi(Ttilda,nT);
double[][] phiP = computephi(Ptilda,nP);
// Compute k(T,P)
for (int k=0; k<T.length; k++) {
for (int i=0; i<nT; i++) {
for (int j=0; j<nP; j++) {
logk[k] += coeffs[i*nP+j] * phiT[i][k] * phiP[j][0];
}
}
}
String output = "";
for (int k=0; k<T.length; k++) {
output += logk[k] + "\t";
}
// System.out.println(output + rxnString);
for (int k=0; k<T.length; k++) {
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
} else {
plogRate = true; // Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
line = ChemParser.readUncommentLine(br_thermodat); // Begin reading PLOG line
while (line != null && line.startsWith("PLOG")) {
StringTokenizer st_plog = new StringTokenizer(line,"/");
String temporaryString = st_plog.nextToken();
StringTokenizer st_plog_info = new StringTokenizer(st_plog.nextToken());
String plog_pressure = st_plog_info.nextToken();
double plog_A = Double.parseDouble(st_plog_info.nextToken());
double plog_n = Double.parseDouble(st_plog_info.nextToken());
double plog_E = Double.parseDouble(st_plog_info.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(plog_A * Math.pow(T[k],plog_n) * Math.exp(-plog_E/R/T[k]));//***note: PLOG uses the same units for Ea and A as Arrhenius expressions; see https://github.com/GreenGroup/RMG-Java/commit/2947e7b8d5b1e3e19543f2489990fa42e43ecad2#commitcomment-844009
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], (fullRxnString+"\t"+plog_pressure));
}
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,(fullRxnString+"\t"+plog_pressure),(shortRxnString+"\t"+plog_pressure));
line = ChemParser.readUncommentLine(br_thermodat);
}
}
}
else if (line.contains("(+m)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+m\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("(+M)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+M\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+m")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+m");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+M=")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+M\\=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
StringTokenizer removeComments = new StringTokenizer(sepStrings[1]);
String inputString = removeComments.nextToken();
prodsIndex = determineSpeciesIndex(inputString.substring(0,inputString.length()-2));
}
else if (line.contains("=")) {
rmgRate = true;
shortRxnString = line;
st = new StringTokenizer(line);
shortRxnString = st.nextToken();
if (shortRxnString.contains("=>")) reversible = false;
A = Double.parseDouble(st.nextToken());
n = Double.parseDouble(st.nextToken());
E = Double.parseDouble(st.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
output += logk[k] + "\t";
}
// System.out.println(output + shortRxnString);
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
String[] reactsANDprods = shortRxnString.split("=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
}
// Calculate G_RT
if (rmgRate || chebyshevRate) {
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,fullRxnString,shortRxnString);
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
} catch (FileNotFoundException e) {
System.err.println("File was not found: " + args[0] + "\n");
}
try {
File reversek = new File("reverseRateCoefficients.txt");
FileWriter fw_rxns = new FileWriter(reversek);
fw_rxns.write(reverseRateCoefficients.toString());
fw_rxns.close();
}
catch (IOException e) {
System.out.println("Could not write reverseRateCoefficients.txt files");
System.exit(0);
}
}
| public static void main(String args[]) {
// Specify (immediately) to the user what the class assumes
System.out.println("The CheckForwardAndReverseRateCoefficients class makes the following assumptions:\n" +
"\t1) The thermodynamics data for each species (NASA-7 polynomials) is contained in the input file\n" +
"\t2) There are <= 400 species in the entire mechanism\n" +
"\t3) Pressure-dependent reactions, with Chebyshev polynomial (CHEB) or pressure-dependent Arrhenius parameters (PLOG)\n" +
"\t\thave a 1.0\t0.0\t0.0 string in the reaction string line (i.e. A+B(+m)=C(+m) 1.0\t0.0\t0.0\n" +
"\t4) Reverse rate coefficients are calculated for all high-P limit reactions and\n" +
"\t\tfor pressure-dependent reactions with CHEB or PLOG pressure-dependent kinetics only\n");
// Temperature is assumed to have units in Kelvin
String temperatureString = "";
double[] T = new double [10];
for (int i=0; i<10; i++) {
double temp = (1000.0/3000.0) + ((double)i/9.0) * (1000.0/300.0 - 1000.0/3000.0);
T[i] = 1000.0 / temp;
temperatureString += Double.toString(T[i])+"\t";
}
reverseRateCoefficients.append(temperatureString+"\n");
// double[] T = {614.0,614.0,614.0,614.0,614.0,629.0,643.0,678.0,713.0,749.0,784.0,854.0,930.0,1010.0,1100.0,1250.0,1350.0,1440.0,1510.0,1570.0,1640.0,1790.0,1970.0,2030.0,2090.0,2110.0,2130.0,2170.0,2180.0,2210.0,2220.0,2220.0,2220.0,2220.0,2210.0,2210.0,2210.0,2200.0,2190.0,2180.0,2170.0,2160.0,2150.0,2150.0,2140.0,2140.0,2140.0,2140.0,2130.0,2130.0,2130.0,2120.0,2120.0,2120.0,2120.0,2110.0,2110.0,2110.0,2110.0,2110.0,2100.0,2100.0,2100.0,2090.0,2080.0,2080.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2000.0,2000.0,1990.0,1980.0,1970.0,1970.0,1960.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0,1950.0};
// double[] T = {681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,681.0,682.0,683.0,684.0,687.0,693.0,703.0,712.0,730.0,749.0,767.0,786.0,823.0,860.0,897.0,934.0,1000.0,1060.0,1120.0,1170.0,1230.0,1320.0,1370.0,1410.0,1440.0,1480.0,1550.0,1660.0,1760.0,1850.0,1920.0,1960.0,2060.0,2110.0,2150.0,2200.0,2240.0,2260.0,2260.0,2250.0,2250.0,2240.0,2240.0,2230.0,2220.0,2210.0,2200.0,2190.0,2180.0,2180.0,2180.0,2180.0,2180.0,2180.0,2170.0,2170.0,2170.0,2170.0,2170.0,2170.0,2160.0,2160.0,2150.0,2150.0,2140.0,2140.0,2130.0,2130.0,2120.0,2120.0,2110.0,2110.0,2100.0,2100.0,2090.0,2090.0,2080.0,2080.0,2070.0,2070.0,2060.0,2050.0,2050.0,2040.0,2030.0,2030.0,2020.0,2010.0,2010.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0,2000.0};
// double[] T = {2.95E+02, 2.95E+02, 2.95E+02, 2.95E+02, 6.12E+02, 9.28E+02, 1.24E+03, 1.56E+03, 1.88E+03, 2.19E+03, 2.19E+03, 2.19E+03};
// Pressure is assumed to have units in atm
// double[] Pressure = {0.03947692};
double[] Pressure = {1};
// Read in the chem.inp file
try {
FileReader fr_thermodat = new FileReader(args[0]);
BufferedReader br_thermodat = new BufferedReader(fr_thermodat);
String line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Continue reading in the file until "THERMO" is read in
boolean foundThermo = false;
while (!foundThermo) {
line = ChemParser.readMeaningfulLine(br_thermodat, true);
if (line.startsWith("THERMO")) {
foundThermo = true;
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line contains the global Tmin, Tmax, Tmid
line = ChemParser.readMeaningfulLine(br_thermodat, true); // This line should have thermo (or comments)
}
}
int counter = 0;
// Read in all information
while (line != null && !line.equals("END")) {
if (!line.startsWith("!")) {
// Thermo data for each species stored in 4 consecutive lines
String speciesName = line.substring(0,16);
StringTokenizer st_chemkinname = new StringTokenizer(speciesName);
names[counter] = st_chemkinname.nextToken().trim();
// String lowTstring = line.substring(46,56);
// double lowT = Double.parseDouble(lowTstring.trim());
// String highTstring = line.substring(56,66);
// double highT = Double.parseDouble(highTstring.trim());
// String midTstring = line.substring(66,74);
// double midT = Double.parseDouble(midTstring.trim());
// Read in the coefficients
for (int numLines=0; numLines<2; ++numLines) {
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<5; ++numcoeffs) {
coeffs[counter][5*numLines+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, false);
for (int numcoeffs=0; numcoeffs<4; ++numcoeffs) {
coeffs[counter][10+numcoeffs] = Double.parseDouble(line.substring(15*numcoeffs,15*(numcoeffs+1)).trim());
}
++counter;
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
// line should be END; next line should be REACTIONS
line = ChemParser.readMeaningfulLine(br_thermodat, true);
// Determine what units Ea is in
StringTokenizer st = new StringTokenizer(line);
double R = 1.987;
while (st.hasMoreTokens()) {
String nextToken = st.nextToken().toLowerCase();
if (nextToken.equals("kcal/mol")) R = 1.987e-3;
else if (nextToken.equals("kj/mol")) R = 8.314e-3;
else if (nextToken.equals("j/mol")) R = 8.314;
}
// next line should have kinetic info
line = ChemParser.readMeaningfulLine(br_thermodat, true);
while (line != null && !line.equals("END")) {
boolean reversible = true;
if (!line.startsWith("!")&& !line.toLowerCase().contains("low") && !line.toLowerCase().contains("troe") && !line.toLowerCase().contains("dup") && !line.toLowerCase().contains("plog") && !line.contains("CHEB")) {
String rxnString = "";
String fullRxnString = line;
int[] reactsIndex = new int[3];
int[] prodsIndex = new int[3];
String shortRxnString = "";
double A = 0.0;
double n = 0.0;
double E = 0.0;
double[] logk = new double[T.length];
boolean chebyshevRate = false;
boolean rmgRate = false;
boolean plogRate = false;
// Find all Chebyshev rate coefficients
if (line.contains("1.0E0 0.0 0.0") || line.contains("1.000e+00 0.00 0.00")) {
st = new StringTokenizer(line);
rxnString = st.nextToken();
shortRxnString = rxnString;
String[] reactsANDprods = rxnString.split("=");
if (shortRxnString.contains("(+m)")) {
chebyshevRate = true;
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
numR = determineNumberOfSpecies(reactsANDprods[0].substring(0,reactsANDprods[0].length()-4));
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
numP = determineNumberOfSpecies(reactsANDprods[1].substring(0,reactsANDprods[1].length()-4));
line = ChemParser.readUncommentLine(br_thermodat); // TCHEB & PCHEB info
while (line.startsWith("!")) {
line = ChemParser.readUncommentLine(br_thermodat);
}
StringTokenizer st_cheb = new StringTokenizer(line,"/");
String currentToken = st_cheb.nextToken(); // TCHEB
StringTokenizer st_values = new StringTokenizer(st_cheb.nextToken());
double Tmin = Double.parseDouble(st_values.nextToken());
double Tmax = Double.parseDouble(st_values.nextToken());
double[] Ttilda = computeTtilda(T,Tmin,Tmax);
currentToken = st_cheb.nextToken(); // PCHEB
st_values = new StringTokenizer(st_cheb.nextToken());
double Pmin = Double.parseDouble(st_values.nextToken());
double Pmax = Double.parseDouble(st_values.nextToken());
double[] Ptilda = computePtilda(Pressure,Pmin,Pmax);
line = ChemParser.readUncommentLine(br_thermodat); // # of basis set info
st_cheb = new StringTokenizer(line,"/");
currentToken = st_cheb.nextToken();
st_values = new StringTokenizer(st_cheb.nextToken());
int nT = Integer.parseInt(st_values.nextToken());
int nP = Integer.parseInt(st_values.nextToken());
// Extract the coefficients
double[] coeffs = new double[nT*nP];
int coeffCounter = 0;
while (coeffCounter < nT*nP) {
line = ChemParser.readUncommentLine(br_thermodat);
String[] splitSlashes = line.split("/");
StringTokenizer st_coeffs = new StringTokenizer(splitSlashes[1]);
while (st_coeffs.hasMoreTokens()) {
coeffs[coeffCounter] = Double.parseDouble(st_coeffs.nextToken().trim());
++coeffCounter;
}
}
double[][] phiT = computephi(Ttilda,nT);
double[][] phiP = computephi(Ptilda,nP);
// Compute k(T,P)
for (int k=0; k<T.length; k++) {
for (int i=0; i<nT; i++) {
for (int j=0; j<nP; j++) {
logk[k] += coeffs[i*nP+j] * phiT[i][k] * phiP[j][0];
}
}
}
String output = "";
for (int k=0; k<T.length; k++) {
output += logk[k] + "\t";
}
// System.out.println(output + rxnString);
for (int k=0; k<T.length; k++) {
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
} else {
plogRate = true; // Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
line = ChemParser.readUncommentLine(br_thermodat); // Begin reading PLOG line
while (line != null && line.startsWith("PLOG")) {
StringTokenizer st_plog = new StringTokenizer(line,"/");
String temporaryString = st_plog.nextToken();
StringTokenizer st_plog_info = new StringTokenizer(st_plog.nextToken());
String plog_pressure = st_plog_info.nextToken();
double plog_A = Double.parseDouble(st_plog_info.nextToken());
double plog_n = Double.parseDouble(st_plog_info.nextToken());
double plog_E = Double.parseDouble(st_plog_info.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(plog_A * Math.pow(T[k],plog_n) * Math.exp(-plog_E/R/T[k]));//***note: PLOG uses the same units for Ea and A as Arrhenius expressions; see https://github.com/GreenGroup/RMG-Java/commit/2947e7b8d5b1e3e19543f2489990fa42e43ecad2#commitcomment-844009
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], (fullRxnString+"\t"+plog_pressure));
}
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,(fullRxnString+"\t"+plog_pressure),(shortRxnString+"\t"+plog_pressure));
line = ChemParser.readUncommentLine(br_thermodat);
}
}
}
else if (line.contains("(+m)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+m\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("(+M)")) {
shortRxnString = line;
String[] sepStrings = line.split("\\(\\+M\\)");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+m")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+m");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(sepStrings[1].substring(1,sepStrings[1].length()));
}
else if (line.contains("+M=")) {
shortRxnString = line;
String[] sepStrings = line.split("\\+M\\=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(sepStrings[0]);
// Determine the products
StringTokenizer removeComments = new StringTokenizer(sepStrings[1]);
String inputString = removeComments.nextToken();
prodsIndex = determineSpeciesIndex(inputString.substring(0,inputString.length()-2));
}
else if (line.contains("=")) {
rmgRate = true;
shortRxnString = line;
st = new StringTokenizer(line);
shortRxnString = st.nextToken();
if (shortRxnString.contains("=>")) reversible = false;
A = Double.parseDouble(st.nextToken());
n = Double.parseDouble(st.nextToken());
E = Double.parseDouble(st.nextToken());
String output = "";
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
output += logk[k] + "\t";
}
// System.out.println(output + shortRxnString);
for (int k=0; k<T.length; k++) {
logk[k] = Math.log10(A * Math.pow(T[k],n) * Math.exp(-E/R/T[k]));
if (logk[k] > 15)
System.out.format("logkf = %4.2f at T = %4.0fK for %s\n", logk[k], T[k], fullRxnString);
}
String[] reactsANDprods = shortRxnString.split("=");
// Determine the reactants
reactsIndex = determineSpeciesIndex(reactsANDprods[0]);
numR = determineNumberOfSpecies(reactsANDprods[0]);
// Determine the products
prodsIndex = determineSpeciesIndex(reactsANDprods[1]);
numP = determineNumberOfSpecies(reactsANDprods[1]);
}
// Calculate G_RT
if (rmgRate || chebyshevRate) {
calculate_G_RT(T,reactsIndex,prodsIndex,reversible,logk,fullRxnString,shortRxnString);
}
}
line = ChemParser.readMeaningfulLine(br_thermodat, true);
}
} catch (FileNotFoundException e) {
System.err.println("File was not found: " + args[0] + "\n");
}
try {
File reversek = new File("reverseRateCoefficients.txt");
FileWriter fw_rxns = new FileWriter(reversek);
fw_rxns.write(reverseRateCoefficients.toString());
fw_rxns.close();
}
catch (IOException e) {
System.out.println("Could not write reverseRateCoefficients.txt files");
System.exit(0);
}
}
|
diff --git a/src/com/strazzere/dehose/unpacker.java b/src/com/strazzere/dehose/unpacker.java
index 8d0ae2f..d0094ad 100644
--- a/src/com/strazzere/dehose/unpacker.java
+++ b/src/com/strazzere/dehose/unpacker.java
@@ -1,139 +1,139 @@
package com.strazzere.dehose;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Unpacker for the first release of the HoseDex2Jar, which uses the inflated header to hide the original dex file.
*
* The dex file is wrapped in a jar (just zipped) and then encrypted. Instead of caring what the crypto is, let's just
* use the tool this packer is meant to thwart, to make our lives easier. As an included library, I've attached the
* dex2jar translated crypto dex file used by the packer. I quickly looked at the munging it's doing, but there's no
* real reason to care what it does - since we can just use it :)
*
*
* @author Tim Strazzere <diff@lookout.com>
*/
public class unpacker {
/**
* You know, the main stuff, read in the dex file, figure out the packed section, decrypt the buffer and output jar.
*
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
System.out.println("[!] Dehoser - unpacker for HoseDex2Jar packer");
System.out.println("[-] Tim Strazzere, diff@lookout.com");
byte[] file = readFile(args[0]);
System.out.println(" [+] Read [ " + file.length + " ] bytes from [ " + args[0] + " ]");
byte[] packed_section = getPackedSection(file);
- System.out.println(" [+] Packed section appears to have a size of [ " + file.length + " ] bytes");
+ System.out.println(" [+] Packed section appears to have a size of [ " + packed_section.length + " ] bytes");
byte[] buff = decryptSection(packed_section);
System.out.println(" [+] Decrypted [ " + buff.length + " ] bytes");
writeFile(args[0] + ".decrypted", buff);
System.out.println(" [+] Output decrypted content!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Figure out the size of the packed/encrypted jar and extract it.
*
* @param buffer
* @return the byte[] of interest
* @throws Exception
*/
private static byte[] getPackedSection(byte[] buffer) throws Exception {
int section_size = getPackedSectionLength(buffer);
if (section_size == -1) {
throw new Exception("File does not appear to be packed!");
}
byte[] packed_section = new byte[section_size];
// Copy out the encrypted/packed section
System.arraycopy(buffer, 0x70, packed_section, 0, section_size);
return packed_section;
}
/**
* Read the header section, and figure out the packed length
*
* @return Length of the packed header section or -1 if no packed section
*/
private static int getPackedSectionLength(byte[] buffer) {
// Read the header size
int header_size = 0;
for (int i = 0; i < 4; i++) {
header_size += (buffer[0x24 + i] & 0xFF) << (i * 8);
}
if (header_size != 112) {
int end_byte = buffer[header_size - 1] & 0xFF;
// The packed section is the size of the header,
// minus the size of the default header (112, 0x70),
// minus the padding at the end (represented by the value
// of the last byte of the header)
return header_size - 112 - end_byte;
}
// The header appeared normal, not packed
return -1;
}
/**
* The deobfuscator actually reversed to our own code
*
* @param buffer
* byte[] to decrypt
* @return decrypted byte[]
*/
private static byte[] decryptSection(byte[] buffer) {
return deobfuscator.syrup(buffer);
}
/**
* Leverage the crypto functions against itself ^_^
*
* @param buffer
* byte[] to decrypt
* @return decrypted byte[]
*/
private static byte[] decryptSectionViaExternal(byte[] buffer) {
return com.code.code.df.DF.syrup(buffer);
}
/**
* Read the file
*
* @param path
* @return
* @throws IOException
*/
private static byte[] readFile(String path) throws IOException {
RandomAccessFile f = new RandomAccessFile(path, "r");
byte[] b = new byte[(int) f.length()];
f.read(b);
f.close();
return b;
}
/**
* Write the file
*
* @param path
* @param buffer
* @throws IOException
*/
private static void writeFile(String path, byte[] buffer) throws IOException {
RandomAccessFile f = new RandomAccessFile(path, "rw");
f.write(buffer);
f.close();
}
}
| true | true | public static void main(String[] args) throws Exception {
try {
System.out.println("[!] Dehoser - unpacker for HoseDex2Jar packer");
System.out.println("[-] Tim Strazzere, diff@lookout.com");
byte[] file = readFile(args[0]);
System.out.println(" [+] Read [ " + file.length + " ] bytes from [ " + args[0] + " ]");
byte[] packed_section = getPackedSection(file);
System.out.println(" [+] Packed section appears to have a size of [ " + file.length + " ] bytes");
byte[] buff = decryptSection(packed_section);
System.out.println(" [+] Decrypted [ " + buff.length + " ] bytes");
writeFile(args[0] + ".decrypted", buff);
System.out.println(" [+] Output decrypted content!");
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void main(String[] args) throws Exception {
try {
System.out.println("[!] Dehoser - unpacker for HoseDex2Jar packer");
System.out.println("[-] Tim Strazzere, diff@lookout.com");
byte[] file = readFile(args[0]);
System.out.println(" [+] Read [ " + file.length + " ] bytes from [ " + args[0] + " ]");
byte[] packed_section = getPackedSection(file);
System.out.println(" [+] Packed section appears to have a size of [ " + packed_section.length + " ] bytes");
byte[] buff = decryptSection(packed_section);
System.out.println(" [+] Decrypted [ " + buff.length + " ] bytes");
writeFile(args[0] + ".decrypted", buff);
System.out.println(" [+] Output decrypted content!");
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/vcap-client/src/main/java/cf/client/model/ApplicationInstance.java b/vcap-client/src/main/java/cf/client/model/ApplicationInstance.java
index 8e868d9..32cb882 100644
--- a/vcap-client/src/main/java/cf/client/model/ApplicationInstance.java
+++ b/vcap-client/src/main/java/cf/client/model/ApplicationInstance.java
@@ -1,113 +1,115 @@
/*
* Copyright (c) 2013 Intellectual Reserve, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package cf.client.model;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonProperty;
import java.net.InetSocketAddress;
import java.util.Date;
/**
* @author Mike Heath <elcapo@gmail.com>
*/
public class ApplicationInstance {
public enum State {
RUNNING,
STARTING,
STOPPED,
FLAPPING,
UNKNOWN
}
private final State state;
private final Date since;
private InetSocketAddress debugAddress;
private InetSocketAddress consoleAddress;
public ApplicationInstance(State state, Date since, InetSocketAddress debugAddress, InetSocketAddress consoleAddress) {
this.state = state;
this.since = since;
this.debugAddress = debugAddress;
this.consoleAddress = consoleAddress;
}
@JsonCreator
public ApplicationInstance(
@JsonProperty("state") String state,
@JsonProperty("since") double since,
@JsonProperty("debug_ip") String debugIp,
@JsonProperty("debug_port") Integer debugPort,
@JsonProperty("console_ip") String consoleIp,
@JsonProperty("console_port") Integer consolePort
) {
- State stateValue = State.valueOf(state.toUpperCase());
- if (stateValue == null) {
+ State stateValue = null;
+ try {
+ stateValue = State.valueOf(state.toUpperCase());
+ } catch (IllegalArgumentException e) {
stateValue = State.UNKNOWN;
}
this.state = stateValue;
this.since = new Date((long)Math.floor(since * 1000));
this.debugAddress = (debugIp == null || debugPort == null) ? null : new InetSocketAddress(debugIp, debugPort);
this.consoleAddress = (consoleIp == null || consolePort == null) ? null : new InetSocketAddress(consoleIp, consolePort);
}
public State getState() {
return state;
}
@JsonIgnore
public Date getSince() {
return since;
}
@JsonIgnore
public InetSocketAddress getDebugAddress() {
return debugAddress;
}
@JsonIgnore
public InetSocketAddress getConsoleAddress() {
return consoleAddress;
}
@JsonProperty("since")
public double getSinceDouble() {
return ((double)since.getTime()) / 1000;
}
@JsonProperty("debug_ip")
public String getDebugIp() {
return debugAddress == null ? null : debugAddress.getHostString();
}
@JsonProperty("debug_port")
public Integer getDebugPort() {
return debugAddress == null ? null : debugAddress.getPort();
}
@JsonProperty("console_ip")
public String getConsoleIp() {
return consoleAddress == null ? null : consoleAddress.getHostString();
}
@JsonProperty("console_port")
public Integer getConsolePort() {
return consoleAddress == null ? null : consoleAddress.getPort();
}
}
| true | true | public ApplicationInstance(
@JsonProperty("state") String state,
@JsonProperty("since") double since,
@JsonProperty("debug_ip") String debugIp,
@JsonProperty("debug_port") Integer debugPort,
@JsonProperty("console_ip") String consoleIp,
@JsonProperty("console_port") Integer consolePort
) {
State stateValue = State.valueOf(state.toUpperCase());
if (stateValue == null) {
stateValue = State.UNKNOWN;
}
this.state = stateValue;
this.since = new Date((long)Math.floor(since * 1000));
this.debugAddress = (debugIp == null || debugPort == null) ? null : new InetSocketAddress(debugIp, debugPort);
this.consoleAddress = (consoleIp == null || consolePort == null) ? null : new InetSocketAddress(consoleIp, consolePort);
}
| public ApplicationInstance(
@JsonProperty("state") String state,
@JsonProperty("since") double since,
@JsonProperty("debug_ip") String debugIp,
@JsonProperty("debug_port") Integer debugPort,
@JsonProperty("console_ip") String consoleIp,
@JsonProperty("console_port") Integer consolePort
) {
State stateValue = null;
try {
stateValue = State.valueOf(state.toUpperCase());
} catch (IllegalArgumentException e) {
stateValue = State.UNKNOWN;
}
this.state = stateValue;
this.since = new Date((long)Math.floor(since * 1000));
this.debugAddress = (debugIp == null || debugPort == null) ? null : new InetSocketAddress(debugIp, debugPort);
this.consoleAddress = (consoleIp == null || consolePort == null) ? null : new InetSocketAddress(consoleIp, consolePort);
}
|
diff --git a/src/com/rj/processing/mt/MTManager.java b/src/com/rj/processing/mt/MTManager.java
index 35b784f..2f5a59e 100644
--- a/src/com/rj/processing/mt/MTManager.java
+++ b/src/com/rj/processing/mt/MTManager.java
@@ -1,81 +1,81 @@
package com.rj.processing.mt;
import java.util.ArrayList;
import android.view.MotionEvent;
public class MTManager {
public MTCallback callback;
private class Point {
public final float x;
public final float y;
public long time;
public Point(float x, float y) {
this.x = x;
this.y = y;
time = System.currentTimeMillis();
}
}
public ArrayList<Point> points;
public MTManager(MTCallback callback) {
this.callback = callback;
this.points = new ArrayList<Point>(8);
}
public void surfaceTouchEvent(MotionEvent me) {
int numPointers = me.getPointerCount();
for (int i = 0; i < numPointers; i++) {
touchEvent(me, i);
}
}
public void touchEvent(MotionEvent me, int i) {
int pointerId = me.getPointerId(i);
float x = me.getX(i);
float y = me.getY(i);
float vx = 0;
float vy = 0;
int index = me.findPointerIndex(pointerId);
if (points.size() < index+1) {
//points.ensureCapacity(index+4);
points.add(null);
points.add(null);
points.add(null);
points.add(null);
}
Point prevPoint = points.get(index);
long curt = System.currentTimeMillis();
if (prevPoint != null && curt-prevPoint.time < 100) {
long t = curt-prevPoint.time;
float dt = (float)t/1000f;
// Log.d("asdf","Old point: "+prevPoint.x+" , "+prevPoint.y+" : "+prevPoint.time);
// Log.d("asdf","Cur point: "+x+" , "+y+" : "+curt);
vx = (x-prevPoint.x)*dt;
vy = (y-prevPoint.y)*dt;
}
- points.add(index, new Point(x,y));
+ points.set(index, new Point(x,y));
float size = me.getSize(i);
callback.touchEvent(me, i, x, y, vx, vy, size);
}
}
| true | true | public void touchEvent(MotionEvent me, int i) {
int pointerId = me.getPointerId(i);
float x = me.getX(i);
float y = me.getY(i);
float vx = 0;
float vy = 0;
int index = me.findPointerIndex(pointerId);
if (points.size() < index+1) {
//points.ensureCapacity(index+4);
points.add(null);
points.add(null);
points.add(null);
points.add(null);
}
Point prevPoint = points.get(index);
long curt = System.currentTimeMillis();
if (prevPoint != null && curt-prevPoint.time < 100) {
long t = curt-prevPoint.time;
float dt = (float)t/1000f;
// Log.d("asdf","Old point: "+prevPoint.x+" , "+prevPoint.y+" : "+prevPoint.time);
// Log.d("asdf","Cur point: "+x+" , "+y+" : "+curt);
vx = (x-prevPoint.x)*dt;
vy = (y-prevPoint.y)*dt;
}
points.add(index, new Point(x,y));
float size = me.getSize(i);
callback.touchEvent(me, i, x, y, vx, vy, size);
}
| public void touchEvent(MotionEvent me, int i) {
int pointerId = me.getPointerId(i);
float x = me.getX(i);
float y = me.getY(i);
float vx = 0;
float vy = 0;
int index = me.findPointerIndex(pointerId);
if (points.size() < index+1) {
//points.ensureCapacity(index+4);
points.add(null);
points.add(null);
points.add(null);
points.add(null);
}
Point prevPoint = points.get(index);
long curt = System.currentTimeMillis();
if (prevPoint != null && curt-prevPoint.time < 100) {
long t = curt-prevPoint.time;
float dt = (float)t/1000f;
// Log.d("asdf","Old point: "+prevPoint.x+" , "+prevPoint.y+" : "+prevPoint.time);
// Log.d("asdf","Cur point: "+x+" , "+y+" : "+curt);
vx = (x-prevPoint.x)*dt;
vy = (y-prevPoint.y)*dt;
}
points.set(index, new Point(x,y));
float size = me.getSize(i);
callback.touchEvent(me, i, x, y, vx, vy, size);
}
|
diff --git a/extensions/gdx-audio/src/com/badlogic/gdx/audio/AudioBuild.java b/extensions/gdx-audio/src/com/badlogic/gdx/audio/AudioBuild.java
index bc75a2606..596ac4826 100644
--- a/extensions/gdx-audio/src/com/badlogic/gdx/audio/AudioBuild.java
+++ b/extensions/gdx-audio/src/com/badlogic/gdx/audio/AudioBuild.java
@@ -1,129 +1,129 @@
package com.badlogic.gdx.audio;
import com.badlogic.gdx.jnigen.AntScriptGenerator;
import com.badlogic.gdx.jnigen.BuildConfig;
import com.badlogic.gdx.jnigen.BuildExecutor;
import com.badlogic.gdx.jnigen.BuildTarget;
import com.badlogic.gdx.jnigen.BuildTarget.TargetOs;
import com.badlogic.gdx.jnigen.NativeCodeGenerator;
public class AudioBuild {
public static void main(String[] args) throws Exception {
new NativeCodeGenerator().generate("src", "bin", "jni",
new String[] { "**/AudioTools.java", "**/KissFFT.java", "**/VorbisDecoder.java", "**/Mpg123Decoder.java", "**/SoundTouch.java" },
null);
String[] headerDirs = new String[] { "kissfft", "vorbis", "soundtouch/include", "soundtouch/source/SoundTouch/" };
String[] cIncludes = new String[] {
"kissfft/*.c",
"vorbis/*.c",
"libmpg123/equalizer.c",
"libmpg123/index.c",
"libmpg123/layer2.c",
"libmpg123/synth.c",
"libmpg123/dct64.c",
"libmpg123/format.c",
"libmpg123/layer3.c",
"libmpg123/ntom.c",
"libmpg123/parse.c",
"libmpg123/readers.c",
"libmpg123/frame.c",
"libmpg123/layer1.c",
"libmpg123/libmpg123.c",
"libmpg123/optimize.c",
"libmpg123/synth_arm.S",
"libmpg123/tabinit.c",
"libmpg123/id3.c",
"libmpg123/stringbuf.c",
"libmpg123/icy.c",
"libmpg123/icy2utf8.c",
"libmpg123/compat.c",
"libmpg123/synth_8bit.c",
"libmpg123/synth_real.c",
"libmpg123/synth_s32.c",
};
String[] cppIncludes = new String[] {
"**/*AudioTools.cpp",
"**/*KissFFT.cpp",
"**/*VorbisDecoder.cpp",
"**/*SoundTouch.cpp",
"**/*Mpg123Decoder.cpp",
"soundtouch/source/SoundTouch/*.cpp"
};
String[] cppExcludes = new String[] { "**/cpu_detect_x86_win.cpp" };
String precompileTask = "<copy failonerror=\"true\" tofile=\"soundtouch/include/STTypes.h\" verbose=\"true\" overwrite=\"true\" file=\"STTypes.h.patched\"/>";
String cFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
String cppFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
BuildConfig buildConfig = new BuildConfig("gdx-audio");
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.cFlags += cFlags;
win32home.cppFlags += cppFlags;
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.headerDirs = headerDirs;
win32home.cIncludes = cIncludes;
win32home.cppIncludes = cppIncludes;
win32home.cppExcludes = cppExcludes;
win32home.excludeFromMasterBuildFile = true;
win32home.preCompileTask = precompileTask;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cFlags += cFlags;
win32.cppFlags += cppFlags;
win32.headerDirs = headerDirs;
win32.cIncludes = cIncludes;
win32.cppIncludes = cppIncludes;
win32.cppExcludes = cppExcludes;
win32.preCompileTask = precompileTask;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cFlags += cFlags;
win64.cppFlags += cppFlags;
win64.headerDirs = headerDirs;
win64.cIncludes = cIncludes;
win64.cppIncludes = cppIncludes;
win64.cppExcludes = cppExcludes;
win64.preCompileTask = precompileTask;
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cFlags += cFlags;
lin32.cppFlags += cppFlags;
lin32.headerDirs = headerDirs;
lin32.cIncludes = cIncludes;
lin32.cppIncludes = cppIncludes;
lin32.cppExcludes = cppExcludes;
lin32.preCompileTask = precompileTask;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cFlags += cFlags;
lin64.cppFlags += cppFlags;
lin64.headerDirs = headerDirs;
lin64.cIncludes = cIncludes;
lin64.cppIncludes = cppIncludes;
lin64.cppExcludes = cppExcludes;
lin64.preCompileTask = precompileTask;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cFlags += cFlags;
mac.cppFlags += cppFlags;
mac.headerDirs = headerDirs;
mac.cIncludes = cIncludes;
mac.cppIncludes = cppIncludes;
mac.cppExcludes = cppExcludes;
mac.preCompileTask = precompileTask;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
- android.cFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__";
- android.cppFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__";
+ android.cFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__ -DMPG123_NO_CONFIGURE -DOPT_ARM -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
+ android.cppFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__ -DMPG123_NO_CONFIGURE -DOPT_ARM -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
android.headerDirs = headerDirs;
android.cIncludes = cIncludes;
android.cppIncludes = cppIncludes;
android.cppExcludes = cppExcludes;
android.preCompileTask = precompileTask;
new AntScriptGenerator().generate(buildConfig, win32home, win32, win64, lin32, lin64, mac, android);
- BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v");
+ BuildExecutor.executeAnt("jni/build-linux64.xml", "clean postcompile -v");
BuildExecutor.executeAnt("jni/build.xml", "pack-natives -v");
}
}
| false | true | public static void main(String[] args) throws Exception {
new NativeCodeGenerator().generate("src", "bin", "jni",
new String[] { "**/AudioTools.java", "**/KissFFT.java", "**/VorbisDecoder.java", "**/Mpg123Decoder.java", "**/SoundTouch.java" },
null);
String[] headerDirs = new String[] { "kissfft", "vorbis", "soundtouch/include", "soundtouch/source/SoundTouch/" };
String[] cIncludes = new String[] {
"kissfft/*.c",
"vorbis/*.c",
"libmpg123/equalizer.c",
"libmpg123/index.c",
"libmpg123/layer2.c",
"libmpg123/synth.c",
"libmpg123/dct64.c",
"libmpg123/format.c",
"libmpg123/layer3.c",
"libmpg123/ntom.c",
"libmpg123/parse.c",
"libmpg123/readers.c",
"libmpg123/frame.c",
"libmpg123/layer1.c",
"libmpg123/libmpg123.c",
"libmpg123/optimize.c",
"libmpg123/synth_arm.S",
"libmpg123/tabinit.c",
"libmpg123/id3.c",
"libmpg123/stringbuf.c",
"libmpg123/icy.c",
"libmpg123/icy2utf8.c",
"libmpg123/compat.c",
"libmpg123/synth_8bit.c",
"libmpg123/synth_real.c",
"libmpg123/synth_s32.c",
};
String[] cppIncludes = new String[] {
"**/*AudioTools.cpp",
"**/*KissFFT.cpp",
"**/*VorbisDecoder.cpp",
"**/*SoundTouch.cpp",
"**/*Mpg123Decoder.cpp",
"soundtouch/source/SoundTouch/*.cpp"
};
String[] cppExcludes = new String[] { "**/cpu_detect_x86_win.cpp" };
String precompileTask = "<copy failonerror=\"true\" tofile=\"soundtouch/include/STTypes.h\" verbose=\"true\" overwrite=\"true\" file=\"STTypes.h.patched\"/>";
String cFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
String cppFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
BuildConfig buildConfig = new BuildConfig("gdx-audio");
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.cFlags += cFlags;
win32home.cppFlags += cppFlags;
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.headerDirs = headerDirs;
win32home.cIncludes = cIncludes;
win32home.cppIncludes = cppIncludes;
win32home.cppExcludes = cppExcludes;
win32home.excludeFromMasterBuildFile = true;
win32home.preCompileTask = precompileTask;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cFlags += cFlags;
win32.cppFlags += cppFlags;
win32.headerDirs = headerDirs;
win32.cIncludes = cIncludes;
win32.cppIncludes = cppIncludes;
win32.cppExcludes = cppExcludes;
win32.preCompileTask = precompileTask;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cFlags += cFlags;
win64.cppFlags += cppFlags;
win64.headerDirs = headerDirs;
win64.cIncludes = cIncludes;
win64.cppIncludes = cppIncludes;
win64.cppExcludes = cppExcludes;
win64.preCompileTask = precompileTask;
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cFlags += cFlags;
lin32.cppFlags += cppFlags;
lin32.headerDirs = headerDirs;
lin32.cIncludes = cIncludes;
lin32.cppIncludes = cppIncludes;
lin32.cppExcludes = cppExcludes;
lin32.preCompileTask = precompileTask;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cFlags += cFlags;
lin64.cppFlags += cppFlags;
lin64.headerDirs = headerDirs;
lin64.cIncludes = cIncludes;
lin64.cppIncludes = cppIncludes;
lin64.cppExcludes = cppExcludes;
lin64.preCompileTask = precompileTask;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cFlags += cFlags;
mac.cppFlags += cppFlags;
mac.headerDirs = headerDirs;
mac.cIncludes = cIncludes;
mac.cppIncludes = cppIncludes;
mac.cppExcludes = cppExcludes;
mac.preCompileTask = precompileTask;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
android.cFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__";
android.cppFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__";
android.headerDirs = headerDirs;
android.cIncludes = cIncludes;
android.cppIncludes = cppIncludes;
android.cppExcludes = cppExcludes;
android.preCompileTask = precompileTask;
new AntScriptGenerator().generate(buildConfig, win32home, win32, win64, lin32, lin64, mac, android);
BuildExecutor.executeAnt("jni/build-windows32home.xml", "-v");
BuildExecutor.executeAnt("jni/build.xml", "pack-natives -v");
}
| public static void main(String[] args) throws Exception {
new NativeCodeGenerator().generate("src", "bin", "jni",
new String[] { "**/AudioTools.java", "**/KissFFT.java", "**/VorbisDecoder.java", "**/Mpg123Decoder.java", "**/SoundTouch.java" },
null);
String[] headerDirs = new String[] { "kissfft", "vorbis", "soundtouch/include", "soundtouch/source/SoundTouch/" };
String[] cIncludes = new String[] {
"kissfft/*.c",
"vorbis/*.c",
"libmpg123/equalizer.c",
"libmpg123/index.c",
"libmpg123/layer2.c",
"libmpg123/synth.c",
"libmpg123/dct64.c",
"libmpg123/format.c",
"libmpg123/layer3.c",
"libmpg123/ntom.c",
"libmpg123/parse.c",
"libmpg123/readers.c",
"libmpg123/frame.c",
"libmpg123/layer1.c",
"libmpg123/libmpg123.c",
"libmpg123/optimize.c",
"libmpg123/synth_arm.S",
"libmpg123/tabinit.c",
"libmpg123/id3.c",
"libmpg123/stringbuf.c",
"libmpg123/icy.c",
"libmpg123/icy2utf8.c",
"libmpg123/compat.c",
"libmpg123/synth_8bit.c",
"libmpg123/synth_real.c",
"libmpg123/synth_s32.c",
};
String[] cppIncludes = new String[] {
"**/*AudioTools.cpp",
"**/*KissFFT.cpp",
"**/*VorbisDecoder.cpp",
"**/*SoundTouch.cpp",
"**/*Mpg123Decoder.cpp",
"soundtouch/source/SoundTouch/*.cpp"
};
String[] cppExcludes = new String[] { "**/cpu_detect_x86_win.cpp" };
String precompileTask = "<copy failonerror=\"true\" tofile=\"soundtouch/include/STTypes.h\" verbose=\"true\" overwrite=\"true\" file=\"STTypes.h.patched\"/>";
String cFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
String cppFlags = " -DFIXED_POINT -DMPG123_NO_CONFIGURE -DOPT_GENERIC -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
BuildConfig buildConfig = new BuildConfig("gdx-audio");
BuildTarget win32home = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32home.cFlags += cFlags;
win32home.cppFlags += cppFlags;
win32home.compilerPrefix = "";
win32home.buildFileName = "build-windows32home.xml";
win32home.headerDirs = headerDirs;
win32home.cIncludes = cIncludes;
win32home.cppIncludes = cppIncludes;
win32home.cppExcludes = cppExcludes;
win32home.excludeFromMasterBuildFile = true;
win32home.preCompileTask = precompileTask;
BuildTarget win32 = BuildTarget.newDefaultTarget(TargetOs.Windows, false);
win32.cFlags += cFlags;
win32.cppFlags += cppFlags;
win32.headerDirs = headerDirs;
win32.cIncludes = cIncludes;
win32.cppIncludes = cppIncludes;
win32.cppExcludes = cppExcludes;
win32.preCompileTask = precompileTask;
BuildTarget win64 = BuildTarget.newDefaultTarget(TargetOs.Windows, true);
win64.cFlags += cFlags;
win64.cppFlags += cppFlags;
win64.headerDirs = headerDirs;
win64.cIncludes = cIncludes;
win64.cppIncludes = cppIncludes;
win64.cppExcludes = cppExcludes;
win64.preCompileTask = precompileTask;
BuildTarget lin32 = BuildTarget.newDefaultTarget(TargetOs.Linux, false);
lin32.cFlags += cFlags;
lin32.cppFlags += cppFlags;
lin32.headerDirs = headerDirs;
lin32.cIncludes = cIncludes;
lin32.cppIncludes = cppIncludes;
lin32.cppExcludes = cppExcludes;
lin32.preCompileTask = precompileTask;
BuildTarget lin64 = BuildTarget.newDefaultTarget(TargetOs.Linux, true);
lin64.cFlags += cFlags;
lin64.cppFlags += cppFlags;
lin64.headerDirs = headerDirs;
lin64.cIncludes = cIncludes;
lin64.cppIncludes = cppIncludes;
lin64.cppExcludes = cppExcludes;
lin64.preCompileTask = precompileTask;
BuildTarget mac = BuildTarget.newDefaultTarget(TargetOs.MacOsX, false);
mac.cFlags += cFlags;
mac.cppFlags += cppFlags;
mac.headerDirs = headerDirs;
mac.cIncludes = cIncludes;
mac.cppIncludes = cppIncludes;
mac.cppExcludes = cppExcludes;
mac.preCompileTask = precompileTask;
BuildTarget android = BuildTarget.newDefaultTarget(TargetOs.Android, false);
android.cFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__ -DMPG123_NO_CONFIGURE -DOPT_ARM -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
android.cppFlags += " -DFIXED_POINT -D_ARM_ASSEM_ -D__ANDROID__ -DMPG123_NO_CONFIGURE -DOPT_ARM -DHAVE_STRERROR -DMPG123_NO_LARGENAME";
android.headerDirs = headerDirs;
android.cIncludes = cIncludes;
android.cppIncludes = cppIncludes;
android.cppExcludes = cppExcludes;
android.preCompileTask = precompileTask;
new AntScriptGenerator().generate(buildConfig, win32home, win32, win64, lin32, lin64, mac, android);
BuildExecutor.executeAnt("jni/build-linux64.xml", "clean postcompile -v");
BuildExecutor.executeAnt("jni/build.xml", "pack-natives -v");
}
|
diff --git a/src/main/java/com/pearson/ed/lplc/ws/MarshallingLicensePoolEndpoint.java b/src/main/java/com/pearson/ed/lplc/ws/MarshallingLicensePoolEndpoint.java
index ed8674e..2c4ccd4 100644
--- a/src/main/java/com/pearson/ed/lplc/ws/MarshallingLicensePoolEndpoint.java
+++ b/src/main/java/com/pearson/ed/lplc/ws/MarshallingLicensePoolEndpoint.java
@@ -1,269 +1,269 @@
package com.pearson.ed.lplc.ws;
import java.util.List;
import org.apache.log4j.Logger;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import com.pearson.ed.lplc.common.LPLCConstants;
import com.pearson.ed.lplc.exception.ComponentCardinalityException;
import com.pearson.ed.lplc.exception.ComponentValidationException;
import com.pearson.ed.lplc.exception.LPLCBaseException;
import com.pearson.ed.lplc.exception.LicensePoolException;
import com.pearson.ed.lplc.exception.LicensePoolExceptionFactory;
import com.pearson.ed.lplc.services.api.LicensePoolServiceEndPoint;
import com.pearson.ed.lplc.services.converter.api.LicensePoolConverter;
import com.pearson.ed.lplc.warning.LicensePoolWarningFactory;
import com.pearson.ed.lplc.ws.schema.CreateLicensePool;
import com.pearson.ed.lplc.ws.schema.CreateLicensePoolRequest;
import com.pearson.ed.lplc.ws.schema.CreateLicensePoolResponse;
import com.pearson.ed.lplc.ws.schema.GetLicensePoolByOrganizationIdRequest;
import com.pearson.ed.lplc.ws.schema.LicensepoolsByOrganizationId;
import com.pearson.ed.lplc.ws.schema.ServiceResponseType;
import com.pearson.ed.lplc.ws.schema.StatusCodeType;
import com.pearson.ed.lplc.ws.schema.UpdateLicensePool;
import com.pearson.ed.lplc.ws.schema.UpdateLicensePoolRequest;
import com.pearson.ed.lplc.ws.schema.UpdateLicensePoolResponse;
/**
* A LicensePool Life Cycle endpoint that processes marshaled messages.
*
* @author Dipali Trivedi
*/
@Endpoint
public class MarshallingLicensePoolEndpoint implements
LicensePoolWebServiceConstants {
private static final Logger logger = Logger
.getLogger(MarshallingLicensePoolEndpoint.class);
/**
* LicensePool Life Cycle service
*/
private LicensePoolServiceEndPoint licensePoolServiceEndPoint;
private LicensePoolExceptionFactory exceptionFactory;
private LicensePoolWarningFactory warningFactory;
private LicensePoolConverter licensePoolConverter;
/**
* @return the licensepoolServiceEndPoint
*/
public LicensePoolServiceEndPoint getLicensePoolServiceEndPoint() {
return licensePoolServiceEndPoint;
}
/**
* @param licensePoolServiceEndPoint
* the licensePoolServiceEndPoint to set
*/
public void setLicensePoolServiceEndPoint(
LicensePoolServiceEndPoint licensePoolServiceEndPoint) {
this.licensePoolServiceEndPoint = licensePoolServiceEndPoint;
}
/**
* @param licensepoolServiceEndPoint
* the licensepoolServiceEndPoint to set
*/
public void setLicensepoolServiceEndPoint(
LicensePoolServiceEndPoint licensePoolServiceEndPoint) {
this.licensePoolServiceEndPoint = licensePoolServiceEndPoint;
}
/**
* @return the exceptionFactory
*/
public LicensePoolExceptionFactory getExceptionFactory() {
return exceptionFactory;
}
/**
* @param exceptionFactory
* the exceptionFactory to set
*/
public void setExceptionFactory(LicensePoolExceptionFactory exceptionFactory) {
this.exceptionFactory = exceptionFactory;
}
/**
* @return the warningFactory
*/
public LicensePoolWarningFactory getWarningFactory() {
return warningFactory;
}
/**
* @param warningFactory
* the warningFactory to set
*/
public void setWarningFactory(LicensePoolWarningFactory warningFactory) {
this.warningFactory = warningFactory;
}
/**
* @return the licensePoolConverter
*/
public LicensePoolConverter getLicensePoolConverter() {
return licensePoolConverter;
}
/**
* @param licensePoolConverter
* the licensePoolConverter to set
*/
public void setLicensePoolConverter(
LicensePoolConverter licensePoolConverter) {
this.licensePoolConverter = licensePoolConverter;
}
/**
* This endpoint method uses marshalling to handle message with a
* <code><CreatelicensepoolRequestElement></code> payload.
*
* @param licensepoolRequest
* the create licensepool request.
*/
@PayloadRoot(localPart = CREATE_LICENSEPOOL_REQUEST_ELEMENT, namespace = LICENSEPOOL_NAMESPACE)
public CreateLicensePoolResponse createLicensePool(
CreateLicensePoolRequest licensepoolRequest) {
ServiceResponseType serviceResponseType = new ServiceResponseType();
try {
CreateLicensePool createLicensePoolSchemaObj = licensepoolRequest
.getCreateLicensePool();
if (logger.isDebugEnabled()) {
logger.debug("Received " + CREATE_LICENSEPOOL_REQUEST_ELEMENT
+ ":" + createLicensePoolSchemaObj.toString());
}
String transactionId = licensePoolServiceEndPoint
.generateTransactionId();
licensePoolServiceEndPoint.setTransactionId(transactionId);
if (createLicensePoolSchemaObj.getProductId().size() > 1)
throw new ComponentCardinalityException(
"More than 1 product association is not supported.");
if (LPLCConstants.LICENSEPOOLTYPE.equalsIgnoreCase(createLicensePoolSchemaObj.getType()))
- throw new ComponentValidationException("More than 1 product association is not supported.");
+ throw new ComponentValidationException("License Type is not Valid.");
logger
.info("Invoking Licensepool Service CreateLicensePool method");
String licensepoolId = licensePoolServiceEndPoint
.createLicensePool(createLicensePoolSchemaObj);
serviceResponseType.setReturnValue(licensepoolId);
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType.setStatusCode(StatusCodeType.SUCCESS);
serviceResponseType.getStatusMessage().add(
"LicensePool created successfully");
} catch (Exception e) {
LicensePoolException licensepoolException = exceptionFactory
.getLicensePoolException(e);
if (e instanceof LPLCBaseException) {
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType
.setReturnValue(LPLCConstants.SERVICE_RESPONSE_RETURN_FAILURE);
serviceResponseType.setStatusCode(StatusCodeType.FAILURE);
serviceResponseType.getStatusMessage().add(
licensepoolException.getCause().toString());
} else {
throw licensepoolException;
}
}
CreateLicensePoolResponse createResponse = new CreateLicensePoolResponse();
createResponse.setServiceResponseType(serviceResponseType);
return createResponse;
}
/**
* This endpoint method uses marshalling to handle message with a
* <code><CreatelicensepoolRequestElement></code> payload.
*
* @param licensepoolRequest
* the update licensepool request.
*/
@PayloadRoot(localPart = UPDATE_LICENSEPOOL_REQUEST_ELEMENT, namespace = LICENSEPOOL_NAMESPACE)
public UpdateLicensePoolResponse createLicensePool(
UpdateLicensePoolRequest licensepoolRequest) {
ServiceResponseType serviceResponseType = new ServiceResponseType();
try {
UpdateLicensePool updateLicensePoolSchemaObj = licensepoolRequest
.getUpdateLicensePool();
if (logger.isDebugEnabled()) {
logger.debug("Received " + UPDATE_LICENSEPOOL_REQUEST_ELEMENT
+ ":" + updateLicensePoolSchemaObj.toString());
}
String transactionId = licensePoolServiceEndPoint
.generateTransactionId();
licensePoolServiceEndPoint.setTransactionId(transactionId);
logger.info("Invoking Licensepool Service UpdateLicensePool method");
String licensepoolId = licensePoolServiceEndPoint
.updateLicensePool(updateLicensePoolSchemaObj);
serviceResponseType.setReturnValue(licensepoolId);
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType.setStatusCode(StatusCodeType.SUCCESS);
serviceResponseType.getStatusMessage().add(
"LicensePool updated successfully");
} catch (Exception e) {
LicensePoolException licensepoolException = exceptionFactory
.getLicensePoolException(e);
if (e instanceof LPLCBaseException) {
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType
.setReturnValue(LPLCConstants.SERVICE_RESPONSE_RETURN_FAILURE);
serviceResponseType.setStatusCode(StatusCodeType.FAILURE);
serviceResponseType.getStatusMessage().add(
licensepoolException.getCause().toString());
} else {
throw licensepoolException;
}
}
UpdateLicensePoolResponse updateResponse = new UpdateLicensePoolResponse();
updateResponse.setServiceResponseType(serviceResponseType);
return updateResponse;
}
/**
* This endpoint method uses marshalling to handle message with a
* <code><CreatelicensepoolRequestElement></code> payload.
*
* @param licensepoolRequest
* the update licensepool request.
*/
@PayloadRoot(localPart = GET_LICENSEPOOL_REQUEST_ELEMENT, namespace = LICENSEPOOL_NAMESPACE)
public LicensepoolsByOrganizationId getLicensepoolByOrgIdLicensePool(
GetLicensePoolByOrganizationIdRequest licensepoolRequest) {
try {
String organizationId = licensepoolRequest
.getGetLicensePoolByOrganizationIdRequestType().getOrgnizationId();
String qualifyingOrgs = licensepoolRequest.getGetLicensePoolByOrganizationIdRequestType().getQualifyingLicensePool().toString();
if (logger.isDebugEnabled()) {
logger.debug("Received " + GET_LICENSEPOOL_REQUEST_ELEMENT
+ ":" + organizationId+" and "+qualifyingOrgs);
}
String transactionId = licensePoolServiceEndPoint
.generateTransactionId();
licensePoolServiceEndPoint.setTransactionId(transactionId);
logger.info("Invoking Licensepool Service GetLicensePool method");
return licensePoolServiceEndPoint.getLicensePoolByOrganizationId(organizationId, qualifyingOrgs);
} catch (Exception e) {
LicensePoolException licensepoolException = exceptionFactory
.getLicensePoolException(e);
throw licensepoolException;
}
}
}
| true | true | public CreateLicensePoolResponse createLicensePool(
CreateLicensePoolRequest licensepoolRequest) {
ServiceResponseType serviceResponseType = new ServiceResponseType();
try {
CreateLicensePool createLicensePoolSchemaObj = licensepoolRequest
.getCreateLicensePool();
if (logger.isDebugEnabled()) {
logger.debug("Received " + CREATE_LICENSEPOOL_REQUEST_ELEMENT
+ ":" + createLicensePoolSchemaObj.toString());
}
String transactionId = licensePoolServiceEndPoint
.generateTransactionId();
licensePoolServiceEndPoint.setTransactionId(transactionId);
if (createLicensePoolSchemaObj.getProductId().size() > 1)
throw new ComponentCardinalityException(
"More than 1 product association is not supported.");
if (LPLCConstants.LICENSEPOOLTYPE.equalsIgnoreCase(createLicensePoolSchemaObj.getType()))
throw new ComponentValidationException("More than 1 product association is not supported.");
logger
.info("Invoking Licensepool Service CreateLicensePool method");
String licensepoolId = licensePoolServiceEndPoint
.createLicensePool(createLicensePoolSchemaObj);
serviceResponseType.setReturnValue(licensepoolId);
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType.setStatusCode(StatusCodeType.SUCCESS);
serviceResponseType.getStatusMessage().add(
"LicensePool created successfully");
} catch (Exception e) {
LicensePoolException licensepoolException = exceptionFactory
.getLicensePoolException(e);
if (e instanceof LPLCBaseException) {
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType
.setReturnValue(LPLCConstants.SERVICE_RESPONSE_RETURN_FAILURE);
serviceResponseType.setStatusCode(StatusCodeType.FAILURE);
serviceResponseType.getStatusMessage().add(
licensepoolException.getCause().toString());
} else {
throw licensepoolException;
}
}
CreateLicensePoolResponse createResponse = new CreateLicensePoolResponse();
createResponse.setServiceResponseType(serviceResponseType);
return createResponse;
}
| public CreateLicensePoolResponse createLicensePool(
CreateLicensePoolRequest licensepoolRequest) {
ServiceResponseType serviceResponseType = new ServiceResponseType();
try {
CreateLicensePool createLicensePoolSchemaObj = licensepoolRequest
.getCreateLicensePool();
if (logger.isDebugEnabled()) {
logger.debug("Received " + CREATE_LICENSEPOOL_REQUEST_ELEMENT
+ ":" + createLicensePoolSchemaObj.toString());
}
String transactionId = licensePoolServiceEndPoint
.generateTransactionId();
licensePoolServiceEndPoint.setTransactionId(transactionId);
if (createLicensePoolSchemaObj.getProductId().size() > 1)
throw new ComponentCardinalityException(
"More than 1 product association is not supported.");
if (LPLCConstants.LICENSEPOOLTYPE.equalsIgnoreCase(createLicensePoolSchemaObj.getType()))
throw new ComponentValidationException("License Type is not Valid.");
logger
.info("Invoking Licensepool Service CreateLicensePool method");
String licensepoolId = licensePoolServiceEndPoint
.createLicensePool(createLicensePoolSchemaObj);
serviceResponseType.setReturnValue(licensepoolId);
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType.setStatusCode(StatusCodeType.SUCCESS);
serviceResponseType.getStatusMessage().add(
"LicensePool created successfully");
} catch (Exception e) {
LicensePoolException licensepoolException = exceptionFactory
.getLicensePoolException(e);
if (e instanceof LPLCBaseException) {
serviceResponseType.setTransactionId(licensePoolServiceEndPoint
.getTransactionId());
serviceResponseType
.setReturnValue(LPLCConstants.SERVICE_RESPONSE_RETURN_FAILURE);
serviceResponseType.setStatusCode(StatusCodeType.FAILURE);
serviceResponseType.getStatusMessage().add(
licensepoolException.getCause().toString());
} else {
throw licensepoolException;
}
}
CreateLicensePoolResponse createResponse = new CreateLicensePoolResponse();
createResponse.setServiceResponseType(serviceResponseType);
return createResponse;
}
|
diff --git a/dspace-api/src/main/java/org/dspace/search/DSQuery.java b/dspace-api/src/main/java/org/dspace/search/DSQuery.java
index 1a86122d4..45dfb4c2c 100644
--- a/dspace-api/src/main/java/org/dspace/search/DSQuery.java
+++ b/dspace-api/src/main/java/org/dspace/search/DSQuery.java
@@ -1,502 +1,502 @@
/*
* DSQuery.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.search;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.queryParser.TokenMgrError;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.sort.SortOption;
// issues
// need to filter query string for security
// cmd line query needs to process args correctly (seems to split them up)
/**
* DSIndexer contains various static methods for performing queries on indices,
* for collections and communities.
*
*/
public class DSQuery
{
// Result types
static final String ALL = "999";
static final String ITEM = "" + Constants.ITEM;
static final String COLLECTION = "" + Constants.COLLECTION;
static final String COMMUNITY = "" + Constants.COMMUNITY;
// cache a Lucene IndexSearcher for more efficient searches
private static IndexSearcher searcher = null;
private static String indexDir = null;
private static String operator = null;
private static long lastModified;
/** log4j logger */
private static Logger log = Logger.getLogger(DSQuery.class);
static
{
String maxClauses = ConfigurationManager.getProperty("search.max-clauses");
if (maxClauses != null)
{
BooleanQuery.setMaxClauseCount(Integer.parseInt(maxClauses));
}
indexDir = ConfigurationManager.getProperty("search.dir");
operator = ConfigurationManager.getProperty("search.operator");
}
/**
* Do a query, returning a QueryResults object
*
* @param c context
* @param args query arguments in QueryArgs object
*
* @return query results QueryResults
*/
public static QueryResults doQuery(Context c, QueryArgs args)
throws IOException
{
String querystring = args.getQuery();
QueryResults qr = new QueryResults();
List hitHandles = new ArrayList();
List hitIds = new ArrayList();
List hitTypes = new ArrayList();
// set up the QueryResults object
qr.setHitHandles(hitHandles);
qr.setHitIds(hitIds);
qr.setHitTypes(hitTypes);
qr.setStart(args.getStart());
qr.setPageSize(args.getPageSize());
qr.setEtAl(args.getEtAl());
// massage the query string a bit
querystring = checkEmptyQuery(querystring); // change nulls to an empty string
// We no longer need to work around the Lucene bug with recent versions
//querystring = workAroundLuceneBug(querystring); // logicals changed to && ||, etc.
querystring = stripHandles(querystring); // remove handles from query string
querystring = stripAsterisk(querystring); // remove asterisk from beginning of string
try
{
// grab a searcher, and do the search
Searcher searcher = getSearcher(c);
QueryParser qp = new QueryParser("default", DSIndexer.getAnalyzer());
log.info("Final query string: " + querystring);
if (operator == null || operator.equals("OR"))
{
qp.setDefaultOperator(QueryParser.OR_OPERATOR);
}
else
{
qp.setDefaultOperator(QueryParser.AND_OPERATOR);
}
Query myquery = qp.parse(querystring);
Hits hits = null;
try
{
if (args.getSortOption() == null)
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField(null, SortField.SCORE, SortOption.ASCENDING.equals(args.getSortOrder()))
};
hits = searcher.search(myquery, new Sort(sortFields));
}
else
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField("sort_" + args.getSortOption().getName(), SortOption.DESCENDING.equals(args.getSortOrder())),
SortField.FIELD_SCORE
};
hits = searcher.search(myquery, new Sort(sortFields));
}
}
catch (Exception e)
{
// Lucene can throw an exception if it is unable to determine a sort time from the specified field
// Provide a fall back that just works on relevancy.
log.error("Unable to use speficied sort option: " + (args.getSortOption() == null ? "type/relevance": args.getSortOption().getName()));
hits = searcher.search(myquery, new Sort(SortField.FIELD_SCORE));
}
// set total number of hits
qr.setHitCount(hits.length());
// We now have a bunch of hits - snip out a 'window'
// defined in start, count and return the handles
// from that window
// first, are there enough hits?
if (args.getStart() < hits.length())
{
// get as many as we can, up to the window size
// how many are available after snipping off at offset 'start'?
int hitsRemaining = hits.length() - args.getStart();
int hitsToProcess = (hitsRemaining < args.getPageSize()) ? hitsRemaining
: args.getPageSize();
for (int i = args.getStart(); i < (args.getStart() + hitsToProcess); i++)
{
Document d = hits.doc(i);
String resourceId = d.get("search.resourceid");
String resourceType = d.get("search.resourcetype");
String handleText = d.get("handle");
String handleType = d.get("type");
switch (Integer.parseInt( resourceType != null ? resourceType : handleType))
{
case Constants.ITEM:
hitTypes.add(new Integer(Constants.ITEM));
break;
case Constants.COLLECTION:
hitTypes.add(new Integer(Constants.COLLECTION));
break;
case Constants.COMMUNITY:
hitTypes.add(new Integer(Constants.COMMUNITY));
break;
}
hitHandles.add( handleText );
hitIds.add( resourceId == null ? null: Integer.parseInt(resourceId) );
}
}
}
catch (NumberFormatException e)
{
log.warn(LogManager.getHeader(c, "Number format exception", "" + e));
- qr.setErrorMsg("Number format exception");
+ qr.setErrorMsg("number-format-exception");
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c, "Invalid search string", "" + e));
- qr.setErrorMsg("Invalid search string");
+ qr.setErrorMsg("invalid-search-string");
}
catch (TokenMgrError tme)
{
// Similar to parse exception
log.warn(LogManager.getHeader(c, "Invalid search string", "" + tme));
- qr.setErrorMsg("Invalid search string");
+ qr.setErrorMsg("invalid-search-string");
}
catch(BooleanQuery.TooManyClauses e)
{
log.warn(LogManager.getHeader(c, "Query too broad", e.toString()));
- qr.setErrorMsg("Your query was too broad. Try a narrower query.");
+ qr.setErrorMsg("query-too-broad");
}
return qr;
}
static String checkEmptyQuery(String myquery)
{
if (myquery == null || myquery.equals("()") || myquery.equals(""))
{
myquery = "empty_query_string";
}
return myquery;
}
/**
* Workaround Lucene bug that breaks wildcard searching.
* This is no longer required with Lucene upgrades.
*
* @param myquery
* @return
* @deprecated
*/
static String workAroundLuceneBug(String myquery)
{
// Lucene currently has a bug which breaks wildcard
// searching when you have uppercase characters.
// Here we substitute the boolean operators -- which
// have to be uppercase -- before tranforming the
// query string to lowercase.
return myquery.replaceAll(" AND ", " && ")
.replaceAll(" OR ", " || ")
.replaceAll(" NOT ", " ! ")
.toLowerCase();
}
static String stripHandles(String myquery)
{
// Drop beginning pieces of full handle strings
return myquery.replaceAll("^\\s*http://hdl\\.handle\\.net/", "")
.replaceAll("^\\s*hdl:", "");
}
static String stripAsterisk(String myquery)
{
// query strings (or words) begining with "*" cause a null pointer error
return myquery.replaceAll("^\\*", "")
.replaceAll("\\s\\*", " ")
.replaceAll("\\(\\*", "(")
.replaceAll(":\\*", ":");
}
/**
* Do a query, restricted to a collection
*
* @param c
* context
* @param args
* query args
* @param coll
* collection to restrict to
*
* @return QueryResults same results as doQuery, restricted to a collection
*/
public static QueryResults doQuery(Context c, QueryArgs args,
Collection coll) throws IOException
{
String querystring = args.getQuery();
querystring = checkEmptyQuery(querystring);
String location = "l" + (coll.getID());
String newquery = new String("+(" + querystring + ") +location:\""
+ location + "\"");
args.setQuery(newquery);
return doQuery(c, args);
}
/**
* Do a query, restricted to a community
*
* @param c
* context
* @param args
* query args
* @param comm
* community to restrict to
*
* @return QueryResults same results as doQuery, restricted to a collection
*/
public static QueryResults doQuery(Context c, QueryArgs args, Community comm)
throws IOException
{
String querystring = args.getQuery();
querystring = checkEmptyQuery(querystring);
String location = "m" + (comm.getID());
String newquery = new String("+(" + querystring + ") +location:\""
+ location + "\"");
args.setQuery(newquery);
return doQuery(c, args);
}
/**
* Do a query, printing results to stdout largely for testing, but it is
* useful
*/
public static void doCMDLineQuery(String query)
{
System.out.println("Command line query: " + query);
System.out.println("Only reporting default-sized results list");
try
{
Context c = new Context();
QueryArgs args = new QueryArgs();
args.setQuery(query);
QueryResults results = doQuery(c, args);
Iterator i = results.getHitHandles().iterator();
Iterator j = results.getHitTypes().iterator();
while (i.hasNext())
{
String thisHandle = (String) i.next();
Integer thisType = (Integer) j.next();
String type = Constants.typeText[thisType.intValue()];
// also look up type
System.out.println(type + "\t" + thisHandle);
}
}
catch (Exception e)
{
System.out.println("Exception caught: " + e);
}
}
/**
* Close any IndexSearcher that is currently open.
*/
public static void close()
{
if (searcher != null)
{
try
{
searcher.close();
searcher = null;
}
catch (IOException ioe)
{
log.error("DSQuery: Unable to close open IndexSearcher", ioe);
}
}
}
public static void main(String[] args)
{
if (args.length > 0)
{
DSQuery.doCMDLineQuery(args[0]);
}
}
/*--------- protected methods ----------*/
/**
* get an IndexReader.
* @throws IOException
*/
protected static IndexReader getIndexReader()
throws IOException
{
return getSearcher(null).getIndexReader();
}
/**
* get an IndexSearcher, hopefully a cached one (gives much better
* performance.) checks to see if the index has been modified - if so, it
* creates a new IndexSearcher
*/
protected static synchronized IndexSearcher getSearcher(Context c)
throws IOException
{
// If we have already opened a searcher, check to see if the index has been updated
// If it has, we need to close the existing searcher - we will open a new one later
if (searcher != null && lastModified != IndexReader.getCurrentVersion(indexDir))
{
try
{
// Close the cached IndexSearcher
searcher.close();
}
catch (IOException ioe)
{
// Index is probably corrupt. Log the error, but continue to either:
// 1) Return existing searcher (may yet throw exception, no worse than throwing here)
log.warn("DSQuery: Unable to check for updated index", ioe);
}
finally
{
searcher = null;
}
}
// There is no existing searcher - either this is the first execution,
// or the index has been updated and we closed the old index.
if (searcher == null)
{
// So, open a new searcher
lastModified = IndexReader.getCurrentVersion(indexDir);
searcher = new IndexSearcher(indexDir){
/*
* TODO: Has Lucene fixed this bug yet?
* Lucene doesn't release read locks in
* windows properly on finalize. Our hack
* extend IndexSearcher to force close().
*/
protected void finalize() throws Throwable {
this.close();
super.finalize();
}
};
}
return searcher;
}
}
// it's now up to the display page to do the right thing displaying
// items & communities & collections
| false | true | public static QueryResults doQuery(Context c, QueryArgs args)
throws IOException
{
String querystring = args.getQuery();
QueryResults qr = new QueryResults();
List hitHandles = new ArrayList();
List hitIds = new ArrayList();
List hitTypes = new ArrayList();
// set up the QueryResults object
qr.setHitHandles(hitHandles);
qr.setHitIds(hitIds);
qr.setHitTypes(hitTypes);
qr.setStart(args.getStart());
qr.setPageSize(args.getPageSize());
qr.setEtAl(args.getEtAl());
// massage the query string a bit
querystring = checkEmptyQuery(querystring); // change nulls to an empty string
// We no longer need to work around the Lucene bug with recent versions
//querystring = workAroundLuceneBug(querystring); // logicals changed to && ||, etc.
querystring = stripHandles(querystring); // remove handles from query string
querystring = stripAsterisk(querystring); // remove asterisk from beginning of string
try
{
// grab a searcher, and do the search
Searcher searcher = getSearcher(c);
QueryParser qp = new QueryParser("default", DSIndexer.getAnalyzer());
log.info("Final query string: " + querystring);
if (operator == null || operator.equals("OR"))
{
qp.setDefaultOperator(QueryParser.OR_OPERATOR);
}
else
{
qp.setDefaultOperator(QueryParser.AND_OPERATOR);
}
Query myquery = qp.parse(querystring);
Hits hits = null;
try
{
if (args.getSortOption() == null)
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField(null, SortField.SCORE, SortOption.ASCENDING.equals(args.getSortOrder()))
};
hits = searcher.search(myquery, new Sort(sortFields));
}
else
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField("sort_" + args.getSortOption().getName(), SortOption.DESCENDING.equals(args.getSortOrder())),
SortField.FIELD_SCORE
};
hits = searcher.search(myquery, new Sort(sortFields));
}
}
catch (Exception e)
{
// Lucene can throw an exception if it is unable to determine a sort time from the specified field
// Provide a fall back that just works on relevancy.
log.error("Unable to use speficied sort option: " + (args.getSortOption() == null ? "type/relevance": args.getSortOption().getName()));
hits = searcher.search(myquery, new Sort(SortField.FIELD_SCORE));
}
// set total number of hits
qr.setHitCount(hits.length());
// We now have a bunch of hits - snip out a 'window'
// defined in start, count and return the handles
// from that window
// first, are there enough hits?
if (args.getStart() < hits.length())
{
// get as many as we can, up to the window size
// how many are available after snipping off at offset 'start'?
int hitsRemaining = hits.length() - args.getStart();
int hitsToProcess = (hitsRemaining < args.getPageSize()) ? hitsRemaining
: args.getPageSize();
for (int i = args.getStart(); i < (args.getStart() + hitsToProcess); i++)
{
Document d = hits.doc(i);
String resourceId = d.get("search.resourceid");
String resourceType = d.get("search.resourcetype");
String handleText = d.get("handle");
String handleType = d.get("type");
switch (Integer.parseInt( resourceType != null ? resourceType : handleType))
{
case Constants.ITEM:
hitTypes.add(new Integer(Constants.ITEM));
break;
case Constants.COLLECTION:
hitTypes.add(new Integer(Constants.COLLECTION));
break;
case Constants.COMMUNITY:
hitTypes.add(new Integer(Constants.COMMUNITY));
break;
}
hitHandles.add( handleText );
hitIds.add( resourceId == null ? null: Integer.parseInt(resourceId) );
}
}
}
catch (NumberFormatException e)
{
log.warn(LogManager.getHeader(c, "Number format exception", "" + e));
qr.setErrorMsg("Number format exception");
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c, "Invalid search string", "" + e));
qr.setErrorMsg("Invalid search string");
}
catch (TokenMgrError tme)
{
// Similar to parse exception
log.warn(LogManager.getHeader(c, "Invalid search string", "" + tme));
qr.setErrorMsg("Invalid search string");
}
catch(BooleanQuery.TooManyClauses e)
{
log.warn(LogManager.getHeader(c, "Query too broad", e.toString()));
qr.setErrorMsg("Your query was too broad. Try a narrower query.");
}
return qr;
}
| public static QueryResults doQuery(Context c, QueryArgs args)
throws IOException
{
String querystring = args.getQuery();
QueryResults qr = new QueryResults();
List hitHandles = new ArrayList();
List hitIds = new ArrayList();
List hitTypes = new ArrayList();
// set up the QueryResults object
qr.setHitHandles(hitHandles);
qr.setHitIds(hitIds);
qr.setHitTypes(hitTypes);
qr.setStart(args.getStart());
qr.setPageSize(args.getPageSize());
qr.setEtAl(args.getEtAl());
// massage the query string a bit
querystring = checkEmptyQuery(querystring); // change nulls to an empty string
// We no longer need to work around the Lucene bug with recent versions
//querystring = workAroundLuceneBug(querystring); // logicals changed to && ||, etc.
querystring = stripHandles(querystring); // remove handles from query string
querystring = stripAsterisk(querystring); // remove asterisk from beginning of string
try
{
// grab a searcher, and do the search
Searcher searcher = getSearcher(c);
QueryParser qp = new QueryParser("default", DSIndexer.getAnalyzer());
log.info("Final query string: " + querystring);
if (operator == null || operator.equals("OR"))
{
qp.setDefaultOperator(QueryParser.OR_OPERATOR);
}
else
{
qp.setDefaultOperator(QueryParser.AND_OPERATOR);
}
Query myquery = qp.parse(querystring);
Hits hits = null;
try
{
if (args.getSortOption() == null)
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField(null, SortField.SCORE, SortOption.ASCENDING.equals(args.getSortOrder()))
};
hits = searcher.search(myquery, new Sort(sortFields));
}
else
{
SortField[] sortFields = new SortField[] {
new SortField("search.resourcetype", true),
new SortField("sort_" + args.getSortOption().getName(), SortOption.DESCENDING.equals(args.getSortOrder())),
SortField.FIELD_SCORE
};
hits = searcher.search(myquery, new Sort(sortFields));
}
}
catch (Exception e)
{
// Lucene can throw an exception if it is unable to determine a sort time from the specified field
// Provide a fall back that just works on relevancy.
log.error("Unable to use speficied sort option: " + (args.getSortOption() == null ? "type/relevance": args.getSortOption().getName()));
hits = searcher.search(myquery, new Sort(SortField.FIELD_SCORE));
}
// set total number of hits
qr.setHitCount(hits.length());
// We now have a bunch of hits - snip out a 'window'
// defined in start, count and return the handles
// from that window
// first, are there enough hits?
if (args.getStart() < hits.length())
{
// get as many as we can, up to the window size
// how many are available after snipping off at offset 'start'?
int hitsRemaining = hits.length() - args.getStart();
int hitsToProcess = (hitsRemaining < args.getPageSize()) ? hitsRemaining
: args.getPageSize();
for (int i = args.getStart(); i < (args.getStart() + hitsToProcess); i++)
{
Document d = hits.doc(i);
String resourceId = d.get("search.resourceid");
String resourceType = d.get("search.resourcetype");
String handleText = d.get("handle");
String handleType = d.get("type");
switch (Integer.parseInt( resourceType != null ? resourceType : handleType))
{
case Constants.ITEM:
hitTypes.add(new Integer(Constants.ITEM));
break;
case Constants.COLLECTION:
hitTypes.add(new Integer(Constants.COLLECTION));
break;
case Constants.COMMUNITY:
hitTypes.add(new Integer(Constants.COMMUNITY));
break;
}
hitHandles.add( handleText );
hitIds.add( resourceId == null ? null: Integer.parseInt(resourceId) );
}
}
}
catch (NumberFormatException e)
{
log.warn(LogManager.getHeader(c, "Number format exception", "" + e));
qr.setErrorMsg("number-format-exception");
}
catch (ParseException e)
{
// a parse exception - log and return null results
log.warn(LogManager.getHeader(c, "Invalid search string", "" + e));
qr.setErrorMsg("invalid-search-string");
}
catch (TokenMgrError tme)
{
// Similar to parse exception
log.warn(LogManager.getHeader(c, "Invalid search string", "" + tme));
qr.setErrorMsg("invalid-search-string");
}
catch(BooleanQuery.TooManyClauses e)
{
log.warn(LogManager.getHeader(c, "Query too broad", e.toString()));
qr.setErrorMsg("query-too-broad");
}
return qr;
}
|
diff --git a/Breakout/src/com/jsteadman/Breakout/Breakout.java b/Breakout/src/com/jsteadman/Breakout/Breakout.java
index 57ae0e3..03df194 100644
--- a/Breakout/src/com/jsteadman/Breakout/Breakout.java
+++ b/Breakout/src/com/jsteadman/Breakout/Breakout.java
@@ -1,595 +1,594 @@
package com.jsteadman.Breakout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.KeyEvent;
import acm.graphics.GLabel;
import acm.graphics.GObject;
import acm.graphics.GOval;
import acm.graphics.GRect;
import acm.graphics.GRoundRect;
import acm.program.GraphicsProgram;
import acm.util.RandomGenerator;
@SuppressWarnings("serial")
public class Breakout extends GraphicsProgram {
// constants for applet size
private final int APPLET_WIDTH = 400;
private final int APPLET_HEIGHT = 600;
// constants for paddle
private final int PADDLE_Y_OFFSET = 30;
private double PADDLE_WIDTH;
private final int PADDLE_HEIGHT = 10;
private double PADDLE_X;
private final int PADDLE_Y = APPLET_HEIGHT - PADDLE_Y_OFFSET;
// constants for bricks
private int BRICK_X = 2;
private int BRICK_Y = 70;
private final int BRICK_ROWS = 10;
private final int BRICK_COLUMNS = 10;
private final int BRICK_SEPARATION = 4;
private final int BRICK_HEIGHT = 8;
private final int BRICK_WIDTH = (APPLET_WIDTH / BRICK_COLUMNS)
- BRICK_SEPARATION;
private static Color BRICK_COLOR;
// constants for ball
private final int BALL_RADIUS = 10;
private final int BALL_X = APPLET_WIDTH / 2 - BALL_RADIUS;
private final int BALL_Y = APPLET_HEIGHT / 2 - BALL_RADIUS;
private final int BALL_DIAMETER = 2 * BALL_RADIUS;
private float BALL_DELAY;
// counter and keeping score
private int BRICK_COUNTER = BRICK_COLUMNS * BRICK_ROWS;
private int POINTS;
GLabel wordScore;
GLabel displayPoints;
// variables for objects
private GRect brick;
private GOval ball;
private GRoundRect paddle;
// ball velocity
private double ballVX = 3;
private double ballVY;
// random generator used to determine initial ball direction
RandomGenerator rand = new RandomGenerator();
// difficulty
int difficulty;
// replay
String userResponse;
// balls remaining
GLabel wordBallsRemaining;
GLabel ballsRemaining;
int BALLS_REMAINING;
public void run() {
setSize(APPLET_WIDTH, APPLET_HEIGHT);
addKeyListeners();
chooseDifficulty();
}
/*
* This method is used to call everything needed in order to play the game.
*/
private void setUpGame() {
wordScore();
ballsRemaining();
trackBallsRemaining();
createBricks();
theBall();
thePaddle();
gameCountdown();
moveBall();
}
/*
* Here we allow the user to choose a difficulty for playing.
*
* 1 - easy
* 2 - medium
* 3 - hard
*
* The values for the ball delay and paddle are changed depending on what
* difficulty is chosen. After a difficulty is chosen and values are set,
* the setUpGame() method is called.
*/
private void chooseDifficulty() {
GLabel diff = new GLabel("Please select a difficulty");
diff.setColor(Color.BLUE);
diff.setFont(new Font("Arial", Font.PLAIN, 20));
diff.setLocation(APPLET_WIDTH / 2 - diff.getWidth() / 2, APPLET_HEIGHT
/ 2 - diff.getHeight() / 2);
add(diff);
GLabel easy = new GLabel("Press 1 for EASY");
easy.setColor(Color.ORANGE);
easy.setFont(new Font("Arial", Font.PLAIN, 15));
easy.setLocation(APPLET_WIDTH / 2 - easy.getWidth() / 2, APPLET_HEIGHT
/ 2 + easy.getHeight());
add(easy);
GLabel medium = new GLabel("Press 2 for MEDIUM");
medium.setColor(Color.CYAN);
medium.setFont(new Font("Arial", Font.PLAIN, 15));
medium.setLocation(APPLET_WIDTH / 2 - easy.getWidth() / 2,
APPLET_HEIGHT / 2 + medium.getHeight() * 2);
add(medium);
GLabel hard = new GLabel("Press 3 for HARD");
hard.setColor(Color.RED);
hard.setFont(new Font("Arial", Font.PLAIN, 15));
hard.setLocation(APPLET_WIDTH / 2 - easy.getWidth() / 2, APPLET_HEIGHT
/ 2 + medium.getHeight() * 3);
add(hard);
GLabel troll = new GLabel("Press 4 for TROLL");
troll.setColor(Color.GREEN);
troll.setFont(new Font("Arial", Font.PLAIN, 15));
troll.setLocation(APPLET_WIDTH / 2 - easy.getWidth() / 2, APPLET_HEIGHT
/ 2 + medium.getHeight() * 4);
add(troll);
difficulty = 0;
while (difficulty == 0) {
pause(50);
}
if (difficulty == 1) {
PADDLE_WIDTH = 60;
BALL_DELAY = 15;
} else if (difficulty == 2) {
PADDLE_WIDTH = 50;
BALL_DELAY = 14;
} else if (difficulty == 3) {
PADDLE_WIDTH = 40;
BALL_DELAY = 13;
// troll mode just for fun!
} else if (difficulty == 4) {
PADDLE_WIDTH = 50;
BALL_DELAY = 13;
}
// set starting location for paddle here
PADDLE_X = APPLET_WIDTH / 2 - PADDLE_WIDTH / 2;
remove(diff);
remove(easy);
remove(medium);
remove(hard);
remove(troll);
setUpGame();
}
private void gameCountdown() {
for (int countdown = 4; countdown > 0; countdown--) {
GLabel counter = new GLabel("" + countdown);
counter.setColor(Color.RED);
counter.setFont(new Font("Arial", Font.PLAIN, 25));
counter.setLocation(APPLET_WIDTH / 2 - counter.getWidth() / 2,
APPLET_HEIGHT / 2 + counter.getHeight() * 2);
add(counter);
pause(1000);
remove(counter);
}
}
private void createBricks() {
/*
* adjust the color of the bricks based every two rows
*/
for (int j = 1; j <= BRICK_ROWS; j++) {
if (j <= 2) {
BRICK_COLOR = Color.RED;
} else if (j > 2 && j <= 4) {
BRICK_COLOR = Color.ORANGE;
} else if (j > 4 && j <= 6) {
BRICK_COLOR = Color.YELLOW;
} else if (j > 6 && j <= 8) {
BRICK_COLOR = Color.GREEN;
} else if (j > 8) {
BRICK_COLOR = Color.CYAN;
}
for (int i = 1; i <= (BRICK_COLUMNS); i++) {
brick = new GRect(BRICK_WIDTH, BRICK_HEIGHT);
brick.setFillColor(BRICK_COLOR);
brick.setColor(BRICK_COLOR);
brick.setFilled(true);
brick.setLocation(BRICK_X, BRICK_Y);
BRICK_X += BRICK_WIDTH + BRICK_SEPARATION;
add(brick);
}
/*
* Since the offset changes as the above loop adds a new brick,
* reset it back to the start for each new row that is created.
*/
BRICK_X = BRICK_SEPARATION / 2;
BRICK_Y += BRICK_HEIGHT + BRICK_SEPARATION;
}
}
/*
* Create the paddle.
*/
private void thePaddle() {
paddle = new GRoundRect(PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFillColor(Color.DARK_GRAY);
paddle.setFilled(true);
paddle.setLocation(PADDLE_X, PADDLE_Y);
add(paddle);
}
/*
* Troll mode!
*
* I'm a dirty stinker.
*
* With this mode active the paddle shrinks half a pixel every time
* a brick is removed. With one brick remaining the paddle will only
* be 0.5 pixels wide. I suppose it's beatable... MAYBE. ;)
*/
private void changePaddleWidth() {
double x = paddle.getX() + 0.25;
double y = paddle.getY();
remove(paddle);
PADDLE_WIDTH -=0.5;
paddle = new GRoundRect(PADDLE_WIDTH, PADDLE_HEIGHT);
paddle.setFillColor(Color.DARK_GRAY);
paddle.setFilled(true);
paddle.setLocation(x, y);
add(paddle);;
}
/*
* Handles controlling the paddle with the arrow keys.
*
* (non-Javadoc)
*
* @see acm.program.Program#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent e) {
/*
* A null check is used here since the paddle method has not yet been
* called to prevent the game from crashing.
*/
if (paddle != null) {
double x = paddle.getX();
double y = 0;
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
if (x < (APPLET_WIDTH - PADDLE_WIDTH) - PADDLE_WIDTH) {
paddle.move(PADDLE_WIDTH, y);
} else {
paddle.move(APPLET_WIDTH - x - PADDLE_WIDTH, y);
}
break;
case KeyEvent.VK_LEFT:
if (x > 0 && x > PADDLE_WIDTH) {
paddle.move(-PADDLE_WIDTH, y);
} else {
paddle.move(-x, y);
}
break;
}
}
switch (e.getKeyCode()) {
case KeyEvent.VK_1:
difficulty = 1;
break;
case KeyEvent.VK_2:
difficulty = 2;
break;
case KeyEvent.VK_3:
difficulty = 3;
break;
case KeyEvent.VK_4:
difficulty = 4;
break;
case KeyEvent.VK_Y:
userResponse = "y";
break;
case KeyEvent.VK_N:
userResponse = "n";
break;
default:
break;
}
}
/*
* Create the ball.
*/
private void theBall() {
// launches ball in random direction
ballVY = rand.nextDouble(1.0, 3.0);
ball = new GOval(BALL_DIAMETER, BALL_DIAMETER);
ball.setFillColor(Color.DARK_GRAY);
ball.setFilled(true);
ball.setLocation(BALL_X, BALL_Y);
add(ball);
}
/*
* This accounts for all four "corners" of the ball and returns each element
* that the ball interacts with. If no element is detected, return null.
*/
private GObject detectCollision() {
if (getElementAt(ball.getX(), ball.getY()) != null) {
return getElementAt(ball.getX(), ball.getY());
} else if (getElementAt(ball.getX() + BALL_DIAMETER, ball.getY()) != null) {
return getElementAt(ball.getX() + BALL_DIAMETER, ball.getY());
} else if (getElementAt(ball.getX(), ball.getY() + BALL_DIAMETER) != null) {
return getElementAt(ball.getX(), ball.getY() + BALL_DIAMETER);
} else if (getElementAt(ball.getX() + BALL_DIAMETER, ball.getY()
+ BALL_DIAMETER) != null) {
return getElementAt(ball.getX() + BALL_DIAMETER, ball.getY()
+ BALL_DIAMETER);
} else {
return null;
}
}
/*
* Here we make the ball move. First we make it change directions when it
* touches the walls and ceiling. Then we use the detectCollision method to
* determine what object the ball has hit. If that object is not the paddle,
* then we remove it. The infinite loop is broken when either all the bricks
* are destroyed or the ball touches the bottom of the screen.
*/
private void moveBall() {
boolean play = true;
while (play) {
// bounce ball off walls and ceiling
if (ball.getX() >= APPLET_WIDTH - BALL_DIAMETER) {
ballVX = -Math.abs(ballVX);
}
if (ball.getX() <= 0) {
ballVX = Math.abs(ballVX);
}
if (ball.getY() <= 0) {
ballVY = Math.abs(ballVY);
}
GObject collider = detectCollision();
if (collider == paddle && ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (collider == paddle && ballVY < 0) {
- ballVY = Math.abs(ballVY);
// do nothing for score, points and balls remaining
} else if (collider == wordScore || collider == displayPoints
|| collider == wordBallsRemaining
|| collider == ballsRemaining) {
// handle the bricks
} else if (collider != null) {
if (ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (ballVY < 0) {
ballVY = Math.abs(ballVY);
}
/*
* Increase ball velocity
*/
BALL_DELAY -= 0.05;
/*
* Call method to change paddle width on troll difficulty.
*/
if (difficulty == 4) {
changePaddleWidth();
}
/*
* Count down from the total number of bricks each time one is
* removed.
*/
BRICK_COUNTER--;
/*
* The displayPoints must first be removed before setting the
* new value. Otherwise, the new value is always written on top
* of the previous.
*/
remove(displayPoints);
/*
* The GObejct collider is sent to the track points method so we
* can get the color of the object for tracking the points.
*/
trackPoints(collider);
/*
* Remove the brick.
*/
remove(collider);
if (BRICK_COUNTER == 0) {
play = false;
}
/*
* Break the while loop if the ball touches the bottom of the
* screen thus ending the game.
*/
} else if (ball.getY() > APPLET_HEIGHT - BALL_DIAMETER) {
if (BALLS_REMAINING > 0) {
BALLS_REMAINING--;
remove(ballsRemaining);
trackBallsRemaining();
remove(ball);
theBall();
pause(500);
} else {
play = false;
}
}
// move the ball
ball.move(ballVX, ballVY);
// set the speed of the moving ball
pause(BALL_DELAY);
}
// Call the endGame() method if the while loop is broken
endGame();
}
/*
* Use two separate methods for the score. One for just the word "Score" and
* another to track the points. This is so we don't redraw the word every
* time we score which causes a minor blip. It looks much cleaner.
*/
private void wordScore() {
/*
* We have to set the initial points to zero here. If we don't then
* there is nothing to remove and the program will crash.
*/
POINTS = 0;
displayPoints = new GLabel("" + POINTS);
displayPoints.setLocation(65, 25);
displayPoints.setFont(new Font("Arial", Font.PLAIN, 20));
add(displayPoints);
/*
* This just adds the word "Score" which is never changed.
*/
wordScore = new GLabel("Score: ");
wordScore.setLocation(5, 25);
wordScore.setFont(new Font("Arial", Font.PLAIN, 20));
add(wordScore);
}
/*
* This method keeps track of the points accumulated. We use the getColor()
* method to return the color of the collider and adjust the points based on
* that color.
*/
private void trackPoints(GObject collider) {
BRICK_COLOR = collider.getColor();
if (BRICK_COLOR == Color.CYAN) {
POINTS += 10;
} else if (BRICK_COLOR == Color.GREEN) {
POINTS += 20;
} else if (BRICK_COLOR == Color.YELLOW) {
POINTS += 30;
} else if (BRICK_COLOR == Color.ORANGE) {
POINTS += 40;
} else if (BRICK_COLOR == Color.RED) {
POINTS += 50;
}
displayPoints = new GLabel("" + POINTS);
displayPoints.setLocation(65, 25);
displayPoints.setFont(new Font("Arial", Font.PLAIN, 20));
add(displayPoints);
}
/*
* Just like with the score, we display just the word Balls Remaining and
* adjust the number independently.
*/
private void ballsRemaining() {
BALLS_REMAINING = 2;
wordBallsRemaining = new GLabel("Balls Remaining: ");
wordBallsRemaining.setLocation(235, 25);
wordBallsRemaining.setFont(new Font("Arial", Font.PLAIN, 20));
add(wordBallsRemaining);
}
/*
* This method keeps track of the number of balls remaining.
*/
private void trackBallsRemaining() {
ballsRemaining = new GLabel("" + BALLS_REMAINING);
ballsRemaining.setLocation(385, 25);
ballsRemaining.setFont(new Font("Arial", Font.PLAIN, 20));
add(ballsRemaining);
}
/*
* This handles what action to take once the game ends.
*/
private void endGame() {
GLabel end;
/*
* If the game ends and the brick counter is 0 then all the bricks have
* been removed and the user has won the game.
*/
if (BRICK_COUNTER == 0) {
end = new GLabel("Congratulations! You won!");
end.setFont(new Font("Arial", Font.BOLD, 20));
end.setColor(Color.BLUE);
/*
* If there are bricks remaining when the game has ended then the
* game is lost.
*/
} else {
// a tribute to Hudson
end = new GLabel("Game Over, Man!");
end.setFont(new Font("Arial", Font.BOLD, 20));
end.setColor(Color.RED);
}
end.setLocation(getWidth() / 2 - end.getWidth() / 2, getHeight() / 2
- end.getHeight() / 2);
add(end);
pause(500);
replayGame();
}
/*
* This method is called at the end of the endGame() method. It asks the user
* whether they would like to replay or not. If they choose yes, everything is
* removed and the Y location for the bricks is reset. Then the chooseDifficulty()
* method is re-called and everything resumes like when the game is initially
* started. If the user says no they do not want to replay, the game closes.
*/
private void replayGame() {
GLabel replay = new GLabel("Would you like to play again?" + "\n"
+ "Press Y or N");
replay.setFont(new Font("Arial", Font.PLAIN, 20));
replay.setLocation(getWidth() / 2 - replay.getWidth() / 2, getHeight()
/ 2 + replay.getHeight());
add(replay);
userResponse = "";
while (userResponse != "y") {
pause(50);
if (userResponse == "y") {
removeAll(); // remove everything on the screen
BRICK_Y = 70; // reset Y location of bricks for loop
chooseDifficulty();
}
if (userResponse == "n") {
System.exit(0);
}
}
}
}
| true | true | private void moveBall() {
boolean play = true;
while (play) {
// bounce ball off walls and ceiling
if (ball.getX() >= APPLET_WIDTH - BALL_DIAMETER) {
ballVX = -Math.abs(ballVX);
}
if (ball.getX() <= 0) {
ballVX = Math.abs(ballVX);
}
if (ball.getY() <= 0) {
ballVY = Math.abs(ballVY);
}
GObject collider = detectCollision();
if (collider == paddle && ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (collider == paddle && ballVY < 0) {
ballVY = Math.abs(ballVY);
// do nothing for score, points and balls remaining
} else if (collider == wordScore || collider == displayPoints
|| collider == wordBallsRemaining
|| collider == ballsRemaining) {
// handle the bricks
} else if (collider != null) {
if (ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (ballVY < 0) {
ballVY = Math.abs(ballVY);
}
/*
* Increase ball velocity
*/
BALL_DELAY -= 0.05;
/*
* Call method to change paddle width on troll difficulty.
*/
if (difficulty == 4) {
changePaddleWidth();
}
/*
* Count down from the total number of bricks each time one is
* removed.
*/
BRICK_COUNTER--;
/*
* The displayPoints must first be removed before setting the
* new value. Otherwise, the new value is always written on top
* of the previous.
*/
remove(displayPoints);
/*
* The GObejct collider is sent to the track points method so we
* can get the color of the object for tracking the points.
*/
trackPoints(collider);
/*
* Remove the brick.
*/
remove(collider);
if (BRICK_COUNTER == 0) {
play = false;
}
/*
* Break the while loop if the ball touches the bottom of the
* screen thus ending the game.
*/
} else if (ball.getY() > APPLET_HEIGHT - BALL_DIAMETER) {
if (BALLS_REMAINING > 0) {
BALLS_REMAINING--;
remove(ballsRemaining);
trackBallsRemaining();
remove(ball);
theBall();
pause(500);
} else {
play = false;
}
}
// move the ball
ball.move(ballVX, ballVY);
// set the speed of the moving ball
pause(BALL_DELAY);
}
// Call the endGame() method if the while loop is broken
endGame();
}
| private void moveBall() {
boolean play = true;
while (play) {
// bounce ball off walls and ceiling
if (ball.getX() >= APPLET_WIDTH - BALL_DIAMETER) {
ballVX = -Math.abs(ballVX);
}
if (ball.getX() <= 0) {
ballVX = Math.abs(ballVX);
}
if (ball.getY() <= 0) {
ballVY = Math.abs(ballVY);
}
GObject collider = detectCollision();
if (collider == paddle && ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (collider == paddle && ballVY < 0) {
// do nothing for score, points and balls remaining
} else if (collider == wordScore || collider == displayPoints
|| collider == wordBallsRemaining
|| collider == ballsRemaining) {
// handle the bricks
} else if (collider != null) {
if (ballVY > 0) {
ballVY = -Math.abs(ballVY);
} else if (ballVY < 0) {
ballVY = Math.abs(ballVY);
}
/*
* Increase ball velocity
*/
BALL_DELAY -= 0.05;
/*
* Call method to change paddle width on troll difficulty.
*/
if (difficulty == 4) {
changePaddleWidth();
}
/*
* Count down from the total number of bricks each time one is
* removed.
*/
BRICK_COUNTER--;
/*
* The displayPoints must first be removed before setting the
* new value. Otherwise, the new value is always written on top
* of the previous.
*/
remove(displayPoints);
/*
* The GObejct collider is sent to the track points method so we
* can get the color of the object for tracking the points.
*/
trackPoints(collider);
/*
* Remove the brick.
*/
remove(collider);
if (BRICK_COUNTER == 0) {
play = false;
}
/*
* Break the while loop if the ball touches the bottom of the
* screen thus ending the game.
*/
} else if (ball.getY() > APPLET_HEIGHT - BALL_DIAMETER) {
if (BALLS_REMAINING > 0) {
BALLS_REMAINING--;
remove(ballsRemaining);
trackBallsRemaining();
remove(ball);
theBall();
pause(500);
} else {
play = false;
}
}
// move the ball
ball.move(ballVX, ballVY);
// set the speed of the moving ball
pause(BALL_DELAY);
}
// Call the endGame() method if the while loop is broken
endGame();
}
|
diff --git a/pixmind/src/com/pix/mind/levels/FirstLevel.java b/pixmind/src/com/pix/mind/levels/FirstLevel.java
index 6fb6865..acb08c4 100644
--- a/pixmind/src/com/pix/mind/levels/FirstLevel.java
+++ b/pixmind/src/com/pix/mind/levels/FirstLevel.java
@@ -1,315 +1,317 @@
package com.pix.mind.levels;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.pix.mind.PixMindGame;
import com.pix.mind.actors.PixGuyActor;
import com.pix.mind.actors.PlatformActivatorActor;
import com.pix.mind.actors.StaticPlatformActor;
import com.pix.mind.box2d.bodies.PixGuy;
import com.pix.mind.box2d.bodies.PlatformActivator;
import com.pix.mind.box2d.bodies.StaticPlatform;
import com.pix.mind.controllers.ArrowController;
import com.pix.mind.controllers.PixGuyController;
public class FirstLevel implements Screen {
private OrthographicCamera camera;
private World world;
private PixGuy pixGuy;
private Box2DDebugRenderer debugRenderer;
private PixMindGame game;
private Image pixGuySkin;
private Stage stage;
private Stage stageGui;
private ArrayList<StaticPlatformActor> platformList;
private ArrayList<PlatformActivatorActor> activatorList;
public FirstLevel(PixMindGame game) {
this.game = game;
}
@Override
public void render(float delta) {
// TODO Auto-generated method stub
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// debugRenderer.render(world, camera.combined);
stage.draw();
stageGui.draw();
stage.getCamera().position.x = pixGuy.getPosX();
stage.getCamera().position.y = pixGuy.getPosY();
camera.position.x = pixGuy.getPosX() * PixMindGame.WORLD_TO_BOX;
camera.position.y = pixGuy.getPosY() * PixMindGame.WORLD_TO_BOX;
camera.update();
world.step(delta, 6, 2);
pixGuy.setActualPosition();
stage.act();
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
// TODO Auto-generated method stub
// float w = Gdx.graphics.getWidth();
// float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(PixMindGame.w
* PixMindGame.WORLD_TO_BOX, PixMindGame.h
* PixMindGame.WORLD_TO_BOX);
camera.translate(PixMindGame.w / 2 * PixMindGame.WORLD_TO_BOX,
PixMindGame.h / 2 * PixMindGame.WORLD_TO_BOX);
// Box2d code
world = new World(new Vector2(0, -10), true);
debugRenderer = new Box2DDebugRenderer();
platformList = new ArrayList<StaticPlatformActor>();
activatorList = new ArrayList<PlatformActivatorActor>();
// comment to be commited
//float posX = 2f, posY = 2f, width = 1f, heigth = 0.2f;
StaticPlatform sPlatform = new StaticPlatform(world, 8,5, 1,0.1f);
StaticPlatform s2Platform = new StaticPlatform(world,3, 2,1,0.1f);
StaticPlatform s3Platform = new StaticPlatform(world, 5, 3,1,0.1f);
StaticPlatform s4Platform = new StaticPlatform(world, 6,4,1,0.1f);
StaticPlatform s5Platform = new StaticPlatform(world, 1,1,1,0.1f);
StaticPlatform s6Platform = new StaticPlatform(world, 2,3,1,0.1f);
StaticPlatform s7Platform = new StaticPlatform(world, 1.5f,4,1,0.1f);
//s
PlatformActivator pActivator = new PlatformActivator(world, 0, 5, 0.1f);
PlatformActivator p2Activator = new PlatformActivator(world, 8, 6, 0.1f);
PlatformActivator p3Activator= new PlatformActivator(world, 0, 2, 0.1f);
PlatformActivator p4Activator= new PlatformActivator(world, 2, 5, 0.1f);
StaticPlatformActor s1Skin = new StaticPlatformActor(sPlatform,
Color.RED, false);
StaticPlatformActor s2Skin = new StaticPlatformActor(s2Platform,
Color.BLUE, true);
StaticPlatformActor s3Skin = new StaticPlatformActor(s3Platform,
Color.GREEN, false);
StaticPlatformActor s4Skin = new StaticPlatformActor(s4Platform,
Color.BLACK, true);
StaticPlatformActor s5Skin = new StaticPlatformActor(s5Platform,
Color.RED, false);
StaticPlatformActor s6Skin = new StaticPlatformActor(s6Platform,
Color.BLACK, true);
StaticPlatformActor s7Skin = new StaticPlatformActor(s7Platform,
Color.BLACK, true);
platformList.add(s1Skin);
platformList.add(s2Skin);
platformList.add(s3Skin);
platformList.add(s4Skin);
platformList.add(s5Skin);
platformList.add(s6Skin);
platformList.add(s7Skin);
PlatformActivatorActor a1Skin = new PlatformActivatorActor(pActivator,
Color.RED, false);
PlatformActivatorActor a2Skin = new PlatformActivatorActor(p2Activator,
Color.BLACK, true);
PlatformActivatorActor a3Skin = new PlatformActivatorActor(p3Activator,
Color.GREEN, false);
PlatformActivatorActor a4Skin = new PlatformActivatorActor(p4Activator,
Color.BLUE, true);
activatorList.add(a1Skin);
activatorList.add(a2Skin);
activatorList.add(a3Skin);
activatorList.add(a4Skin);
// main character initialization
pixGuy = new PixGuy(world, 4,4, 0.2f, 0.2f);
stage = new Stage(PixMindGame.w, PixMindGame.h, true);
stageGui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),
true);
PixGuyController controller = new ArrowController(pixGuy, stageGui);
pixGuy.setController(controller);
pixGuySkin = new PixGuyActor(pixGuy);
stage.addActor(pixGuySkin);
stage.addActor(s1Skin);
stage.addActor(s2Skin);
stage.addActor(s3Skin);
stage.addActor(s4Skin);
stage.addActor(s5Skin);
stage.addActor(s6Skin);
stage.addActor(s7Skin);
stage.addActor(a1Skin);
stage.addActor(a2Skin);
stage.addActor(a3Skin);
stage.addActor(a4Skin);
camera.update();
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
Fixture fixGuy= null;
Fixture fixPlatform = null;
Fixture fixActivator = null;
//get fixture fixguy
if (contact.getFixtureA().getUserData().equals(PixGuy.PIX_ID)) {
fixGuy = contact.getFixtureA();
// fixPlatform = contact.getFixtureB();
} else {
// fixPlatform = contact.getFixtureA();
fixGuy = contact.getFixtureB();
}
//get fixture Platform
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor
|| contact.getFixtureB().getUserData()
instanceof StaticPlatformActor ) {
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor) {
fixPlatform = contact.getFixtureA();
} else {
fixPlatform = contact.getFixtureB();
}
}
//get fixture PlatformActivator
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor
|| contact.getFixtureB().getUserData()
instanceof PlatformActivatorActor) {
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor) {
fixActivator = contact.getFixtureA();
} else {
fixActivator = contact.getFixtureB();
}
}
//collision with a Activator
if(fixActivator!=null){
PlatformActivatorActor platformActivatorActor = (PlatformActivatorActor) fixActivator.getUserData();
if(platformActivatorActor.isActive()){
//if activator is black go to next level
if(platformActivatorActor.color.equals(Color.BLACK)){
game.changeLevel(game.getSecondLevel());
}
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
//get all activator of the same color and change state
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
}else{
//platformActivatorActor.setActive(true);
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
}
}
//jump only if collide with a platform and its not sensor
if(fixPlatform!=null && !fixPlatform.isSensor()){
//only jump if bottom position of pixguy is equal or above of top position of the platform
System.out.println(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX);
System.out.println(fixPlatform.getBody().getPosition().y);
if(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX >fixPlatform.getBody().getPosition().y)
+ {
fixGuy.getBody().setLinearVelocity(0, 0);
fixGuy.getBody().applyLinearImpulse(new Vector2(0, 0.1f),
fixGuy.getBody().getWorldCenter(), true);
+ }
}
}
@Override
public void endContact(Contact contact) {
// TODO Auto-generated method stub
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
// TODO Auto-generated method stub
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
// TODO Auto-generated method stub
}
});
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
| false | true | public void show() {
// TODO Auto-generated method stub
// float w = Gdx.graphics.getWidth();
// float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(PixMindGame.w
* PixMindGame.WORLD_TO_BOX, PixMindGame.h
* PixMindGame.WORLD_TO_BOX);
camera.translate(PixMindGame.w / 2 * PixMindGame.WORLD_TO_BOX,
PixMindGame.h / 2 * PixMindGame.WORLD_TO_BOX);
// Box2d code
world = new World(new Vector2(0, -10), true);
debugRenderer = new Box2DDebugRenderer();
platformList = new ArrayList<StaticPlatformActor>();
activatorList = new ArrayList<PlatformActivatorActor>();
// comment to be commited
//float posX = 2f, posY = 2f, width = 1f, heigth = 0.2f;
StaticPlatform sPlatform = new StaticPlatform(world, 8,5, 1,0.1f);
StaticPlatform s2Platform = new StaticPlatform(world,3, 2,1,0.1f);
StaticPlatform s3Platform = new StaticPlatform(world, 5, 3,1,0.1f);
StaticPlatform s4Platform = new StaticPlatform(world, 6,4,1,0.1f);
StaticPlatform s5Platform = new StaticPlatform(world, 1,1,1,0.1f);
StaticPlatform s6Platform = new StaticPlatform(world, 2,3,1,0.1f);
StaticPlatform s7Platform = new StaticPlatform(world, 1.5f,4,1,0.1f);
//s
PlatformActivator pActivator = new PlatformActivator(world, 0, 5, 0.1f);
PlatformActivator p2Activator = new PlatformActivator(world, 8, 6, 0.1f);
PlatformActivator p3Activator= new PlatformActivator(world, 0, 2, 0.1f);
PlatformActivator p4Activator= new PlatformActivator(world, 2, 5, 0.1f);
StaticPlatformActor s1Skin = new StaticPlatformActor(sPlatform,
Color.RED, false);
StaticPlatformActor s2Skin = new StaticPlatformActor(s2Platform,
Color.BLUE, true);
StaticPlatformActor s3Skin = new StaticPlatformActor(s3Platform,
Color.GREEN, false);
StaticPlatformActor s4Skin = new StaticPlatformActor(s4Platform,
Color.BLACK, true);
StaticPlatformActor s5Skin = new StaticPlatformActor(s5Platform,
Color.RED, false);
StaticPlatformActor s6Skin = new StaticPlatformActor(s6Platform,
Color.BLACK, true);
StaticPlatformActor s7Skin = new StaticPlatformActor(s7Platform,
Color.BLACK, true);
platformList.add(s1Skin);
platformList.add(s2Skin);
platformList.add(s3Skin);
platformList.add(s4Skin);
platformList.add(s5Skin);
platformList.add(s6Skin);
platformList.add(s7Skin);
PlatformActivatorActor a1Skin = new PlatformActivatorActor(pActivator,
Color.RED, false);
PlatformActivatorActor a2Skin = new PlatformActivatorActor(p2Activator,
Color.BLACK, true);
PlatformActivatorActor a3Skin = new PlatformActivatorActor(p3Activator,
Color.GREEN, false);
PlatformActivatorActor a4Skin = new PlatformActivatorActor(p4Activator,
Color.BLUE, true);
activatorList.add(a1Skin);
activatorList.add(a2Skin);
activatorList.add(a3Skin);
activatorList.add(a4Skin);
// main character initialization
pixGuy = new PixGuy(world, 4,4, 0.2f, 0.2f);
stage = new Stage(PixMindGame.w, PixMindGame.h, true);
stageGui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),
true);
PixGuyController controller = new ArrowController(pixGuy, stageGui);
pixGuy.setController(controller);
pixGuySkin = new PixGuyActor(pixGuy);
stage.addActor(pixGuySkin);
stage.addActor(s1Skin);
stage.addActor(s2Skin);
stage.addActor(s3Skin);
stage.addActor(s4Skin);
stage.addActor(s5Skin);
stage.addActor(s6Skin);
stage.addActor(s7Skin);
stage.addActor(a1Skin);
stage.addActor(a2Skin);
stage.addActor(a3Skin);
stage.addActor(a4Skin);
camera.update();
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
Fixture fixGuy= null;
Fixture fixPlatform = null;
Fixture fixActivator = null;
//get fixture fixguy
if (contact.getFixtureA().getUserData().equals(PixGuy.PIX_ID)) {
fixGuy = contact.getFixtureA();
// fixPlatform = contact.getFixtureB();
} else {
// fixPlatform = contact.getFixtureA();
fixGuy = contact.getFixtureB();
}
//get fixture Platform
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor
|| contact.getFixtureB().getUserData()
instanceof StaticPlatformActor ) {
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor) {
fixPlatform = contact.getFixtureA();
} else {
fixPlatform = contact.getFixtureB();
}
}
//get fixture PlatformActivator
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor
|| contact.getFixtureB().getUserData()
instanceof PlatformActivatorActor) {
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor) {
fixActivator = contact.getFixtureA();
} else {
fixActivator = contact.getFixtureB();
}
}
//collision with a Activator
if(fixActivator!=null){
PlatformActivatorActor platformActivatorActor = (PlatformActivatorActor) fixActivator.getUserData();
if(platformActivatorActor.isActive()){
//if activator is black go to next level
if(platformActivatorActor.color.equals(Color.BLACK)){
game.changeLevel(game.getSecondLevel());
}
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
//get all activator of the same color and change state
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
}else{
//platformActivatorActor.setActive(true);
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
}
}
//jump only if collide with a platform and its not sensor
if(fixPlatform!=null && !fixPlatform.isSensor()){
//only jump if bottom position of pixguy is equal or above of top position of the platform
System.out.println(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX);
System.out.println(fixPlatform.getBody().getPosition().y);
if(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX >fixPlatform.getBody().getPosition().y)
fixGuy.getBody().setLinearVelocity(0, 0);
fixGuy.getBody().applyLinearImpulse(new Vector2(0, 0.1f),
fixGuy.getBody().getWorldCenter(), true);
}
}
@Override
public void endContact(Contact contact) {
// TODO Auto-generated method stub
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
// TODO Auto-generated method stub
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
// TODO Auto-generated method stub
}
});
}
| public void show() {
// TODO Auto-generated method stub
// float w = Gdx.graphics.getWidth();
// float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(PixMindGame.w
* PixMindGame.WORLD_TO_BOX, PixMindGame.h
* PixMindGame.WORLD_TO_BOX);
camera.translate(PixMindGame.w / 2 * PixMindGame.WORLD_TO_BOX,
PixMindGame.h / 2 * PixMindGame.WORLD_TO_BOX);
// Box2d code
world = new World(new Vector2(0, -10), true);
debugRenderer = new Box2DDebugRenderer();
platformList = new ArrayList<StaticPlatformActor>();
activatorList = new ArrayList<PlatformActivatorActor>();
// comment to be commited
//float posX = 2f, posY = 2f, width = 1f, heigth = 0.2f;
StaticPlatform sPlatform = new StaticPlatform(world, 8,5, 1,0.1f);
StaticPlatform s2Platform = new StaticPlatform(world,3, 2,1,0.1f);
StaticPlatform s3Platform = new StaticPlatform(world, 5, 3,1,0.1f);
StaticPlatform s4Platform = new StaticPlatform(world, 6,4,1,0.1f);
StaticPlatform s5Platform = new StaticPlatform(world, 1,1,1,0.1f);
StaticPlatform s6Platform = new StaticPlatform(world, 2,3,1,0.1f);
StaticPlatform s7Platform = new StaticPlatform(world, 1.5f,4,1,0.1f);
//s
PlatformActivator pActivator = new PlatformActivator(world, 0, 5, 0.1f);
PlatformActivator p2Activator = new PlatformActivator(world, 8, 6, 0.1f);
PlatformActivator p3Activator= new PlatformActivator(world, 0, 2, 0.1f);
PlatformActivator p4Activator= new PlatformActivator(world, 2, 5, 0.1f);
StaticPlatformActor s1Skin = new StaticPlatformActor(sPlatform,
Color.RED, false);
StaticPlatformActor s2Skin = new StaticPlatformActor(s2Platform,
Color.BLUE, true);
StaticPlatformActor s3Skin = new StaticPlatformActor(s3Platform,
Color.GREEN, false);
StaticPlatformActor s4Skin = new StaticPlatformActor(s4Platform,
Color.BLACK, true);
StaticPlatformActor s5Skin = new StaticPlatformActor(s5Platform,
Color.RED, false);
StaticPlatformActor s6Skin = new StaticPlatformActor(s6Platform,
Color.BLACK, true);
StaticPlatformActor s7Skin = new StaticPlatformActor(s7Platform,
Color.BLACK, true);
platformList.add(s1Skin);
platformList.add(s2Skin);
platformList.add(s3Skin);
platformList.add(s4Skin);
platformList.add(s5Skin);
platformList.add(s6Skin);
platformList.add(s7Skin);
PlatformActivatorActor a1Skin = new PlatformActivatorActor(pActivator,
Color.RED, false);
PlatformActivatorActor a2Skin = new PlatformActivatorActor(p2Activator,
Color.BLACK, true);
PlatformActivatorActor a3Skin = new PlatformActivatorActor(p3Activator,
Color.GREEN, false);
PlatformActivatorActor a4Skin = new PlatformActivatorActor(p4Activator,
Color.BLUE, true);
activatorList.add(a1Skin);
activatorList.add(a2Skin);
activatorList.add(a3Skin);
activatorList.add(a4Skin);
// main character initialization
pixGuy = new PixGuy(world, 4,4, 0.2f, 0.2f);
stage = new Stage(PixMindGame.w, PixMindGame.h, true);
stageGui = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),
true);
PixGuyController controller = new ArrowController(pixGuy, stageGui);
pixGuy.setController(controller);
pixGuySkin = new PixGuyActor(pixGuy);
stage.addActor(pixGuySkin);
stage.addActor(s1Skin);
stage.addActor(s2Skin);
stage.addActor(s3Skin);
stage.addActor(s4Skin);
stage.addActor(s5Skin);
stage.addActor(s6Skin);
stage.addActor(s7Skin);
stage.addActor(a1Skin);
stage.addActor(a2Skin);
stage.addActor(a3Skin);
stage.addActor(a4Skin);
camera.update();
world.setContactListener(new ContactListener() {
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
Fixture fixGuy= null;
Fixture fixPlatform = null;
Fixture fixActivator = null;
//get fixture fixguy
if (contact.getFixtureA().getUserData().equals(PixGuy.PIX_ID)) {
fixGuy = contact.getFixtureA();
// fixPlatform = contact.getFixtureB();
} else {
// fixPlatform = contact.getFixtureA();
fixGuy = contact.getFixtureB();
}
//get fixture Platform
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor
|| contact.getFixtureB().getUserData()
instanceof StaticPlatformActor ) {
if (contact.getFixtureA().getUserData()
instanceof StaticPlatformActor) {
fixPlatform = contact.getFixtureA();
} else {
fixPlatform = contact.getFixtureB();
}
}
//get fixture PlatformActivator
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor
|| contact.getFixtureB().getUserData()
instanceof PlatformActivatorActor) {
if (contact.getFixtureA().getUserData()
instanceof PlatformActivatorActor) {
fixActivator = contact.getFixtureA();
} else {
fixActivator = contact.getFixtureB();
}
}
//collision with a Activator
if(fixActivator!=null){
PlatformActivatorActor platformActivatorActor = (PlatformActivatorActor) fixActivator.getUserData();
if(platformActivatorActor.isActive()){
//if activator is black go to next level
if(platformActivatorActor.color.equals(Color.BLACK)){
game.changeLevel(game.getSecondLevel());
}
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
//get all activator of the same color and change state
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(false);
}
}else{
//platformActivatorActor.setActive(true);
//get all platform of the same color and change state
for(StaticPlatformActor sp : platformList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
for(PlatformActivatorActor sp : activatorList){
if(platformActivatorActor.color.equals(sp.color))
sp.setActive(true);
}
}
}
//jump only if collide with a platform and its not sensor
if(fixPlatform!=null && !fixPlatform.isSensor()){
//only jump if bottom position of pixguy is equal or above of top position of the platform
System.out.println(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX);
System.out.println(fixPlatform.getBody().getPosition().y);
if(fixGuy.getBody().getPosition().y-PixGuy.pixHeight*PixMindGame.WORLD_TO_BOX >fixPlatform.getBody().getPosition().y)
{
fixGuy.getBody().setLinearVelocity(0, 0);
fixGuy.getBody().applyLinearImpulse(new Vector2(0, 0.1f),
fixGuy.getBody().getWorldCenter(), true);
}
}
}
@Override
public void endContact(Contact contact) {
// TODO Auto-generated method stub
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
// TODO Auto-generated method stub
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
// TODO Auto-generated method stub
}
});
}
|
diff --git a/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/GpFrame.java b/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/GpFrame.java
index 51813a4c..7b6c65eb 100644
--- a/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/GpFrame.java
+++ b/gpswinggui/src/main/java/org/geopublishing/geopublisher/gui/GpFrame.java
@@ -1,951 +1,950 @@
/*******************************************************************************
* Copyright (c) 2010 Stefan A. Tzeggai.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Stefan A. Tzeggai - initial API and implementation
******************************************************************************/
package org.geopublishing.geopublisher.gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.apache.commons.lang.SystemUtils;
import org.apache.log4j.Logger;
import org.geopublishing.atlasViewer.AVProps;
import org.geopublishing.atlasViewer.GpCoreUtil;
import org.geopublishing.atlasViewer.dp.DataPool;
import org.geopublishing.atlasViewer.map.MapPool;
import org.geopublishing.atlasViewer.swing.AtlasViewerGUI;
import org.geopublishing.atlasViewer.swing.Icons;
import org.geopublishing.geopublisher.AtlasConfigEditable;
import org.geopublishing.geopublisher.GPProps;
import org.geopublishing.geopublisher.GPProps.Keys;
import org.geopublishing.geopublisher.GpUtil;
import org.geopublishing.geopublisher.UncacheAtlasAction;
import org.geopublishing.geopublisher.gui.datapool.DataPoolJTable;
import org.geopublishing.geopublisher.gui.datapool.DraggableDatapoolJTable;
import org.geopublishing.geopublisher.gui.group.DnDJTree;
import org.geopublishing.geopublisher.gui.internal.GPDialogManager;
import org.geopublishing.geopublisher.gui.map.DesignMapViewJDialog;
import org.geopublishing.geopublisher.gui.map.MapPoolJTable;
import org.geopublishing.geopublisher.gui.settings.GpOptionsDialog;
import org.geopublishing.geopublisher.swing.GeopublisherGUI;
import org.geopublishing.geopublisher.swing.GeopublisherGUI.ActionCmds;
import org.geopublishing.geopublisher.swing.GpSwingUtil;
import de.schmitzm.i18n.I18NUtil;
import de.schmitzm.i18n.Translation;
import de.schmitzm.io.IOUtil;
import de.schmitzm.swing.ExceptionDialog;
import de.schmitzm.swing.HeapBar;
import de.schmitzm.swing.ResourceProviderManagerFrame;
import de.schmitzm.swing.SwingUtil;
import de.schmitzm.versionnumber.ReleaseUtil;
public class GpFrame extends JFrame {
private static final Logger log = Logger.getLogger(GpFrame.class);
/** A reference to the existing Geopublisher **/
private final GeopublisherGUI gp;
/**
* The heap bar starts a timer that updates it automatically. Hence we just
* want one instance of it, otherwise there would be many threads.
**/
protected HeapBar singleHeapBar;
/** A reference to the {@link GpJSplitPane} **/
private volatile GpJSplitPane gsSplitPane;
/** The status bar displayed at the bottom of the frame **/
private GpStatusBar statusBar;
/**
* Just a convenience method to access Geopublisher translation
*/
private String R(String key, Object... values) {
return GeopublisherGUI.R(key, values);
}
/**
* A listener to exchange all components on language change.
*/
PropertyChangeListener repaintGuiListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Close all open MapComposer instances.
GPDialogManager.dm_MapComposer.forceCloseAllInstances();
updateAce();
/**
* Trigger a repaint of all components
*/
repaint(1000);
}
});
}
};
private JCheckBoxMenuItem rasterCheckBoxMenuItem;
public AtlasConfigEditable getAce() {
return gp.getAce();
}
public GpFrame(final GeopublisherGUI gp) {
this.gp = gp;
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (gp.closeAtlas(null)) {
gp.exitGP(0);
}
}
});
// React to changes of the locale
Translation.addActiveLangChangeListener(repaintGuiListener);
// React to changes of atlas language changes
Translation.addLocaleChangeListener(repaintGuiListener);
setTitle(R("ApplicationMainWindowTitle",
ReleaseUtil.getVersionInfo(GpUtil.class)));
setSize(new Dimension(GPProps.getInt(GPProps.Keys.gpWindowWidth, 750),
GPProps.getInt(GPProps.Keys.gpWindowHeight, 510)));
Boolean newStart = GPProps.get(GPProps.Keys.gpWindowWidth) == null;
if (newStart) {
SwingUtil.centerFrameOnScreen(this);
} else {
SwingUtil.centerFrameOnScreen(this);
}
// MMaximize the JFrame, depending on the last saved state.
setExtendedState(GPProps.getInt(GPProps.Keys.windowMaximized, 0));
// Setting the GP icons for this frame
try {
final List<Image> icons = new ArrayList<Image>(3);
icons.add(new ImageIcon(Icons.class
.getResource("/icons/gp_icon16.png")).getImage());
icons.add(new ImageIcon(Icons.class
.getResource("/icons/gp_icon32.png")).getImage());
icons.add(new ImageIcon(Icons.class
.getResource("/icons/gp_icon64.png")).getImage());
setIconImages(icons);
} catch (Exception e) {
ExceptionDialog.show(this, e);
}
updateAce();
setVisible(true);
}
/**
* This method initializes the jJMenuBar. No MenuItem is cached. All are
* recreated when this method is called. This {@link JMenu} is dependent a
* lot on the {@link #gp.getAce()}
*
* @return a fresh javax.swing.JMenuBar
*/
protected JMenuBar createMenuBar() {
AtlasConfigEditable ace = gp.getAce();
if (ace == null) {
setTitle(R("ApplicationMainWindowTitle",
ReleaseUtil.getVersionInfo(GpUtil.class)));
} else {
setTitle(R("ApplicationMainWindowTitle_with_open_atlas",
ReleaseUtil.getVersionInfo(GpUtil.class), ace.getTitle()
.toString()));
}
JMenuBar jMenuBar = new JMenuBar();
jMenuBar.add(getFileMenu());
jMenuBar.add(getAtlasMenu());
jMenuBar.add(getOptionsMenu());
jMenuBar.invalidate();
return jMenuBar;
}
/**
* This {@link JMenu} allows to load, save and create an atlas. Plus the
* exit button.
*/
private JMenu getFileMenu() {
JMenuItem menuItem;
final AtlasConfigEditable ace = gp.getAce();
JMenu fileMenu = new JMenu(R("MenuBar.FileMenu"));
// ******************************************************************
// "New Atlas" Menu Item - newAtlasMenuItem
// ******************************************************************
JMenuItem newAtlasMenuItem = new JMenuItem(R("MenuBar.FileMenu.New"));
newAtlasMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
Event.CTRL_MASK, true));
newAtlasMenuItem.addActionListener(gp);
newAtlasMenuItem.setActionCommand(ActionCmds.newAtlas.toString());
newAtlasMenuItem.setEnabled(ace == null);
fileMenu.add(newAtlasMenuItem);
// ******************************************************************
// "Load Atlas" Menu Item - loadAtlasMenuItem
// ******************************************************************
JMenuItem loadAtlasMenuItem = new JMenuItem(new AbstractAction(
R("MenuBar.FileMenu.Load")) {
@Override
public void actionPerformed(ActionEvent e) {
gp.loadAtlas();
}
});
loadAtlasMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3,
0, true));
loadAtlasMenuItem.setEnabled(ace == null);
fileMenu.add(loadAtlasMenuItem);
// ******************************************************************
// "Close Atlas" Menu Item
// ******************************************************************
JMenuItem closeAtlasMenuItem = new JMenuItem(new AbstractAction(
R("MenuBar.FileMenu.Close")) {
@Override
public void actionPerformed(ActionEvent e) {
gp.closeAtlas(null);
}
});
closeAtlasMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
InputEvent.CTRL_DOWN_MASK, true));
closeAtlasMenuItem.setEnabled(ace != null);
fileMenu.add(closeAtlasMenuItem);
// ******************************************************************
// "Save Atlas" Menu Item - saveAtlasMenuItem
// ******************************************************************
if (ace != null) {
JMenuItem saveAtlasMenuItem = new JMenuItem(
R("MenuBar.FileMenu.Save"));
saveAtlasMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK, true));
saveAtlasMenuItem.setActionCommand(ActionCmds.saveAtlas.toString());
saveAtlasMenuItem.addActionListener(gp);
fileMenu.add(saveAtlasMenuItem);
}
// ******************************************************************
// "Import data into the atlas using a wizard
// ******************************************************************
if (ace != null) {
fileMenu.add(new GpMenuItem(R("MenuBar.FileMenu.ImportWizard"),
null, ActionCmds.importWizard, null, KeyStroke
.getKeyStroke(KeyEvent.VK_I, Event.CTRL_MASK, true)));
}
// ******************************************************************
// "Export Atlas as JARs" Menu Item - exportJarsMenuItem
// ******************************************************************
if (ace != null) {
fileMenu.add(new GpMenuItem(R("MenuBar.FileMenu.Export"), null,
ActionCmds.exportJarsAtlas, null, KeyStroke.getKeyStroke(
KeyEvent.VK_E, Event.CTRL_MASK, true)));
}
// ******************************************************************
// "Test atlas without creating JARs" Menu Item - testAVMenuItem
// ******************************************************************
if (ace != null) {
ImageIcon previewIcon = new ImageIcon(
GPProps.class.getResource("/icons/testRun.png"));
fileMenu.add(new GpMenuItem(R("MenuBar.FileMenu.Preview"),
R("MenuBar.FileMenu.Preview.TT"), ActionCmds.previewAtlas,
previewIcon, KeyStroke.getKeyStroke(KeyEvent.VK_F5,
KeyEvent.SHIFT_MASK, true)));
fileMenu.add(new GpMenuItem(R("MenuBar.FileMenu.LivePreview"),
R("MenuBar.FileMenu.LivePreview.TT"),
ActionCmds.previewAtlasLive, previewIcon, KeyStroke
.getKeyStroke(KeyEvent.VK_F5, 0, true)));
}
/**
* Show a link to load the last loaded atlas if one is stored
*/
if (GPProps.get(Keys.LastOpenAtlasFolder) != null) {
final File lastAtalsFolder = new File(
GPProps.get(Keys.LastOpenAtlasFolder));
if (lastAtalsFolder.exists()
&& AtlasConfigEditable.isAtlasDir(lastAtalsFolder)) {
fileMenu.add(new JSeparator());
fileMenu.add(new AbstractAction(lastAtalsFolder
.getAbsolutePath()) {
@Override
public void actionPerformed(ActionEvent arg0) {
gp.loadAtlasFromDir(lastAtalsFolder);
}
});
}
}
// ******************************************************************
// "Exit" Menu Item - exitMenuItem
// ******************************************************************
fileMenu.add(new JSeparator()); // SEPARATOR
menuItem = new GpMenuItem(
GpCoreUtil
.R("AtlasViewer.FileMenu.ExitMenuItem.exit_application"),
null, ActionCmds.exitGP, Icons.ICON_EXIT_SMALL);
fileMenu.add(menuItem);
return fileMenu;
}
/**
* @return the {@link DraggableDatapoolJTable} that represents the
* {@link DataPool}
*/
public DataPoolJTable getDatapoolJTable() {
return getGpSplitPane().getDatapoolJTable();
}
/**
* @return the {@link MapPoolJTable} that represents the {@link MapPool}
*/
public MapPoolJTable getMappoolJTable() {
return getGpSplitPane().getMappoolJTable();
}
public DnDJTree getGroupJTree() {
return getGpSplitPane().getGroupJTable();
}
/**
* Will recreate the {@link JMenuBar} of this {@link JFrame}. Should be
* called after an {@link AtlasConfigEditable} has been loaded, closed or
* any language changes.
*/
public void updateMenu() {
JMenuBar mBar = createMenuBar();
setJMenuBar(mBar);
// Helps against the problem, that the menu bar is sometimes not
// clickable
validate();
repaint();
}
/**
* Will make the needed changes when another atlas has been loaded, closed
* or created. This will also automatically update the {@link JMenuBar}.<br/>
* When calling this method, we expect that the gp.getAce() contains the
* {@link AtlasConfigEditable} that should be displayed.
*/
public void updateAce() {
JPanel contentPane = new JPanel(new BorderLayout());
// need a new menu, a new splitpane and a new status bar
if (gsSplitPane != null)
gsSplitPane.dispose();
gsSplitPane = null;
statusBar = null;
contentPane.add(getGpSplitPane(), BorderLayout.CENTER);
contentPane.add(getGpStatusBar(), BorderLayout.SOUTH);
setContentPane(contentPane);
updateMenu();
validate();
}
/**
* @return a single instance of the {@link HeapBar}
*/
public HeapBar getHeapBar() {
if (singleHeapBar == null)
singleHeapBar = new HeapBar();
return singleHeapBar;
}
public GpStatusBar getGpStatusBar() {
if (statusBar == null) {
statusBar = new GpStatusBar(this);
}
return statusBar;
}
public GpJSplitPane getGpSplitPane() {
if (gsSplitPane == null) {
gsSplitPane = new GpJSplitPane(gp.getAce());
}
return gsSplitPane;
}
/**
* Saves the dimensions of the main frame and the state of the internal
* split pane to a .properties file.
*/
public void saveWindowPosition() {
// Remember the State of the Windows
GPProps.set(GPProps.Keys.windowMaximized, getExtendedState());
GPProps.set(GPProps.Keys.gpWindowWidth, getSize().width);
GPProps.set(GPProps.Keys.gpWindowHeight, getSize().height);
if (getContentPane() instanceof GpJSplitPane) {
// getContentPane() is a JPanel until an atlas is loaded.
GpJSplitPane gpSplit = (GpJSplitPane) getContentPane();
GPProps.set(GPProps.Keys.gpWindowLeftDividerLocation,
gpSplit.getLeftDividerLocation());
GPProps.set(GPProps.Keys.gpWindowRightDividerLocation,
gpSplit.getRightDividerLocation());
}
GPProps.store();
}
/**
* Creates the options menu. It contains general settings that are not
* directly related to the loaded atlas.
*/
private JMenu getOptionsMenu() {
final AtlasConfigEditable ace = gp.getAce();
JMenu optionsMenu = new JMenu(R("MenuBar.OptionsMenu"));
- final JMenuItem optionsMenuItem = new JMenuItem(new AbstractAction(
- "Einstellungen") {
+ final JMenuItem optionsMenuItem = new JMenuItem(new AbstractAction(R("GpOptionsDialog.title")) {
@Override
public void actionPerformed(ActionEvent arg0) {
new GpOptionsDialog(GpFrame.this, GeopublisherGUI.getInstance());
}
});
optionsMenu.add(optionsMenuItem);
if (ace != null) {
// Option to re-read all the information that is NOT stored in the
// atlas.xml, but in the ad/ folders.
final JMenuItem uncacheMenuItem = new JMenuItem(
new UncacheAtlasAction(this, ace));
uncacheMenuItem
.setToolTipText(R("MenuBar.OptionsMenu.ClearCaches.tt"));
uncacheMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, Event.CTRL_MASK, true));
optionsMenu.add(uncacheMenuItem);
}
// OLD CODE TO SWITCH THE RENDERER
//
// final JCheckBoxMenuItem rendererSwitchCheckBox = new
// JCheckBoxMenuItem();
// rendererSwitchCheckBox.setAction(new AbstractAction(
// "use ShapefileRenderer") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// GTUtil
// .setGTRendererType(rendererSwitchCheckBox.isSelected() ?
// GTRendererType.ShapefileRenderer
// : GTRendererType.StreamingRenderer);
// }
// });
// optionsMenu.add(rendererSwitchCheckBox);
// rendererSwitchCheckBox.setSelected(true);
// ******************************************************************
// Switch Atlas Translations language
// ******************************************************************
if (ace != null && ace.getLanguages().size() > 1)
optionsMenu.add(getChangeAtlasLangJMenu());
// ******************************************************************
// Switch Geopublisher GUI language
// ******************************************************************
optionsMenu.add(getChangeGpLangJMenu());
/**
* The MenuItem Language to create a new language
*/
JMenuItem manageLanguageJMenuitem = new JMenuItem(new AbstractAction(
GpSwingUtil.R("MenuBar.OptionsMenu.TranslateSoftware"),
Icons.ICON_FLAGS_SMALL) {
@Override
public void actionPerformed(ActionEvent e) {
String resPath = IOUtil.escapePath(System
.getProperty("user.home")
+ File.separator
+ ".Geopublishing");
ResourceProviderManagerFrame manLanguagesFrame = new ResourceProviderManagerFrame(
GpFrame.this, true, GpSwingUtil.R(
"TranslateSoftwareDialog.Explanation.Html",
R("MenuBar.AtlasMenu"),
R("MenuBar.AtlasMenu.ChangeLanguages"),
resPath, SystemUtils.IS_OS_WINDOWS ? "bat"
: "sh"));
manLanguagesFrame.setRootPath(new File(resPath));
manLanguagesFrame.setTitle(GpSwingUtil
.R("TranslateSoftwareDialog.Title"));
manLanguagesFrame.setPreferredSize(new Dimension(780, 450));
manLanguagesFrame.setVisible(true);
}
});
manageLanguageJMenuitem.setToolTipText(GpSwingUtil
.R("MenuBar.OptionsMenu.TranslateSoftware.TT"));
optionsMenu.add(manageLanguageJMenuitem);
// ******************************************************************
// Set rendering for the Geopublisher application
// ******************************************************************
JCheckBoxMenuItem jCheckBoxMenuItemAntiAliasingAC = new JCheckBoxMenuItem(
new AbstractAction(
R("MenuBar.OptionsMenu.Checkbox.QualityRenderingGP")) {
@Override
public void actionPerformed(ActionEvent e) {
boolean useAntiAliase = ((JCheckBoxMenuItem) e
.getSource()).isSelected();
GPProps.set(GPProps.Keys.antialiasingMaps,
useAntiAliase ? "1" : "0");
// Update all open DesignMapViewialogs
DesignMapViewJDialog.setAntiAliasing(useAntiAliase);
}
});
jCheckBoxMenuItemAntiAliasingAC.setSelected(GPProps.getInt(
GPProps.Keys.antialiasingMaps, 1) == 1);
optionsMenu.add(jCheckBoxMenuItemAntiAliasingAC);
// // ******************************************************************
// // Send logfiles to author by email
// // ******************************************************************
// JMenuItem jMenuItemShowlog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.OpenLogFile")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
//
// /**
// * Stefan Tzeggai 25th Sep 2010 Some real ugly stuff: On Windows
// * 7 the line <param name="File"
// * value="${java.io.tmpdir}/geopublisher.log" /> from
// * gp_log4j.xml resolves to "C:\tmp", but during program
// * execution it resolves to "C:\ Users\ username\ AppData\
// * Local\ Temp"
// */
//
// try {
// File logFile = new File(IOUtil.getTempDir(),
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
// try {
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// }
// } catch (Exception ee) {
// try {
//
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp" : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
//
// try {
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp"
// : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// } catch (Exception eee) {
// ExceptionDialog.show(GpFrame.this, eee);
// }
// }
//
// }
// }
//
// });
// optionsMenu.add(jMenuItemShowlog);
/**
* Allow to switch LookAndFeel
*/
if (UIManager.getInstalledLookAndFeels().length > 1)
optionsMenu.add(getLnFJMenu());
/**
* Manage logging
*/
{
JMenu logMenu = SwingUtil.createChangeLog4JLevelJMenu();
optionsMenu.add(logMenu);
// ******************************************************************
// Send logfiles to author by email
// //
// ******************************************************************
// JMenuItem jMenuItemSendLog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.SendLogToAuthor")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// BugReportmailer bugReport = new GPBugReportmailer();
// bugReport.send(GpFrame.this);
// }
//
// });
// logMenu.add(jMenuItemSendLog);
}
// // TODO unschön, Switch raster Renderers for testing
// {
// rasterCheckBoxMenuItem = new JCheckBoxMenuItem(new AbstractAction(
// "Use new reader for raster") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// boolean oldValue = GPProps
// .getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true);
//
// boolean newValue = !oldValue;
// GPProps.set(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// newValue);
// rasterCheckBoxMenuItem.setSelected(newValue);
// }
// });
// rasterCheckBoxMenuItem.setSelected((GPProps.getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true)));
// optionsMenu.add(rasterCheckBoxMenuItem);
// }
/**
* Manage ASCII Reader
*/
return optionsMenu;
}
private JMenuItem getLnFJMenu() {
JMenu lnfJMenu = new JMenu(R("MenuBar.OptionsMenu.ChangeLookAndFeel"));
/** the look and feels available in the system */
for (UIManager.LookAndFeelInfo lnf : UIManager
.getInstalledLookAndFeels()) {
if (UIManager.getLookAndFeel().getName().equals(lnf.getName())) {
continue;
}
JMenuItem oneLnFJmenuItem = new JMenuItem(lnf.getName());
oneLnFJmenuItem.setActionCommand(ActionCmds.changeLnF.toString()
+ lnf.getClassName());
oneLnFJmenuItem.addActionListener(gp);
lnfJMenu.add(oneLnFJmenuItem);
}
return lnfJMenu;
}
/**
* Creates a {@link JMenu} languageSubMenu that allows changing the language
* the atlas data is displayed in. <br/>
* Attention, not to replace the object in the {@link JMenu} structure Call
* this after changes to atlasConfig.languages.
*
* @author <a href="mailto:skpublic@wikisquare.de">Stefan Alfons Tzeggai</a>
*
* Note: This method is double in {@link AtlasViewerGUI} and
* {@link GeopublisherGUI}
*/
private JMenu getChangeAtlasLangJMenu() {
SwingUtil.checkOnEDT();
AtlasConfigEditable ace = gp.getAce();
JMenu languageSubMenu = new JMenu(
GpCoreUtil
.R("AtlasViewer.FileMenu.LanguageSubMenu.change_language"));
languageSubMenu.setToolTipText(GpCoreUtil
.R("AtlasViewer.FileMenu.LanguageSubMenu.change_language_tt"));
languageSubMenu.setIcon(Icons.ICON_FLAGS_SMALL);
for (String code : ace.getLanguages()) {
// Not show the option to switch to actual language...
if (code.equals(Translation.getActiveLang()))
continue;
/**
* Lookup a country where they speak the language, so we can print
* the language in local tounge.
*/
JMenuItem langMenuItem = new JMenuItem(new AbstractAction(
I18NUtil.getMultilanguageString(code)) {
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
Translation.setActiveLang(actionCommand, false);
}
});
langMenuItem.setActionCommand(code);
languageSubMenu.add(langMenuItem);
}
return languageSubMenu;
}
/**
* Creates a {@link JMenu} languageSubMenu that allows changing the language
* the atlas data is displayed in. <br/>
* Attention, not to replace the object in the {@link JMenu} structure Call
* this after changes to atlasConfig.languages.
*
* @author <a href="mailto:skpublic@wikisquare.de">Stefan Alfons Tzeggai</a>
*
* Note: This method is double in {@link AtlasViewerGUI} and
* {@link GeopublisherGUI}
*/
private JMenu getChangeGpLangJMenu() {
SwingUtil.checkOnEDT();
JMenu languageSubMenu = new JMenu(
GpUtil.R("MenuBar.OptionsMenu.change_gp_language"));
languageSubMenu.setToolTipText(GpUtil
.R("MenuBar.OptionsMenu.change_gp_language.tt"));
languageSubMenu.setIcon(Icons.ICON_FLAGS_SMALL);
for (Locale locale : GpUtil.getAvailableLocales()) {
// Not show the option to switch to actual GUI language...
if (locale.getLanguage().equals(Locale.getDefault()))
continue;
JMenuItem langMenuItem = new JMenuItem(
new AbstractAction(I18NUtil.getMultilanguageString(locale
.getDisplayLanguage())) {
public void actionPerformed(ActionEvent e) {
String langCode = e.getActionCommand();
Locale.setDefault(new Locale(langCode));
Translation.fireLocaleChangeEvents();
}
});
langMenuItem.setActionCommand(locale.getLanguage());
languageSubMenu.add(langMenuItem);
}
return languageSubMenu;
}
/**
* This {@link JMenu} contains {@link MenuItem}s that configure the loaded
* atlas. The menu is disabled if no atlas is loaded.
*/
private JMenu getAtlasMenu() {
JMenu atlasJMenu = new JMenu(R("MenuBar.AtlasMenu"));
final AtlasConfigEditable ace = gp.getAce();
if (ace == null) {
atlasJMenu.setEnabled(false);
} else {
atlasJMenu.add(new GpMenuItem(
R("MenuBar.AtlasMenu.ChangeAtlasParams"),
ActionCmds.editAtlasParams));
atlasJMenu.add(new GpMenuItem(
R("MenuBar.AtlasMenu.PersonalizeImages"),
ActionCmds.showImagesInfo));
atlasJMenu.add(new GpMenuItem(R("MenuBar.AtlasMenu.EditPopupInfo"),
ActionCmds.editPopupInfo));
atlasJMenu.add(new GpMenuItem(R("MenuBar.AtlasMenu.EditAboutInfo"),
ActionCmds.editAboutInfo));
// ******************************************************************
// Set rendering quality for the atlas-product
// ******************************************************************
JCheckBoxMenuItem jCheckBoxMenuItemAntiAliasingAV = new JCheckBoxMenuItem(
new AbstractAction(
R("MenuBar.AtlasMenu.Checkbox.QualityRenderingAV")) {
@Override
public void actionPerformed(ActionEvent e) {
boolean b = ((JCheckBoxMenuItem) e.getSource())
.isSelected();
getAce().getProperties().set(GpFrame.this,
AVProps.Keys.antialiasingMaps,
b ? "1" : "0");
}
});
jCheckBoxMenuItemAntiAliasingAV
.setSelected(getAce().getProperties().getInt(
AVProps.Keys.antialiasingMaps, 1) == 1);
atlasJMenu.add(jCheckBoxMenuItemAntiAliasingAV);
atlasJMenu.add(new GpMenuItem(
R("MenuBar.AtlasMenu.ChangeLanguages"),
ActionCmds.editAtlasLanguages, Icons.ICON_FLAGS_SMALL));
atlasJMenu.add(new GpMenuItem(
R("MenuBar.AtlasMenu.PrintTranslations"),
ActionCmds.exportAtlasTranslations));
// Export the data pool as CSV
atlasJMenu.add(new JMenuItem(new GPExportCSVAction(
R("MenuBar.AtlasMenu.ExportCSV"), ace, GpFrame.this)));
/**
* A an item to change the default CRS used in the atlas
*/
JMenuItem jMenuItemDefaultCRS = new JMenuItem(new AbstractAction(
R("MenuBar.OptionsMenu.SetDefaultCRS"),
DefaultCRSSelectionJDialog.defaultCRSIcon) {
@Override
public void actionPerformed(ActionEvent e) {
// TODO should implement {@link CancellableDialogAdapter}
DefaultCRSSelectionJDialog defaultCRSSelectionJDialog = new DefaultCRSSelectionJDialog(
GpFrame.this, ace);
defaultCRSSelectionJDialog.setModal(true);
defaultCRSSelectionJDialog.setVisible(true);
}
});
atlasJMenu.add(jMenuItemDefaultCRS);
atlasJMenu.add(new JMenuItem(new GpConfigureAtlasFontsAction(
R("MenuBar.AtlasMenu.ManageFonts"), ace, GpFrame.this)));
}
return atlasJMenu;
}
/**
* Extension of {@link JMenuItem} that automatically set's the
* {@link GeopublisherGUI} instance as the {@link ActionListener}
*/
class GpMenuItem extends JMenuItem {
public GpMenuItem(final String label, final ImageIcon imageIcon,
final ActionCmds actionCmd, final KeyStroke keyStroke) {
this(label, null, actionCmd, null, null);
}
public GpMenuItem(final String label, final String tooltip,
final ActionCmds actionCmd, final ImageIcon iconFlagsSmall,
final KeyStroke keyStroke) {
super(label);
if (tooltip != null && !tooltip.isEmpty())
setToolTipText(tooltip);
setActionCommand(actionCmd.toString());
addActionListener(gp);
if (iconFlagsSmall != null)
setIcon(iconFlagsSmall);
if (keyStroke != null) {
setAccelerator(keyStroke);
}
}
public GpMenuItem(final String label, final String tooltip,
final ActionCmds actionCmd, final ImageIcon icon) {
this(label, tooltip, actionCmd, icon, null);
}
public GpMenuItem(final String label, final ActionCmds cmd,
final ImageIcon icon) {
this(label, null, cmd, icon);
}
public GpMenuItem(final String label, final ActionCmds cmd) {
this(label, cmd, null);
}
}
}
| true | true | private JMenu getOptionsMenu() {
final AtlasConfigEditable ace = gp.getAce();
JMenu optionsMenu = new JMenu(R("MenuBar.OptionsMenu"));
final JMenuItem optionsMenuItem = new JMenuItem(new AbstractAction(
"Einstellungen") {
@Override
public void actionPerformed(ActionEvent arg0) {
new GpOptionsDialog(GpFrame.this, GeopublisherGUI.getInstance());
}
});
optionsMenu.add(optionsMenuItem);
if (ace != null) {
// Option to re-read all the information that is NOT stored in the
// atlas.xml, but in the ad/ folders.
final JMenuItem uncacheMenuItem = new JMenuItem(
new UncacheAtlasAction(this, ace));
uncacheMenuItem
.setToolTipText(R("MenuBar.OptionsMenu.ClearCaches.tt"));
uncacheMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, Event.CTRL_MASK, true));
optionsMenu.add(uncacheMenuItem);
}
// OLD CODE TO SWITCH THE RENDERER
//
// final JCheckBoxMenuItem rendererSwitchCheckBox = new
// JCheckBoxMenuItem();
// rendererSwitchCheckBox.setAction(new AbstractAction(
// "use ShapefileRenderer") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// GTUtil
// .setGTRendererType(rendererSwitchCheckBox.isSelected() ?
// GTRendererType.ShapefileRenderer
// : GTRendererType.StreamingRenderer);
// }
// });
// optionsMenu.add(rendererSwitchCheckBox);
// rendererSwitchCheckBox.setSelected(true);
// ******************************************************************
// Switch Atlas Translations language
// ******************************************************************
if (ace != null && ace.getLanguages().size() > 1)
optionsMenu.add(getChangeAtlasLangJMenu());
// ******************************************************************
// Switch Geopublisher GUI language
// ******************************************************************
optionsMenu.add(getChangeGpLangJMenu());
/**
* The MenuItem Language to create a new language
*/
JMenuItem manageLanguageJMenuitem = new JMenuItem(new AbstractAction(
GpSwingUtil.R("MenuBar.OptionsMenu.TranslateSoftware"),
Icons.ICON_FLAGS_SMALL) {
@Override
public void actionPerformed(ActionEvent e) {
String resPath = IOUtil.escapePath(System
.getProperty("user.home")
+ File.separator
+ ".Geopublishing");
ResourceProviderManagerFrame manLanguagesFrame = new ResourceProviderManagerFrame(
GpFrame.this, true, GpSwingUtil.R(
"TranslateSoftwareDialog.Explanation.Html",
R("MenuBar.AtlasMenu"),
R("MenuBar.AtlasMenu.ChangeLanguages"),
resPath, SystemUtils.IS_OS_WINDOWS ? "bat"
: "sh"));
manLanguagesFrame.setRootPath(new File(resPath));
manLanguagesFrame.setTitle(GpSwingUtil
.R("TranslateSoftwareDialog.Title"));
manLanguagesFrame.setPreferredSize(new Dimension(780, 450));
manLanguagesFrame.setVisible(true);
}
});
manageLanguageJMenuitem.setToolTipText(GpSwingUtil
.R("MenuBar.OptionsMenu.TranslateSoftware.TT"));
optionsMenu.add(manageLanguageJMenuitem);
// ******************************************************************
// Set rendering for the Geopublisher application
// ******************************************************************
JCheckBoxMenuItem jCheckBoxMenuItemAntiAliasingAC = new JCheckBoxMenuItem(
new AbstractAction(
R("MenuBar.OptionsMenu.Checkbox.QualityRenderingGP")) {
@Override
public void actionPerformed(ActionEvent e) {
boolean useAntiAliase = ((JCheckBoxMenuItem) e
.getSource()).isSelected();
GPProps.set(GPProps.Keys.antialiasingMaps,
useAntiAliase ? "1" : "0");
// Update all open DesignMapViewialogs
DesignMapViewJDialog.setAntiAliasing(useAntiAliase);
}
});
jCheckBoxMenuItemAntiAliasingAC.setSelected(GPProps.getInt(
GPProps.Keys.antialiasingMaps, 1) == 1);
optionsMenu.add(jCheckBoxMenuItemAntiAliasingAC);
// // ******************************************************************
// // Send logfiles to author by email
// // ******************************************************************
// JMenuItem jMenuItemShowlog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.OpenLogFile")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
//
// /**
// * Stefan Tzeggai 25th Sep 2010 Some real ugly stuff: On Windows
// * 7 the line <param name="File"
// * value="${java.io.tmpdir}/geopublisher.log" /> from
// * gp_log4j.xml resolves to "C:\tmp", but during program
// * execution it resolves to "C:\ Users\ username\ AppData\
// * Local\ Temp"
// */
//
// try {
// File logFile = new File(IOUtil.getTempDir(),
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
// try {
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// }
// } catch (Exception ee) {
// try {
//
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp" : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
//
// try {
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp"
// : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// } catch (Exception eee) {
// ExceptionDialog.show(GpFrame.this, eee);
// }
// }
//
// }
// }
//
// });
// optionsMenu.add(jMenuItemShowlog);
/**
* Allow to switch LookAndFeel
*/
if (UIManager.getInstalledLookAndFeels().length > 1)
optionsMenu.add(getLnFJMenu());
/**
* Manage logging
*/
{
JMenu logMenu = SwingUtil.createChangeLog4JLevelJMenu();
optionsMenu.add(logMenu);
// ******************************************************************
// Send logfiles to author by email
// //
// ******************************************************************
// JMenuItem jMenuItemSendLog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.SendLogToAuthor")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// BugReportmailer bugReport = new GPBugReportmailer();
// bugReport.send(GpFrame.this);
// }
//
// });
// logMenu.add(jMenuItemSendLog);
}
// // TODO unschön, Switch raster Renderers for testing
// {
// rasterCheckBoxMenuItem = new JCheckBoxMenuItem(new AbstractAction(
// "Use new reader for raster") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// boolean oldValue = GPProps
// .getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true);
//
// boolean newValue = !oldValue;
// GPProps.set(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// newValue);
// rasterCheckBoxMenuItem.setSelected(newValue);
// }
// });
// rasterCheckBoxMenuItem.setSelected((GPProps.getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true)));
// optionsMenu.add(rasterCheckBoxMenuItem);
// }
/**
* Manage ASCII Reader
*/
return optionsMenu;
}
| private JMenu getOptionsMenu() {
final AtlasConfigEditable ace = gp.getAce();
JMenu optionsMenu = new JMenu(R("MenuBar.OptionsMenu"));
final JMenuItem optionsMenuItem = new JMenuItem(new AbstractAction(R("GpOptionsDialog.title")) {
@Override
public void actionPerformed(ActionEvent arg0) {
new GpOptionsDialog(GpFrame.this, GeopublisherGUI.getInstance());
}
});
optionsMenu.add(optionsMenuItem);
if (ace != null) {
// Option to re-read all the information that is NOT stored in the
// atlas.xml, but in the ad/ folders.
final JMenuItem uncacheMenuItem = new JMenuItem(
new UncacheAtlasAction(this, ace));
uncacheMenuItem
.setToolTipText(R("MenuBar.OptionsMenu.ClearCaches.tt"));
uncacheMenuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_R, Event.CTRL_MASK, true));
optionsMenu.add(uncacheMenuItem);
}
// OLD CODE TO SWITCH THE RENDERER
//
// final JCheckBoxMenuItem rendererSwitchCheckBox = new
// JCheckBoxMenuItem();
// rendererSwitchCheckBox.setAction(new AbstractAction(
// "use ShapefileRenderer") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// GTUtil
// .setGTRendererType(rendererSwitchCheckBox.isSelected() ?
// GTRendererType.ShapefileRenderer
// : GTRendererType.StreamingRenderer);
// }
// });
// optionsMenu.add(rendererSwitchCheckBox);
// rendererSwitchCheckBox.setSelected(true);
// ******************************************************************
// Switch Atlas Translations language
// ******************************************************************
if (ace != null && ace.getLanguages().size() > 1)
optionsMenu.add(getChangeAtlasLangJMenu());
// ******************************************************************
// Switch Geopublisher GUI language
// ******************************************************************
optionsMenu.add(getChangeGpLangJMenu());
/**
* The MenuItem Language to create a new language
*/
JMenuItem manageLanguageJMenuitem = new JMenuItem(new AbstractAction(
GpSwingUtil.R("MenuBar.OptionsMenu.TranslateSoftware"),
Icons.ICON_FLAGS_SMALL) {
@Override
public void actionPerformed(ActionEvent e) {
String resPath = IOUtil.escapePath(System
.getProperty("user.home")
+ File.separator
+ ".Geopublishing");
ResourceProviderManagerFrame manLanguagesFrame = new ResourceProviderManagerFrame(
GpFrame.this, true, GpSwingUtil.R(
"TranslateSoftwareDialog.Explanation.Html",
R("MenuBar.AtlasMenu"),
R("MenuBar.AtlasMenu.ChangeLanguages"),
resPath, SystemUtils.IS_OS_WINDOWS ? "bat"
: "sh"));
manLanguagesFrame.setRootPath(new File(resPath));
manLanguagesFrame.setTitle(GpSwingUtil
.R("TranslateSoftwareDialog.Title"));
manLanguagesFrame.setPreferredSize(new Dimension(780, 450));
manLanguagesFrame.setVisible(true);
}
});
manageLanguageJMenuitem.setToolTipText(GpSwingUtil
.R("MenuBar.OptionsMenu.TranslateSoftware.TT"));
optionsMenu.add(manageLanguageJMenuitem);
// ******************************************************************
// Set rendering for the Geopublisher application
// ******************************************************************
JCheckBoxMenuItem jCheckBoxMenuItemAntiAliasingAC = new JCheckBoxMenuItem(
new AbstractAction(
R("MenuBar.OptionsMenu.Checkbox.QualityRenderingGP")) {
@Override
public void actionPerformed(ActionEvent e) {
boolean useAntiAliase = ((JCheckBoxMenuItem) e
.getSource()).isSelected();
GPProps.set(GPProps.Keys.antialiasingMaps,
useAntiAliase ? "1" : "0");
// Update all open DesignMapViewialogs
DesignMapViewJDialog.setAntiAliasing(useAntiAliase);
}
});
jCheckBoxMenuItemAntiAliasingAC.setSelected(GPProps.getInt(
GPProps.Keys.antialiasingMaps, 1) == 1);
optionsMenu.add(jCheckBoxMenuItemAntiAliasingAC);
// // ******************************************************************
// // Send logfiles to author by email
// // ******************************************************************
// JMenuItem jMenuItemShowlog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.OpenLogFile")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
//
// /**
// * Stefan Tzeggai 25th Sep 2010 Some real ugly stuff: On Windows
// * 7 the line <param name="File"
// * value="${java.io.tmpdir}/geopublisher.log" /> from
// * gp_log4j.xml resolves to "C:\tmp", but during program
// * execution it resolves to "C:\ Users\ username\ AppData\
// * Local\ Temp"
// */
//
// try {
// File logFile = new File(IOUtil.getTempDir(),
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
// try {
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// }
// } catch (Exception ee) {
// try {
//
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp" : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().edit(logFile);
// } catch (Exception usoe) {
//
// try {
// File logFile = new File(
// SystemUtils.IS_OS_WINDOWS ? "C:\\tmp"
// : "/tmp",
// GPBugReportmailer.GEOPUBLISHERLOG)
// .getCanonicalFile();
//
// Desktop.getDesktop().browse(
// DataUtilities.fileToURL(logFile).toURI());
// } catch (Exception eee) {
// ExceptionDialog.show(GpFrame.this, eee);
// }
// }
//
// }
// }
//
// });
// optionsMenu.add(jMenuItemShowlog);
/**
* Allow to switch LookAndFeel
*/
if (UIManager.getInstalledLookAndFeels().length > 1)
optionsMenu.add(getLnFJMenu());
/**
* Manage logging
*/
{
JMenu logMenu = SwingUtil.createChangeLog4JLevelJMenu();
optionsMenu.add(logMenu);
// ******************************************************************
// Send logfiles to author by email
// //
// ******************************************************************
// JMenuItem jMenuItemSendLog = new JMenuItem(new AbstractAction(
// R("MenuBar.OptionsMenu.SendLogToAuthor")) {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// BugReportmailer bugReport = new GPBugReportmailer();
// bugReport.send(GpFrame.this);
// }
//
// });
// logMenu.add(jMenuItemSendLog);
}
// // TODO unschön, Switch raster Renderers for testing
// {
// rasterCheckBoxMenuItem = new JCheckBoxMenuItem(new AbstractAction(
// "Use new reader for raster") {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// boolean oldValue = GPProps
// .getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true);
//
// boolean newValue = !oldValue;
// GPProps.set(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// newValue);
// rasterCheckBoxMenuItem.setSelected(newValue);
// }
// });
// rasterCheckBoxMenuItem.setSelected((GPProps.getBoolean(
// org.geopublishing.geopublisher.GPProps.Keys.rasterReader,
// true)));
// optionsMenu.add(rasterCheckBoxMenuItem);
// }
/**
* Manage ASCII Reader
*/
return optionsMenu;
}
|
diff --git a/src/hexgui/sgf/SgfWriter.java b/src/hexgui/sgf/SgfWriter.java
index 3c04b57..9fa7f7f 100644
--- a/src/hexgui/sgf/SgfWriter.java
+++ b/src/hexgui/sgf/SgfWriter.java
@@ -1,144 +1,144 @@
//----------------------------------------------------------------------------
// $Id$
//----------------------------------------------------------------------------
package hexgui.sgf;
import hexgui.version.Version;
import hexgui.hex.HexColor;
import hexgui.hex.HexPoint;
import hexgui.hex.Move;
import hexgui.game.Node;
import hexgui.game.GameInfo;
import java.io.*;
import java.awt.Dimension;
import java.util.Map;
import java.util.Iterator;
import java.util.Vector;
//----------------------------------------------------------------------------
/** SGF Writer. */
public final class SgfWriter
{
/** Write a game tree. */
public SgfWriter(OutputStream out, Node root, GameInfo game)
{
m_out = new PrintStream(out);
m_buffer = new StringBuffer(128);
m_gameinfo = game;
writeTree(root, true);
print("\n");
flushBuffer();
m_out.flush();
m_out.close();
}
private void writeTree(Node root, boolean isroot)
{
print("(");
writeNode(root, isroot);
print(")");
}
private void writeNode(Node node, boolean isroot)
{
print(";");
if (isroot) {
String value;
node.setSgfProperty("FF", "4");
- node.setSgfProperty("AP", "HexGui:"+Version.id+"."+Version.build);
+ node.setSgfProperty("AP", "HexGui:"+Version.id);
node.setSgfProperty("GM", "11");
Dimension dim = m_gameinfo.getBoardSize();
value = Integer.toString(dim.width);
if (dim.width != dim.height)
value += ":" + Integer.toString(dim.height);
node.setSgfProperty("SZ", value);
}
if (node.getMove() != null)
printMove(node.getMove());
if (node.hasSetup()) {
Vector<HexPoint> list;
list = node.getSetup(HexColor.BLACK);
if (!list.isEmpty()) {
print("AB");
printPointList(list);
}
list = node.getSetup(HexColor.WHITE);
if (!list.isEmpty()) {
print("AW");
printPointList(list);
}
list = node.getSetup(HexColor.EMPTY);
if (!list.isEmpty()) {
print("AE");
printPointList(list);
}
}
Map<String,String> map = node.getProperties();
Iterator<Map.Entry<String,String> > it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String,String> e = it.next();
if (!(e.getKey().equals("C") && e.getValue().equals("")))
print(e.getKey() + "[" + e.getValue() + "]");
}
int num = node.numChildren();
if (num == 0) return;
if (num == 1) {
writeNode(node.getChild(), false);
return;
}
for (int i=0; i<num; i++)
writeTree(node.getChild(i), false);
}
private void printMove(Move move)
{
String color = "B";
if (move.getColor() == HexColor.WHITE)
color = "W";
print(color + "[" + move.getPoint().toString() + "]");
}
private void printPointList(Vector<HexPoint> list)
{
for (int i=0; i<list.size(); ++i) {
print("[" + list.get(i).toString() + "]");
}
}
private void print(String str)
{
if (m_buffer.length() + str.length() > 72) {
m_out.append(m_buffer.toString());
m_out.append("\n");
m_buffer.setLength(0);
}
m_buffer.append(str);
}
private void flushBuffer()
{
m_out.append(m_buffer.toString());
m_buffer.setLength(0);
}
private PrintStream m_out;
private StringBuffer m_buffer;
private GameInfo m_gameinfo;
}
//----------------------------------------------------------------------------
| true | true | private void writeNode(Node node, boolean isroot)
{
print(";");
if (isroot) {
String value;
node.setSgfProperty("FF", "4");
node.setSgfProperty("AP", "HexGui:"+Version.id+"."+Version.build);
node.setSgfProperty("GM", "11");
Dimension dim = m_gameinfo.getBoardSize();
value = Integer.toString(dim.width);
if (dim.width != dim.height)
value += ":" + Integer.toString(dim.height);
node.setSgfProperty("SZ", value);
}
if (node.getMove() != null)
printMove(node.getMove());
if (node.hasSetup()) {
Vector<HexPoint> list;
list = node.getSetup(HexColor.BLACK);
if (!list.isEmpty()) {
print("AB");
printPointList(list);
}
list = node.getSetup(HexColor.WHITE);
if (!list.isEmpty()) {
print("AW");
printPointList(list);
}
list = node.getSetup(HexColor.EMPTY);
if (!list.isEmpty()) {
print("AE");
printPointList(list);
}
}
Map<String,String> map = node.getProperties();
Iterator<Map.Entry<String,String> > it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String,String> e = it.next();
if (!(e.getKey().equals("C") && e.getValue().equals("")))
print(e.getKey() + "[" + e.getValue() + "]");
}
int num = node.numChildren();
if (num == 0) return;
if (num == 1) {
writeNode(node.getChild(), false);
return;
}
for (int i=0; i<num; i++)
writeTree(node.getChild(i), false);
}
| private void writeNode(Node node, boolean isroot)
{
print(";");
if (isroot) {
String value;
node.setSgfProperty("FF", "4");
node.setSgfProperty("AP", "HexGui:"+Version.id);
node.setSgfProperty("GM", "11");
Dimension dim = m_gameinfo.getBoardSize();
value = Integer.toString(dim.width);
if (dim.width != dim.height)
value += ":" + Integer.toString(dim.height);
node.setSgfProperty("SZ", value);
}
if (node.getMove() != null)
printMove(node.getMove());
if (node.hasSetup()) {
Vector<HexPoint> list;
list = node.getSetup(HexColor.BLACK);
if (!list.isEmpty()) {
print("AB");
printPointList(list);
}
list = node.getSetup(HexColor.WHITE);
if (!list.isEmpty()) {
print("AW");
printPointList(list);
}
list = node.getSetup(HexColor.EMPTY);
if (!list.isEmpty()) {
print("AE");
printPointList(list);
}
}
Map<String,String> map = node.getProperties();
Iterator<Map.Entry<String,String> > it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<String,String> e = it.next();
if (!(e.getKey().equals("C") && e.getValue().equals("")))
print(e.getKey() + "[" + e.getValue() + "]");
}
int num = node.numChildren();
if (num == 0) return;
if (num == 1) {
writeNode(node.getChild(), false);
return;
}
for (int i=0; i<num; i++)
writeTree(node.getChild(i), false);
}
|
diff --git a/src/main/java/bang/bang/App.java b/src/main/java/bang/bang/App.java
index 55ddadf..713a160 100644
--- a/src/main/java/bang/bang/App.java
+++ b/src/main/java/bang/bang/App.java
@@ -1,740 +1,740 @@
package bang.bang;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
/**
* Hello world!
*
*/
public class App
{
static String[] printArray = {"empty",
"You lily livered yellow bellied scoundrel",
"Butthead",
"You smell like manure.",
"You're as ugly as a burnt boot.",
"You couldn't teach a hen to cluck.",
"You're as dull as a dishwasher.",
"You gutless, yellow, pie-slinger",
"So, from now on, you better be lookin' behind you when you walk. 'Cause one day you're gonna get a bullet in your back.",
"You are uglier than a new-sheared sheep.",
"You Irish bug",
"Ouch!",
"You got me!",
"Barf!",
"Jackpot!",
"I'm laughing all the way to the bank.",
"Bonus!",
"Mmmmm…beer.",
"Drinks all around!",
"Yay... water",
"One tequila, two tequlia, three tequila, floor.",
"What wiskey will not cure, there is no cure for.",
"Thank heaven",
"INDIANS!!!",
"When I'm done with you, there won't be enough left of you to snore.",
"Cause of death? Lead poisoning.",
"Let's settle this once and for all, runt! Or ain't you got the gumption?",
"I aim to shoot somebody today and I'd prefer it'd be you.",
"Bang!",
"Bang, Bang!",
"Dodge this!",
"Not as deceiving as a low down, dirty... deceiver.","Make like a tree and get out of here.",
"That's about as funny as a screen door on a battleship.",
"Tim is a saboteur.",
"Let's go! I got me a runt to kill!",
"Let these sissies have their party.",
"Nobody calls me \"Mad Dog\", especially not some duded-up, egg-suckin' gutter trash.",
"I hate manure.","What's wrong, McFly. Chicken?",
"New York city! Get a rope.",
"There's a snake in my boot. ",
"Gimme, Gimme!",
"I'll be taking that.","Mine!",
"Get that trash out of here!",
"Go back to where you came from. ",
"Yeah, you can go ahead and get rid of that.",
"I'm armed and dangerous.",
"Which way to the gun show?",
"I'm on a horse.",
"Ha, you can't find me!",
"Saved by the Barrel.",
"Setting my sights.",
"I spy with my little eye.",
"Lets make this a little more interesting.",
"Kaboom!",
"I'm locking you up!",
"Nobody knows the trouble I've seen…",
"Thanks, sucker!",
"I'm getting better.",
"You Missed.",
"In yo face!",
"You couldn't hit water if you fell out of a boat.",
"I'm Buford 'Pi' Tannen","Blargh! *DEATH*",
"I call my gun Vera"};
static Random rnd = new Random();
static int health = 0;
static int rangeGun = 1;
static int rangeOther = 0;
static int myRange = rangeGun + rangeOther;
static List <String> roles = new ArrayList<String>();
static List <String> hand = new ArrayList<String>();
static List <String> bHand = new ArrayList<String>();
static List <GreenHand> gHand = new ArrayList<GreenHand>();
static String myRole = "";
static int inHand = 0;
static String lastCardPlayed = "";
static boolean isVolcanic = false;
static Long lastModifiedDate;
public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
b3Button(action[2]);
System.out.println("b3 command");
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
- System.out.println("green hands: " + gHand);
+ System.out.println("green hands: " + gHand.get(0).getCard());
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void healMe() {
// TODO Auto-generated method stub
if(health >= 4){
//Print i have full health don't need to heal me
play("I have full health, don't need your heal");
}
else
{
health = health + 1;
//print my full health
play("my health should be: " + health);
}
}
private static void someoneShootAtMe(String card) {
int idxOfHand = 0;
if(card.equals("indians") || card.equals("duel")){
//do i have a miss
if(hand.contains("bang")){
idxOfHand = hand.indexOf("bang");
hand.remove(idxOfHand);
//print something to pi hand + bang, index
play ("Hand: " + String.valueOf(idxOfHand) +" card should be bang " + printArray[30].toString());
}
else{
//print something is wrong
//lost one health, if health is <= 0 print out die message
if(health >=2){
health = health - 1;
play ("Almost got me" + printArray[11] + "health is: " + health );
}
else
{
play ("I am dead " + printArray[13]);
}
}
}
else
{
if(gHand.contains("sombrero") || gHand.contains("tengallonhat") || gHand.contains("ironplate")
|| gHand.contains("bible")){
Iterator<GreenHand> iter = gHand.iterator();
while (iter.hasNext()) { // any more element
// Retrieve the next element, explicitly downcast from Object back to String
GreenHand gh = iter.next();
if(gh.Card.equals("sombrero") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("Hand: " + idxOfHand + " card should be sombrero " + " you can do better than this!");
break;
}
else if(gh.Card.equals("tengallonhat") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be sombrero " + " Oh my ten gallon hat is so heavy");
break;
}
else if(gh.Card.equals("ironplate") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be ironplate " + " nothing can come through with my iron plate");
break;
}
else if(gh.Card.equals("bible") && gh.active > 0){
idxOfHand = gHand.indexOf(gh.Card);
gHand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be bible " + " God is awesome!");
break;
}
}
}
else if(hand.contains("missed") ){
idxOfHand = hand.indexOf("missed");
hand.remove(idxOfHand);
//print something
System.out.println("hand: " + idxOfHand + " card should be miss " + " You Missed.");
play (String.valueOf("hand: " + idxOfHand + " card should be miss " + " You Missed."));
}
else if(hand.contains("dodge")){
idxOfHand = hand.indexOf("dodge");
hand.remove(idxOfHand);
//print something
play("hand: " + idxOfHand + " card should be dodge " + " I dodged the bullet.");
}
else{
//
if (health >= 2){
health = health - 1;
}
else
{
if(hand.contains("beer")){
idxOfHand = hand.indexOf("beer");
hand.remove(idxOfHand);
//print last health but played beer
play("hand: " + idxOfHand + " card should be beer " + " I am dead, but I have beer");
}
else{
//print I am dead, no miss or health
play(" I have no health, it's game over for me ");
}
}
}
}
}
private static void takeCardFromHand(String cardType,String card) {
int idxOfHand = 0;
if(cardType.equals("blue")){
if(bHand.contains(card)){
//do somehting
idxOfHand = bHand.indexOf(card);
bHand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else{
//print something wrong
play("are you sure? if you are here there is something wrong, you should start a new game. ");
}
}
else if(cardType.equals("gren")){
if(gHand.contains(card)){
//do something
idxOfHand = gHand.indexOf(card);
gHand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else{
//print something wrong
play("are you sure? if you are here, there is something wrong, you should start a new game. ");
}
}
else {
if(hand.contains(card)){
//do something
idxOfHand = hand.indexOf(card);
hand.remove(card);
play("Hand: " + idxOfHand + "card should be: " + card + printArray[8]);
}
else
{
//print something wrong
play("are you sure? if you are here, there is something wrong, you should start a new game. ");
}
}
}
public static void addToHand(int handType, String card) {
// resulted from b3 - used to add initial hand and general store cards
switch (handType) {
case 1: hand.add(card);
inHand++;
break;
case 2: GreenHand tmp = new GreenHand(card);
gHand.add(tmp);
inHand++;
break;
case 3: bHand.add(card);
inHand++;
break;
default: break;
}
}
public static void b3Button(String card) {
// see excel sheet B3 table
String print = new String();
String currentCard = new String();
int playerIndex;
int sheriffPos = findSheriff();
// if (card.equals("jail"))
// play("miss turn");
// if (card.equals("dynamite")) {
// health = health - 3;
// if (health <=0) {
// for (int i = 0; i < bHand.size(); i++) {
// currentCard = hand.get(i);
// if (currentCard.equals("beer")) {
// play("Hand: " + i + " " + printArray[17]);
// break;
// }
// }
// }
// else
// play(printArray[56]);
// }
System.out.println("in b3!");
for (int i = 0; i < bHand.size(); i++) {
System.out.println("looping blue hand");
currentCard = bHand.get(i);
if (currentCard.equals("jail")) {
do
playerIndex = choosePlayerIndex(roles.size());
while (playerIndex != sheriffPos);
}
if (currentCard.equals("dynamite")) {
playerIndex = choosePlayerIndex(roles.size());
}
if (currentCard.equals("binocular")) {
rangeOther++;
bHand.remove(i);
play("Hand: " + i + printArray[54]);
}
if (currentCard.equals("scope")) {
rangeOther++;
bHand.remove(i);
play("Hand: " + i + printArray[53]);
}
if (currentCard.equals("barrel") || currentCard.equals("hideout") || currentCard.equals("mustang")) {
bHand.remove(i);
play("Hand: " + i);
}
if (currentCard.equals("schofield") && rangeGun < 2) {
rangeGun = 2;
bHand.remove(i);
play("Hand: " + i + printArray[48]);
}
if (currentCard.equals("remindton") && rangeGun < 3){
rangeGun = 3;
bHand.remove(i);
play("Hand: " + i + printArray[49]);
}
if (currentCard.equals("schofield") && rangeGun < 4){
rangeGun = 4;
bHand.remove(i);
play("Hand: " + i + printArray[48]);
}
if (currentCard.equals("schofield") && rangeGun < 5){
rangeGun = 5;
bHand.remove(i);
play("Hand: " + i + printArray[49]);
}
if (currentCard.equals("volcanic")) {
if (!(myRole.contains("outlaw") && sheriffPos > 1)) {
rangeGun = 1;
isVolcanic = true;
bHand.remove(i);
play("Hand: " + i + printArray[66]);
}
}
}
for (int i = 0; i < gHand.size(); i++) {
GreenHand currentGreen = gHand.get(i);
if (currentGreen.isInPlay() && !currentGreen.isActive()) {
currentGreen.activate();
gHand.set(i,currentGreen);
}
}
for (int i = 0; i < gHand.size(); i++) {
System.out.println("looping green hand");
GreenHand currentGreen = gHand.get(i);
String cGCard = currentGreen.getCard();
if (currentGreen.isActive()) {
if (cGCard.equals("contestoga") || cGCard.equals("cancan") || cGCard.equals("pepperbox")
|| cGCard.equals("howitzer") || cGCard.equals("buffalorifle") || cGCard.equals("knife")
|| cGCard.equals("derringer")) {
play(String.valueOf("Green Hand: " + i + " On player: " + choosePlayerIndex(myRange)) + printArray[25]);
}
if (cGCard.equals("canteen") && health < 4) {
gHand.remove(i);
play("Green Hand: " + i + printArray[19]);
}
if (cGCard.equals("ponyexpress")) {
gHand.remove(i);
play("Green Hand: " + i + printArray[14]);
}
}
if (!currentGreen.isInPlay()) {
currentGreen.play();
gHand.set(i,currentGreen);
play("green card" + i + printArray[10]);
}
}
for (int i = 0; i < hand.size(); i++) {
System.out.println("looping hand");
String cBCard = hand.get(i);
if (cBCard.equals("panic")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(rangeOther)) + printArray[43]);
}
if (cBCard.equals("ragtime") || cBCard.equals("brawl")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i) + " On player: " + choosePlayerIndex(rangeOther)) + printArray[44]);
}
if (cBCard.equals("cat")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(roles.size())) + printArray[47]);
}
if (cBCard.equals("bang")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(myRange)) + printArray[28]);
}
if (cBCard.equals("gatling")) {
hand.remove(i);
play("Hand: " + i + " On player: " + choosePlayerIndex(myRange) + printArray[29]);
}
if (cBCard.equals("punch")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " On player: " + choosePlayerIndex(rangeOther)) + printArray[30]);
}
if (cBCard.equals("springfield") || cBCard.equals("duel")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i) + " On player: " + choosePlayerIndex(roles.size())) + printArray[8]);
}
if (cBCard.equals("indians") || cBCard.equals("wellsfargo") || cBCard.equals("stagecoach")) {
hand.remove(i);
play("Hand: " + + i + printArray[15]);
}
if (health < 4) {
if (cBCard.equals("beer")) {
hand.remove(i);
play("Hand: " + i + printArray[17]);
}
if (cBCard.equals("saloon")) {
hand.remove(i);
play("Hand: " + i + printArray[18]);
}
if (cBCard.equals("whiskey")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i)) + printArray[21]);
}
if (cBCard.equals("tequila")) {
hand.remove(i);
play(String.valueOf("Hand: " + i + " and " + randomCard(i)) + printArray[20]);
}
}
}
}
public static int randomCard(int index) {
int rand = rnd.nextInt(hand.size());
if (rand == index)
rand = randomCard(index);
return rand;
}
public static void b2Button(String card) {
// see excel sheet B2 table
switch (1) {
case 1:
break;
default: break;
}
}
public static void play(String str) {
try {
Runtime.getRuntime().exec("python scream.py \"" + str + "\"");
System.out.println("inside of method to exec scream.py ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static int choosePlayerIndex(int range) {
/*
* Sheriff: shoot all
* Outlaw: shoot sheriff if in range, else random
* Deputy: shoot all except sheriff
* Renegade: shoot all except sheriff, sheriff last
*
*/
int sheriffPos = findSheriff();
int direction = 0; // 0 = left, 1 = right
if (!(sheriffPos == 0))
if (((double)sheriffPos/(double)roles.size()) > 0.5)
direction = 1;
int index = rnd.nextInt(Math.abs(range));
if (index == 0)
index++;
int sheriff = findSheriff();
// if (myRole.equals("sheriff")) {
// return index;
// }
// else
if (myRole.equals("renegade")) {
if (roles.get(index).equals("sheriff") && roles.size() > 2)
index = choosePlayerIndex(range);
}
else if (myRole.equals("deputy1") || myRole.equals("deputy2")) {
if (roles.get(index).equals("sheriff"))
index = choosePlayerIndex(range);
}
else if (myRole.equals("outlaw1") || myRole.equals("outlaw2") || myRole.equals("outlaw3")) {
if (sheriff <= myRange)
index = sheriff;
}
if (direction == 1)
return Math.abs(roles.size() - index);
else
return index;
}
public static int findSheriff () {
for (int i = 0; i < roles.size(); i++)
if (roles.get(i).equals("sheriff"))
return i;
return 0;
}
}
| true | true | public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
b3Button(action[2]);
System.out.println("b3 command");
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
System.out.println("green hands: " + gHand);
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void main( String[] args )
{
boolean start = true;
File file = new File("bang.txt");
//card holders
// String colorOfCard = "";
// String B1 = "";
// String B2 = "";
lastModifiedDate = file.lastModified();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String[] action;
line = reader.readLine();
//Read one line at a time, printing it.
while (start) {
if(line.equals("start"))
{
start = true;
/*
* To do
* initialize the game state
*/
//Initilaize Myself;
health = 4;
System.out.println("start command: ");
}
else if(line.equals("end"))
{ /*
* To do
* Cleanup
*/
start = false;
System.out.print("end command");
}
// close file and wait for new input
try {
reader.close();
while(lastModifiedDate.equals(file.lastModified()))
{
Thread.sleep(5000);
}
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
while(line.equals(null)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line = reader.readLine();
}
while(line.split(",").length < 2){
try {
reader.close();
Thread.sleep(5000);
reader = new BufferedReader(new FileReader(file));
line = reader.readLine();
lastModifiedDate = file.lastModified();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//read file for command to play the game
action = line.split(",");
if(action.length < 1){
// something is wrong
} else if (action[0].equals("b3")) {
/*
* to do
* add cards to correct hand
*/
b3Button(action[2]);
System.out.println("b3 command");
} else if (action[0].equals("b1")){
/*
* to do
* Add 2 cards to hand and play my turn
* If role card
* scan for roles (sheriff, deputy, outlaw, renegate)
*/
if (action[1].equals("role")) {
roles.add(action[2]);
if(myRole.equals("")) {
myRole = roles.get(0);
if (myRole.equals("sheriff")){
health++;
play("I am el Sheriffo!"); // announce myself if sheriff
}
}
System.out.println("starting a new game... role has been set");
}
else { // Add to hand
if (action[1].equals("gren"))
addToHand(2, action[2]);
else if (action[1].equals("blue"))
addToHand(3, action[2]);
else
addToHand(1, action[2]);
}
} else if (action[0].equals("b2")){
String card = action[2];
String cardType = action[1];
//b2 role action , one of the player is dead, reset role
if (action[1].equals("role")) {
for (int i = 0; i < roles.size(); i++) {
if (roles.get(i).equals(action[2])){
roles.remove(i);
//print something
play("You dead player " + i + "who is the champ now?");
}
}
}
if(lastCardPlayed.equals("panic") || lastCardPlayed.equals("contestoga") || lastCardPlayed.equals("ragtime")
|| lastCardPlayed.equals("cancan") || lastCardPlayed.equals("catbalou")
|| lastCardPlayed.equals("brawl")) {
//do action for taking a card away from my hand
takeCardFromHand(cardType, card);
lastCardPlayed = card;
}
if(card.equals("panic") || card.equals("contestoga") || card.equals("ragtime")
|| card.equals("cancan") || card.equals("cat") || card.equals("brawl")){
lastCardPlayed = card;
}
else if(card.equals("bang") || card.equals("pepperbox") || card.equals("howitzer") || card.equals("Buffalorifle")
|| card.equals("punch") || card.equals("knife") || card.equals("derringer")
|| card.equals("springfield") || card.equals("indian") || card.equals("duel")){
// do action for to check for miss, no miss check for health, last health check for beer. if last health play beer
System.out.println("inside: someoneShottAtMe");
someoneShootAtMe(card);
lastCardPlayed = card;
}
// else if(card.equals("indian") || card.equals("duel")){
// // play bang , if no bang in hand, minus health, if last bullet,
// someoneShootMe(card);
// //print something and announce finished from the game
// }
else if(card.equals("saloon") || card.equals("tequila")){
// heal me, check for health if full health skip
healMe();
lastCardPlayed = card;
}
}
System.out.println("hands: " + hand );
System.out.println("myrole: " + myRole);
System.out.println("roles: " + roles);
System.out.println("blue hands: " + bHand);
System.out.println("green hands: " + gHand.get(0).getCard());
System.out.println("health: " + health);
}
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/api_test/APITest.java b/api_test/APITest.java
index 12fcf5c..af2fa4f 100644
--- a/api_test/APITest.java
+++ b/api_test/APITest.java
@@ -1,129 +1,129 @@
import clj_span.java_span_bridge;
import java.util.HashMap;
public class APITest {
public static void main(String[] args) {
int rows = 10;
int cols = 10;
double[] sourceLayer =
{0.0,100.0,0.0,0.0,0.0,100.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0,100.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0,100.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0};
double[] sinkLayer =
{0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0,100.0,10.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0};
double[] useLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
double[] elevLayer =
{30.0,60.0,32.0,32.0,32.0,28.0,11.0, 5.0, 5.0,5.0,
30.0,29.0,27.0,27.0,27.0,20.0, 6.0, 5.0, 5.0,5.0,
30.0,28.0,22.0,22.0,22.0,15.0, 3.0, 5.0, 5.0,5.0,
30.0,27.0,17.0,17.0,17.0,11.0, 2.0, 2.0, 5.0,5.0,
30.0,26.0,12.0, 8.0, 9.0, 9.0, 0.0, 1.0, 5.0,5.0,
30.0,25.0, 7.0, 3.0, 5.0, 5.0, 1.0, 3.0, 5.0,5.0,
30.0,24.0, 2.0, 2.0, 4.0, 4.0, 3.0, 5.0, 8.0,5.0,
30.0,23.0, 1.0, 3.0, 3.0, 3.0, 8.0, 9.0,11.0,5.0,
30.0,22.0, 1.0, 3.0, 7.0, 9.0,12.0,13.0,20.0,5.0,
30.0,21.0, 1.0, 3.0, 8.0, 9.0,14.0,15.0,17.0,5.0};
double[] waterLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
HashMap<String,double[]> flowLayers = new HashMap<String,double[]>();
flowLayers.put("Altitude", elevLayer);
flowLayers.put("WaterBodies", waterLayer);
double sourceThreshold = 0.0;
double sinkThreshold = 0.0;
double useThreshold = 0.0;
double transThreshold = 1.0;
double cellWidth = 100.0;
double cellHeight = 100.0;
int rvMaxStates = 10;
double downscalingFactor = 1.0;
String sourceType = "infinite";
String sinkType = "infinite";
String useType = "infinite";
String benefitType = "non-rival";
String valueType = "numbers";
String flowModel = "LineOfSight";
- boolean animation = false;
+ boolean animation = true;
String[] resultLayers = {"theoretical-source","actual-sink","possible-use","blocked-flow"};
HashMap<String,Object> spanParams = new HashMap<String,Object>();
spanParams.put("source-layer", sourceLayer);
spanParams.put("sink-layer", sinkLayer);
spanParams.put("use-layer", useLayer);
spanParams.put("flow-layers", flowLayers);
spanParams.put("rows", rows);
spanParams.put("cols", cols);
spanParams.put("source-threshold", sourceThreshold);
spanParams.put("sink-threshold", sinkThreshold);
spanParams.put("use-threshold", useThreshold);
spanParams.put("trans-threshold", transThreshold);
spanParams.put("cell-width", cellWidth);
spanParams.put("cell-height", cellHeight);
spanParams.put("rv-max-states", rvMaxStates);
spanParams.put("downscaling-factor", downscalingFactor);
spanParams.put("source-type", sourceType);
spanParams.put("sink-type", sinkType);
spanParams.put("use-type", useType);
spanParams.put("benefit-type", benefitType);
spanParams.put("value-type", valueType);
spanParams.put("flow-model", flowModel);
spanParams.put("animation?", animation);
spanParams.put("result-layers", resultLayers);
HashMap<String,Object> resultMap = clj_span.java_span_bridge.runSpan(spanParams);
System.out.println(resultMap);
}
}
| true | true | public static void main(String[] args) {
int rows = 10;
int cols = 10;
double[] sourceLayer =
{0.0,100.0,0.0,0.0,0.0,100.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0,100.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0,100.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0};
double[] sinkLayer =
{0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0,100.0,10.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0};
double[] useLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
double[] elevLayer =
{30.0,60.0,32.0,32.0,32.0,28.0,11.0, 5.0, 5.0,5.0,
30.0,29.0,27.0,27.0,27.0,20.0, 6.0, 5.0, 5.0,5.0,
30.0,28.0,22.0,22.0,22.0,15.0, 3.0, 5.0, 5.0,5.0,
30.0,27.0,17.0,17.0,17.0,11.0, 2.0, 2.0, 5.0,5.0,
30.0,26.0,12.0, 8.0, 9.0, 9.0, 0.0, 1.0, 5.0,5.0,
30.0,25.0, 7.0, 3.0, 5.0, 5.0, 1.0, 3.0, 5.0,5.0,
30.0,24.0, 2.0, 2.0, 4.0, 4.0, 3.0, 5.0, 8.0,5.0,
30.0,23.0, 1.0, 3.0, 3.0, 3.0, 8.0, 9.0,11.0,5.0,
30.0,22.0, 1.0, 3.0, 7.0, 9.0,12.0,13.0,20.0,5.0,
30.0,21.0, 1.0, 3.0, 8.0, 9.0,14.0,15.0,17.0,5.0};
double[] waterLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
HashMap<String,double[]> flowLayers = new HashMap<String,double[]>();
flowLayers.put("Altitude", elevLayer);
flowLayers.put("WaterBodies", waterLayer);
double sourceThreshold = 0.0;
double sinkThreshold = 0.0;
double useThreshold = 0.0;
double transThreshold = 1.0;
double cellWidth = 100.0;
double cellHeight = 100.0;
int rvMaxStates = 10;
double downscalingFactor = 1.0;
String sourceType = "infinite";
String sinkType = "infinite";
String useType = "infinite";
String benefitType = "non-rival";
String valueType = "numbers";
String flowModel = "LineOfSight";
boolean animation = false;
String[] resultLayers = {"theoretical-source","actual-sink","possible-use","blocked-flow"};
HashMap<String,Object> spanParams = new HashMap<String,Object>();
spanParams.put("source-layer", sourceLayer);
spanParams.put("sink-layer", sinkLayer);
spanParams.put("use-layer", useLayer);
spanParams.put("flow-layers", flowLayers);
spanParams.put("rows", rows);
spanParams.put("cols", cols);
spanParams.put("source-threshold", sourceThreshold);
spanParams.put("sink-threshold", sinkThreshold);
spanParams.put("use-threshold", useThreshold);
spanParams.put("trans-threshold", transThreshold);
spanParams.put("cell-width", cellWidth);
spanParams.put("cell-height", cellHeight);
spanParams.put("rv-max-states", rvMaxStates);
spanParams.put("downscaling-factor", downscalingFactor);
spanParams.put("source-type", sourceType);
spanParams.put("sink-type", sinkType);
spanParams.put("use-type", useType);
spanParams.put("benefit-type", benefitType);
spanParams.put("value-type", valueType);
spanParams.put("flow-model", flowModel);
spanParams.put("animation?", animation);
spanParams.put("result-layers", resultLayers);
HashMap<String,Object> resultMap = clj_span.java_span_bridge.runSpan(spanParams);
System.out.println(resultMap);
}
| public static void main(String[] args) {
int rows = 10;
int cols = 10;
double[] sourceLayer =
{0.0,100.0,0.0,0.0,0.0,100.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0,100.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0,100.0,0.0,
0.0, 0.0,0.0,0.0,0.0, 0.0,0.0, 0.0, 0.0,0.0};
double[] sinkLayer =
{0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,10.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0,100.0,10.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0, 0.0, 0.0, 0.0,0.0,0.0};
double[] useLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
double[] elevLayer =
{30.0,60.0,32.0,32.0,32.0,28.0,11.0, 5.0, 5.0,5.0,
30.0,29.0,27.0,27.0,27.0,20.0, 6.0, 5.0, 5.0,5.0,
30.0,28.0,22.0,22.0,22.0,15.0, 3.0, 5.0, 5.0,5.0,
30.0,27.0,17.0,17.0,17.0,11.0, 2.0, 2.0, 5.0,5.0,
30.0,26.0,12.0, 8.0, 9.0, 9.0, 0.0, 1.0, 5.0,5.0,
30.0,25.0, 7.0, 3.0, 5.0, 5.0, 1.0, 3.0, 5.0,5.0,
30.0,24.0, 2.0, 2.0, 4.0, 4.0, 3.0, 5.0, 8.0,5.0,
30.0,23.0, 1.0, 3.0, 3.0, 3.0, 8.0, 9.0,11.0,5.0,
30.0,22.0, 1.0, 3.0, 7.0, 9.0,12.0,13.0,20.0,5.0,
30.0,21.0, 1.0, 3.0, 8.0, 9.0,14.0,15.0,17.0,5.0};
double[] waterLayer =
{0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,
0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
HashMap<String,double[]> flowLayers = new HashMap<String,double[]>();
flowLayers.put("Altitude", elevLayer);
flowLayers.put("WaterBodies", waterLayer);
double sourceThreshold = 0.0;
double sinkThreshold = 0.0;
double useThreshold = 0.0;
double transThreshold = 1.0;
double cellWidth = 100.0;
double cellHeight = 100.0;
int rvMaxStates = 10;
double downscalingFactor = 1.0;
String sourceType = "infinite";
String sinkType = "infinite";
String useType = "infinite";
String benefitType = "non-rival";
String valueType = "numbers";
String flowModel = "LineOfSight";
boolean animation = true;
String[] resultLayers = {"theoretical-source","actual-sink","possible-use","blocked-flow"};
HashMap<String,Object> spanParams = new HashMap<String,Object>();
spanParams.put("source-layer", sourceLayer);
spanParams.put("sink-layer", sinkLayer);
spanParams.put("use-layer", useLayer);
spanParams.put("flow-layers", flowLayers);
spanParams.put("rows", rows);
spanParams.put("cols", cols);
spanParams.put("source-threshold", sourceThreshold);
spanParams.put("sink-threshold", sinkThreshold);
spanParams.put("use-threshold", useThreshold);
spanParams.put("trans-threshold", transThreshold);
spanParams.put("cell-width", cellWidth);
spanParams.put("cell-height", cellHeight);
spanParams.put("rv-max-states", rvMaxStates);
spanParams.put("downscaling-factor", downscalingFactor);
spanParams.put("source-type", sourceType);
spanParams.put("sink-type", sinkType);
spanParams.put("use-type", useType);
spanParams.put("benefit-type", benefitType);
spanParams.put("value-type", valueType);
spanParams.put("flow-model", flowModel);
spanParams.put("animation?", animation);
spanParams.put("result-layers", resultLayers);
HashMap<String,Object> resultMap = clj_span.java_span_bridge.runSpan(spanParams);
System.out.println(resultMap);
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_urbandictionary.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_urbandictionary.java
index 098c26b..a9f0939 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_urbandictionary.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_urbandictionary.java
@@ -1,68 +1,68 @@
package com.github.zathrus_writer.commandsex.commands;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.zathrus_writer.commandsex.helpers.Commands;
import com.github.zathrus_writer.commandsex.helpers.LogHelper;
import com.github.zathrus_writer.commandsex.helpers.Permissions;
import com.github.zathrus_writer.commandsex.helpers.PlayerHelper;
import com.github.zathrus_writer.commandsex.helpers.Utils;
public class Command_cex_urbandictionary {
/***
* Urban Dictionary - Gets the definition of a word in the urban dictionary!
* @author Kezz101
* @param sender
* @param args
* @return
*/
public static Boolean run(CommandSender sender, String alias, String[] args) {
if(PlayerHelper.checkIsPlayer(sender) && !Utils.checkCommandSpam((Player)sender, "urbandictionary") && Permissions.checkPerms((Player)sender, "cex.urbandictionary")) {
if(args.length == 1) {
String def = null;
try {
LogHelper.showInfo("urbanDictionaryPleaseWait", sender);
HttpURLConnection url = (HttpURLConnection) new URL("http://urbanscraper.herokuapp.com/define/" + args[0] + ".json").openConnection();
url.setConnectTimeout(10000);
url.setReadTimeout(10000);
url.connect();
if(url.getErrorStream() == null) {
def = convertStreamToString((InputStream)url.getContent());
}
} catch (Exception e) {
LogHelper.showWarnings(sender, "urbanDictionaryError");
return true;
}
Pattern pattern = Pattern.compile("\"definition\":\"(.*?)\",\"example\"");
Matcher matcher = pattern.matcher(def);
if (matcher.find()) {
def = matcher.group(1);
- LogHelper.showInfo("urbanDictionaryDef#####[" + def, sender);
+ LogHelper.showInfo("urbanDictionaryDef#####[" + def.replaceAll("\\\\r", "\n"), sender);
} else {
LogHelper.showWarnings(sender, "urbanDictionaryError");
}
} else {
Commands.showCommandHelpAndUsage(sender, "cex_urbandictionary", alias);
}
}
return true;
}
public static String convertStreamToString(java.io.InputStream is) {
try {
return new java.util.Scanner(is).useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
}
| true | true | public static Boolean run(CommandSender sender, String alias, String[] args) {
if(PlayerHelper.checkIsPlayer(sender) && !Utils.checkCommandSpam((Player)sender, "urbandictionary") && Permissions.checkPerms((Player)sender, "cex.urbandictionary")) {
if(args.length == 1) {
String def = null;
try {
LogHelper.showInfo("urbanDictionaryPleaseWait", sender);
HttpURLConnection url = (HttpURLConnection) new URL("http://urbanscraper.herokuapp.com/define/" + args[0] + ".json").openConnection();
url.setConnectTimeout(10000);
url.setReadTimeout(10000);
url.connect();
if(url.getErrorStream() == null) {
def = convertStreamToString((InputStream)url.getContent());
}
} catch (Exception e) {
LogHelper.showWarnings(sender, "urbanDictionaryError");
return true;
}
Pattern pattern = Pattern.compile("\"definition\":\"(.*?)\",\"example\"");
Matcher matcher = pattern.matcher(def);
if (matcher.find()) {
def = matcher.group(1);
LogHelper.showInfo("urbanDictionaryDef#####[" + def, sender);
} else {
LogHelper.showWarnings(sender, "urbanDictionaryError");
}
} else {
Commands.showCommandHelpAndUsage(sender, "cex_urbandictionary", alias);
}
}
return true;
}
| public static Boolean run(CommandSender sender, String alias, String[] args) {
if(PlayerHelper.checkIsPlayer(sender) && !Utils.checkCommandSpam((Player)sender, "urbandictionary") && Permissions.checkPerms((Player)sender, "cex.urbandictionary")) {
if(args.length == 1) {
String def = null;
try {
LogHelper.showInfo("urbanDictionaryPleaseWait", sender);
HttpURLConnection url = (HttpURLConnection) new URL("http://urbanscraper.herokuapp.com/define/" + args[0] + ".json").openConnection();
url.setConnectTimeout(10000);
url.setReadTimeout(10000);
url.connect();
if(url.getErrorStream() == null) {
def = convertStreamToString((InputStream)url.getContent());
}
} catch (Exception e) {
LogHelper.showWarnings(sender, "urbanDictionaryError");
return true;
}
Pattern pattern = Pattern.compile("\"definition\":\"(.*?)\",\"example\"");
Matcher matcher = pattern.matcher(def);
if (matcher.find()) {
def = matcher.group(1);
LogHelper.showInfo("urbanDictionaryDef#####[" + def.replaceAll("\\\\r", "\n"), sender);
} else {
LogHelper.showWarnings(sender, "urbanDictionaryError");
}
} else {
Commands.showCommandHelpAndUsage(sender, "cex_urbandictionary", alias);
}
}
return true;
}
|
diff --git a/android-app/src/main/java/com/afzaln/mi_chat/activity/MessagesActivity.java b/android-app/src/main/java/com/afzaln/mi_chat/activity/MessagesActivity.java
index 65d05f2..204e4b9 100644
--- a/android-app/src/main/java/com/afzaln/mi_chat/activity/MessagesActivity.java
+++ b/android-app/src/main/java/com/afzaln/mi_chat/activity/MessagesActivity.java
@@ -1,364 +1,366 @@
package com.afzaln.mi_chat.activity;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import com.afzaln.mi_chat.AlarmReceiver;
import com.afzaln.mi_chat.MessagesCursorAdapter;
import com.afzaln.mi_chat.R;
import com.afzaln.mi_chat.R.id;
import com.afzaln.mi_chat.processor.ProcessorFactory;
import com.afzaln.mi_chat.processor.ResourceProcessor;
import com.afzaln.mi_chat.provider.ProviderContract.MessagesTable;
import com.afzaln.mi_chat.resource.Message;
import com.afzaln.mi_chat.service.ServiceContract;
import com.afzaln.mi_chat.utils.BackoffUtils;
import com.afzaln.mi_chat.utils.NetUtils;
import com.afzaln.mi_chat.view.MessageListView;
import com.afzaln.mi_chat.view.MessageListView.OnSizeChangedListener;
import com.google.analytics.tracking.android.EasyTracker;
import com.loopj.android.http.XmlHttpResponseHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import java.util.Calendar;
public class MessagesActivity extends BaseActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static int mRefreshInterval = BackoffUtils.DEFAULT_REFRESH_INTERVAL;
private static final int MESSAGE_LOADER = 0;
private static final String TAG = MessagesActivity.class.getSimpleName();
private MessagesCursorAdapter mAdapter;
private MessageListView mListView;
private EditText mEditText;
private ImageButton mSubmitButton;
private Menu mMenu;
private AlarmManager mAlarmManager;
private PendingIntent mPendingIntent;
private boolean mManualRefresh = false;
private XmlHttpResponseHandler mLogoutResponseHandler = new XmlHttpResponseHandler() {
@Override
public void onStart() {
// Log.d(TAG, "onStart");
}
@Override
public void onSuccess(Document response) {
// Log.d(TAG, "onSuccess");
Node info = response.getElementsByTagName("info").item(0);
if (info.getAttributes().getNamedItem("type").getNodeValue().equals("logout")) {
NetUtils.getCookieStoreInstance(MessagesActivity.this).clear();
Intent i = new Intent(MessagesActivity.this, LoginActivity.class);
MessagesActivity.this.finish();
startActivity(i);
};
}
@Override
public void onFailure(Throwable e, Document response) {
// Log.d(TAG, "onFailure");
e.printStackTrace();
// Response failed :(
}
@Override
public void onFinish() {
// Log.d(TAG, "onFinish");
// Completed the request (either success or failure)
}
};
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
private TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().equals("")) {
mSubmitButton.setEnabled(false);
} else {
mSubmitButton.setEnabled(true);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawable(null);
getSupportLoaderManager().initLoader(MESSAGE_LOADER, null, this);
initListView();
mEditText = (EditText) findViewById(id.text_editor);
mEditText.addTextChangedListener(textWatcher);
initSubmitButton();
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
mPendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// ViewServer.get(this).addWindow(this);
}
private void initListView() {
mListView = (MessageListView) findViewById(id.messagelist);
mAdapter = new MessagesCursorAdapter(this, null, 0);
mListView.setAdapter(mAdapter);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
}
registerForContextMenu(mListView);
mListView.setOnSizeChangedListener(new OnSizeChangedListener() {
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
mListView.setSelection(mAdapter.getCount() - 1);
}
});
}
private void initSubmitButton() {
mSubmitButton = (ImageButton) findViewById(id.submit_msg);
mSubmitButton.setEnabled(false);
mSubmitButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mAlarmManager.cancel(mPendingIntent);
Bundle bundle = new Bundle();
bundle.putString("message", mEditText.getText().toString());
ResourceProcessor processor = ProcessorFactory.getInstance(MessagesActivity.this).getProcessor(ServiceContract.RESOURCE_TYPE_MESSAGE);
processor.postResource(bundle);
showRefreshProgressBar(true);
mEditText.setText("");
mSubmitButton.setEnabled(false);
}
});
}
@Override
public void onResume() {
super.onResume();
showRefreshProgressBar(true);
// TODO use the Service for this
// IntentService doesn't work with async-http client because you can't run AsyncTask from it
// Use normal Service class maybe
ResourceProcessor processor = ProcessorFactory.getInstance(this).getProcessor(ServiceContract.RESOURCE_TYPE_PAGE);
processor.getResource();
}
@Override
public void onPause() {
super.onPause();
mManualRefresh = false;
mAlarmManager.cancel(mPendingIntent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
menu.findItem(id.action_prefs).setVisible(true);
}
mMenu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
ResourceProcessor processor = ProcessorFactory.getInstance(this).getProcessor(ServiceContract.RESOURCE_TYPE_PAGE);
Intent i;
switch (item.getItemId()) {
case R.id.action_refresh:
setSupportProgressBarIndeterminateVisibility(true);
item.setVisible(false);
mManualRefresh = true;
processor.getResource();
return true;
case R.id.action_prefs:
i = new Intent(MessagesActivity.this, SettingsActivity.class);
startActivity(i);
break;
case R.id.action_clearmessages:
processor.deleteResource();
showRefreshProgressBar(true);
break;
case R.id.action_logout:
NetUtils.postLogout(mLogoutResponseHandler);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
CharSequence message;
switch (item.getItemId()) {
case id.menu_copytext:
message = ((TextView) info.targetView.findViewById(id.message)).getText();
copyToClipboard(message);
return true;
case id.menu_reply:
CharSequence username = ((TextView) info.targetView.findViewById(id.username)).getText();
makeReply(username, mAdapter.getItemViewType(info.position));
default:
return false;
}
}
private void makeReply(CharSequence username, int itemType) {
switch (itemType) {
case Message.NORMAL_TYPE:
mEditText.append("@" + username + " ");
mEditText.setSelection(mEditText.getText().length());
break;
case Message.ACTION_TYPE:
// TODO detect action type
mEditText.setText("!!" + username + " ");
mEditText.setSelection(mEditText.getText().length());
break;
default:
break;
}
}
private void copyToClipboard(CharSequence message) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
@SuppressWarnings("deprecation")
android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (clipboardManager != null) {
clipboardManager.setText(message);
}
} else {
android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (clipboardManager != null) {
@SuppressLint("NewApi")
android.content.ClipData data = android.content.ClipData.newPlainText("message", message);
clipboardManager.setPrimaryClip(data);
}
}
}
@Override
public Loader<Cursor> onCreateLoader(int loaderId, Bundle bundle) {
Log.d(TAG, "Loading messages");
switch (loaderId) {
case MESSAGE_LOADER:
return new CursorLoader(this, MessagesTable.CONTENT_URI, MessagesTable.DISPLAY_COLUMNS, null, null, null);
default:
// invalid id was passed
return null;
}
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
int prevCount = mAdapter.getCount();
boolean isListAtEnd = mListView.getLastVisiblePosition() == (prevCount - 1);
mAdapter.changeCursor(cursor);
showRefreshProgressBar(false);
int newCount = mAdapter.getCount();
boolean newMessagesExist = newCount - prevCount > 0;
// Smooth scroll if the refresh was manual
// or the user is within 10 rows of the new content
if (newMessagesExist && (mManualRefresh || isListAtEnd)) {
if (newCount - mListView.getLastVisiblePosition() > 10) {
mListView.setSelection(newCount - 1);
} else {
mListView.smoothScrollToPosition(newCount - 1);
}
}
- long latestTimestamp = mAdapter.getItemDateTime(newCount - 1);
- mRefreshInterval = BackoffUtils.getRefreshInterval(newMessagesExist, latestTimestamp);
+ if (newCount > 0) {
+ long latestTimestamp = mAdapter.getItemDateTime(newCount - 1);
+ mRefreshInterval = BackoffUtils.getRefreshInterval(newMessagesExist, latestTimestamp);
+ }
mManualRefresh = false;
// Updates on regular intervals on the idea
// that if the app is open, the user must be
// expecting responses in quick succession
mAlarmManager.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + mRefreshInterval, mPendingIntent);
}
/*
* Clears out the adapter's reference to the Cursor. This prevents memory
* leaks.
*/
@Override
public void onLoaderReset(Loader<Cursor> cusror) {
showRefreshProgressBar(false);
mAdapter.changeCursor(null);
}
private void showRefreshProgressBar(boolean value) {
if (mMenu != null) {
mMenu.findItem(id.action_refresh).setVisible(!value);
}
setSupportProgressBarIndeterminateVisibility(value);
}
}
| true | true | public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
int prevCount = mAdapter.getCount();
boolean isListAtEnd = mListView.getLastVisiblePosition() == (prevCount - 1);
mAdapter.changeCursor(cursor);
showRefreshProgressBar(false);
int newCount = mAdapter.getCount();
boolean newMessagesExist = newCount - prevCount > 0;
// Smooth scroll if the refresh was manual
// or the user is within 10 rows of the new content
if (newMessagesExist && (mManualRefresh || isListAtEnd)) {
if (newCount - mListView.getLastVisiblePosition() > 10) {
mListView.setSelection(newCount - 1);
} else {
mListView.smoothScrollToPosition(newCount - 1);
}
}
long latestTimestamp = mAdapter.getItemDateTime(newCount - 1);
mRefreshInterval = BackoffUtils.getRefreshInterval(newMessagesExist, latestTimestamp);
mManualRefresh = false;
// Updates on regular intervals on the idea
// that if the app is open, the user must be
// expecting responses in quick succession
mAlarmManager.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + mRefreshInterval, mPendingIntent);
}
| public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
int prevCount = mAdapter.getCount();
boolean isListAtEnd = mListView.getLastVisiblePosition() == (prevCount - 1);
mAdapter.changeCursor(cursor);
showRefreshProgressBar(false);
int newCount = mAdapter.getCount();
boolean newMessagesExist = newCount - prevCount > 0;
// Smooth scroll if the refresh was manual
// or the user is within 10 rows of the new content
if (newMessagesExist && (mManualRefresh || isListAtEnd)) {
if (newCount - mListView.getLastVisiblePosition() > 10) {
mListView.setSelection(newCount - 1);
} else {
mListView.smoothScrollToPosition(newCount - 1);
}
}
if (newCount > 0) {
long latestTimestamp = mAdapter.getItemDateTime(newCount - 1);
mRefreshInterval = BackoffUtils.getRefreshInterval(newMessagesExist, latestTimestamp);
}
mManualRefresh = false;
// Updates on regular intervals on the idea
// that if the app is open, the user must be
// expecting responses in quick succession
mAlarmManager.set(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + mRefreshInterval, mPendingIntent);
}
|