answer stringlengths 17 10.2M |
|---|
package org.datazup.grouper;
import org.apache.commons.lang3.math.NumberUtils;
import org.datazup.expression.NullObject;
import org.datazup.grouper.exceptions.GroupingException;
import org.datazup.grouper.exceptions.NotValidMetric;
import org.datazup.grouper.utils.GroupUtils;
import org.datazup.utils.Tuple;
import java.util.*;
public abstract class AbstractGrouper implements IGrouper{
protected abstract Number handleMinMetric(String reportName, String fieldKey, Number metricValue) throws Exception;
protected abstract Number handleMaxMetric(String reportName, String fieldKey, Number metricValue) throws Exception;
protected abstract Number handleAvgMetric(String reportName, String fieldKey, Number metricValue) throws Exception;
protected abstract Number handleSumMetric(String reportName, String fieldKey, Number metricValue) throws Exception;
protected abstract Object handleLastMetric(String reportName, String fieldKey, String metricValue) throws Exception;
protected abstract Map<String,String> getRawReport(String reportName) throws Exception;
protected abstract Number handleCountMetric(String reportName, String fieldKey) throws Exception;
@Override
public Map<String, Object> upsert(String reportName, DimensionKey dimensionKey, List<Map<String,String>> metrics) {
List<Tuple<Map<String,String>,Object>> tupleList = dimensionKey.getDimensionValues();
// Map<GroupKey,Map<String,Number>> groupedByDimensionAsKey = new HashMap<>();
Map<String,Object> report = dimensionKey.getDimensionValuesMap();
if (null==report || report.size()==0)
return null;
for (Map<String,String> metric: metrics){
Tuple<String, MetricType> metricType = GroupUtils.parseMetricType(metric.get("name").toString());
// increment field in reportName - hash - in Redis
String fieldKey = GroupUtils.getFieldKey(tupleList);
// Map<String,Object> mapDefinition = JsonUtils.getMapFromJson(metricType.getKey());
Object metricValueObject = dimensionKey.evaluate(metricType.getKey());
if (metricValueObject instanceof NullObject || null==metricValueObject){
// TODO: metricValueObject is sometimes NullObject - what we should do? - do we need to remove and not to count or to count NullObjects as well
continue;
}
fieldKey+=("^"+metric.get("name"));
Object result = null;
try {
result = upsert(reportName, fieldKey, metricType.getValue(), metricValueObject);
} catch (Exception e) {
throw new GroupingException("Problem upserting report: "+reportName+" for field: "+fieldKey+" metric: "+metric.get("name"));
}
if (null==result){
throw new NotValidMetric("Invalid metric upserted result - it shouldn't be null");
}
report.put(GroupUtils.normalizeKey(metric.get("name").toString()), result);
}
return report;
}
private Object upsert(String reportName, String fieldKey, MetricType metricType, Object metricValueObject) throws Exception {
Object result = null;
if (metricType.equals(MetricType.COUNT)){
result = handleCountMetric(reportName, fieldKey);
}
else if (metricType.equals(MetricType.LAST)){
result = handleLastMetric(reportName, fieldKey, (String)metricValueObject);
}
else {
if (!(metricValueObject instanceof Number)){
throw new NotValidMetric("Invalid metric value: "+metricValueObject+" for metric: "+metricType);
}
Number metricValue = (Number)metricValueObject;
switch (metricType) {
case SUM:
result = handleSumMetric(reportName, fieldKey, metricValue);
break;
case AVG:
result = handleAvgMetric(reportName, fieldKey, metricValue);
break;
case MAX:
result = handleMaxMetric(reportName, fieldKey, metricValue);
break;
case MIN:
result = handleMinMetric(reportName, fieldKey, metricValue);
break;
default:
throw new NotValidMetric("Invalid metric: " + metricType);
}
}
return result;
}
@Override
public List<Map<String, Object>> getReportList(String reportName, List<Map<String,String>> dimensions, List<Map<String,String>> metrics) {
List<Map<String, Object>> result = getGroupedSimpleReportList(reportName, dimensions, metrics);
return result;
}
private List<Map<String,Object>> getGroupedSimpleReportList(String reportName, List<Map<String,String>> dimensions, List<Map<String,String>> metrics){
try {
List<Map<String,Object>> result = new ArrayList<>();
Map<String,String> reportMap = getRawReport(reportName);
if (null==reportMap)
throw new GroupingException("There is no report: "+reportName);
Map<GroupKey,Map<String,Number>> groupedByDimensionAsKey = new HashMap<>();
GroupKey dimensionMap = new GroupKey();
Map<String,Number> metricMap = new HashMap<>();
Set<String> processedDimensions = new HashSet<>();
Set<String> processedMetrics = new HashSet<>();
Map<String,Map<String,String>> mapKeyDimensionKeyValue = new HashMap<String,Map<String,String>>();
for (Map<String, String> dimKeyVal: dimensions){
String key = dimKeyVal.get("name");
mapKeyDimensionKeyValue.put(key, dimKeyVal);
}
Map<String,Map<String,String>> mapKeyDimensionKeyValueMetrics = new HashMap<String,Map<String,String>>();
for (Map<String, String> dimKeyVal: metrics){
String key = dimKeyVal.get("name");
mapKeyDimensionKeyValueMetrics.put(key, dimKeyVal);
}
for (String key: reportMap.keySet()) {
String valueStr = reportMap.get(key);
Number metricKeyValueNumber = NumberUtils.createNumber(valueStr);
// have to group by dimension keys
String[] splitted = key.split(":");
for (String splitKey: splitted){
if (splitKey.contains("^")){ // check metrics
String metric = splitKey.substring(1);
Tuple<String, MetricType> metricType = GroupUtils.parseMetricType(metric);
String metricKeyName = metricType.getValue().toString()+"("+metricType.getKey()+")";
if (mapKeyDimensionKeyValueMetrics.containsKey(metricKeyName)) {
processedMetrics.add(metricKeyName);
metricMap.put(metricType.getValue() + GroupUtils.normalizeKey(metricType.getKey()), metricKeyValueNumber);
}
}else if (splitKey.contains("(")){
String functionKey = splitKey.substring(0, splitKey.indexOf("("));
String fieldName = splitKey.substring(splitKey.indexOf("$")+1,splitKey.lastIndexOf("$"));
String fieldValueStr = splitKey.substring(splitKey.lastIndexOf(")")+1);
Object resolvedValue = GroupUtils.resolveValue(fieldValueStr);
String fieldKeyName = GroupUtils.toFunctionKey(functionKey, fieldName);
if (mapKeyDimensionKeyValue.containsKey(fieldKeyName)){
processedDimensions.add(fieldKeyName);
String normalizedKey = GroupUtils.normalizeKey(fieldKeyName);
dimensionMap.put(normalizedKey, resolvedValue);
}
}else {
String fieldKey = splitKey.substring(0, splitKey.lastIndexOf("$") + 1);
String fieldValue = splitKey.substring(splitKey.lastIndexOf("$") + 1);
Object resolvedValue = GroupUtils.resolveValue(fieldValue);
if (mapKeyDimensionKeyValue.containsKey(fieldKey)) {
processedDimensions.add(fieldKey);
String normalizedKey = GroupUtils.normalizeKey(fieldKey);
dimensionMap.put(normalizedKey, resolvedValue);
}
}
}
if (processedDimensions.size()==dimensions.size()){
Map<String,Number> metricInGroupedMap = null;
if (groupedByDimensionAsKey.containsKey(dimensionMap)){
metricInGroupedMap = groupedByDimensionAsKey.get(dimensionMap);
}else{
metricInGroupedMap = new HashMap<>();
}
metricInGroupedMap.putAll(metricMap);
groupedByDimensionAsKey.put(dimensionMap, metricInGroupedMap);
}
metricMap = new HashMap<>();
dimensionMap = new GroupKey();
}
for (GroupKey key: groupedByDimensionAsKey.keySet()){
Map<String,Number> metric = groupedByDimensionAsKey.get(key);
Map<String,Object> obj = new HashMap<>();
obj.putAll(key.getKeyValueMap());
obj.putAll(metric);
result.add(obj);
}
return result;
}catch (Exception e) {
throw new GroupingException("Cannot execute report: "+reportName, e);
}
}
} |
package org.github.etcd.viewer;
import org.apache.wicket.request.mapper.parameter.PageParameters;
public class ConvertUtils {
public static String getEtcdKey(PageParameters pageParameters) {
if (pageParameters.getIndexedCount() == 0) {
return "/";
} else {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < pageParameters.getIndexedCount(); i++) {
sb.append('/');
sb.append(pageParameters.get(i).toString());
}
return sb.toString();
}
}
public static PageParameters getPageParameters(String etcdKey) {
String[] keyParts = etcdKey == null ? new String[0] : etcdKey.split("/");
PageParameters parameters = new PageParameters();
for (String keyPart : keyParts) {
if (!"".equals(keyPart)) {
parameters.set(parameters.getIndexedCount(), keyPart); // add the current non empty part
}
}
if (etcdKey != null && etcdKey.endsWith("/")) {
// add trailing slash
parameters.set(parameters.getIndexedCount(), "");
}
return parameters;
}
/*
public static List<PageParameters> getBreadcrumb(String etcdKey) {
String[] keyParts = etcdKey == null ? new String[0] : etcdKey.split("/");
List<PageParameters> breadcrumb = new ArrayList<>(keyParts.length + 1);
PageParameters parameters = new PageParameters(); // root node
breadcrumb.add(parameters);
for (String keyPart : keyParts) {
if (!"".equals(keyPart)) {
parameters = new PageParameters(parameters); // copy previous params
parameters.set(parameters.getIndexedCount(), keyPart); // add the current part
breadcrumb.add(parameters);
}
}
return breadcrumb;
}
*/
} |
package org.jactiveresource;
import static org.jactiveresource.Inflector.dasherize;
import static org.jactiveresource.Inflector.singularize;
import static org.jactiveresource.Inflector.underscore;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.util.EntityUtils;
import org.jactiveresource.annotation.CollectionName;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.extended.ISO8601DateConverter;
import com.thoughtworks.xstream.core.util.ClassLoaderReference;
import com.thoughtworks.xstream.core.util.CompositeClassLoader;
import com.thoughtworks.xstream.io.xml.XppDriver;
/**
* <h3>Finding Resources</h3>
*
* @version $LastChangedRevision$ <br>
* $LastChangedDate$
* @author $LastChangedBy$
*/
public class ResourceFactory {
private ResourceConnection connection;
private Class<? extends ActiveResource> clazz;
private XStream xstream;
private Log log = LogFactory.getLog(ResourceFactory.class);
public ResourceFactory(ResourceConnection c,
Class<? extends ActiveResource> clazz) {
this.connection = c;
this.clazz = clazz;
xstream = makeXStream();
registerClass(clazz);
log.debug("new ResourceFactory created");
}
public void registerClass(Class c) {
log.trace("registering class " + c.getName());
String xmlname = singularize(dasherize(underscore(c.getSimpleName())));
xstream.alias(xmlname, c);
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
xmlname = dasherize(underscore(field.getName()));
xstream.aliasField(xmlname, c, field.getName());
}
log.trace("processing XStream annotations");
xstream.processAnnotations(c);
}
/**
* create an XStream object suitable for use in parsing Rails flavored XML
*
* @return
*/
private XStream makeXStream() {
log.trace("creating new XStream() object");
RailsConverterLookup rcl = new RailsConverterLookup();
XStream xstream = new XStream(null, new XppDriver(),
new ClassLoaderReference(new CompositeClassLoader()), null,
rcl, null);
// register a special converter so we can parse rails dates
xstream.registerConverter(new ISO8601DateConverter());
return xstream;
}
/**
* Retrieve the resource identified by <code>id</code>, and return a new
* instance of the appropriate object
*
* @param <T>
* @param id
* the primary identifier
* @return a new instance of a subclass of @{link ActiveResource}
* @throws URISyntaxException
* @throws InterruptedException
* @throws IOException
* @throws HttpException
*/
public <T extends ActiveResource> T find(String id) throws HttpException,
IOException, InterruptedException, URISyntaxException {
log.trace("find(id) id=" + id);
return this.<T> fetchOne(getCollectionURL().add(
id + getResourceFormat().extension()));
}
public <T extends ActiveResource> ArrayList<T> findAll()
throws HttpException, IOException, InterruptedException,
URISyntaxException {
URLBuilder url = new URLBuilder(getCollectionName()
+ getResourceFormat().extension());
log.trace("findAll() url=" + url.toString());
return fetchMany(url);
}
public <T extends ActiveResource> ArrayList<T> findAll(
Map<Object, Object> params) throws HttpException, IOException,
InterruptedException, URISyntaxException {
URLBuilder url = new URLBuilder(getCollectionName()
+ getResourceFormat().extension()).addQuery(params);
log.trace("findAll(Map<Object, Object> params) url=" + url.toString());
return fetchMany(url);
}
public <T extends ActiveResource> ArrayList<T> findAll(URLBuilder params)
throws HttpException, IOException, InterruptedException,
URISyntaxException {
URLBuilder url = new URLBuilder(getCollectionName()
+ getResourceFormat().extension()).addQuery(params);
log.trace("findAll(URLBuilder params) url=" + url.toString());
return fetchMany(url);
}
public <T extends ActiveResource> ArrayList<T> findAll(String from)
throws HttpException, IOException, InterruptedException,
URISyntaxException {
URLBuilder url = getCollectionURL().add(
from + getResourceFormat().extension());
log.trace("findAll(String from) from=" + from);
return fetchMany(url);
}
public <T extends ActiveResource> ArrayList<T> findAll(String from,
Map<Object, Object> params) throws HttpException, IOException,
InterruptedException, URISyntaxException {
URLBuilder url = getCollectionURL().add(
from + getResourceFormat().extension()).addQuery(params);
log.trace("findAll(String from, Map<Object, Object> params) from="
+ from);
return fetchMany(url);
}
public <T extends ActiveResource> ArrayList<T> findAll(String from,
URLBuilder params) throws HttpException, IOException,
InterruptedException, URISyntaxException {
URLBuilder url = getCollectionURL().add(
from + getResourceFormat().extension()).addQuery(params);
log.trace("findAll(String from, URLBuilder params) from=" + from);
return fetchMany(url);
}
public boolean exists(String id) {
log.trace("exists(String id) id=" + id);
URLBuilder url = getCollectionURL().add(
id + getResourceFormat().extension());
try {
connection.get(url.toString());
log.trace(url.toString() + " exists");
return true;
} catch (ResourceNotFound e) {
log.trace(url.toString() + " does not exist");
return false;
} catch (HttpException e) {
log.info(url.toString() + " generated an HttpException", e);
return false;
} catch (IOException e) {
log.info(url.toString() + " generated an IOException", e);
return false;
} catch (InterruptedException e) {
log.info(url.toString() + " generated an InterruptedException", e);
return false;
} catch (URISyntaxException e) {
log.info(url.toString() + " generated an URISyntaxException", e);
return false;
}
}
@SuppressWarnings("unchecked")
public <T extends ActiveResource> T instantiate()
throws InstantiationException, IllegalAccessException {
T obj = (T) clazz.newInstance();
obj.setFactory(this);
log.trace("instantiated resource class=" + clazz.toString());
return obj;
}
/**
* create a new resource on the server from a local object
*
* @param r
* @throws ClientProtocolException
* @throws ClientError
* @throws ServerError
* @throws IOException
*/
public boolean create(ActiveResource r) throws ClientProtocolException,
ClientError, ServerError, IOException {
log.trace("trying to create resource of class="
+ r.getClass().toString());
URLBuilder url = new URLBuilder(getCollectionName()
+ getResourceFormat().extension());
String xml = xstream.toXML(r);
HttpResponse response = connection.post(url.toString(), xml,
ResourceFormat.XML.contentType());
String entity = EntityUtils.toString(response.getEntity());
try {
connection.checkHttpStatus(response);
xstream.fromXML(entity, r);
r.setFactory(this);
log.trace("resource created with id=" + r.getId());
return true;
} catch (ResourceInvalid e) {
return false;
}
}
/**
* update the server resource associated with an object
*
* @param r
* @throws URISyntaxException
* @throws HttpException
* @throws IOException
* @throws InterruptedException
*/
public boolean update(ActiveResource r) throws URISyntaxException,
HttpException, IOException, InterruptedException {
log.trace("update class=" + r.getClass().toString() + " id="
+ r.getId());
URLBuilder url = getCollectionURL().add(
r.getId() + getResourceFormat().extension());
String xml = xstream.toXML(r);
HttpResponse response = connection.put(url.toString(), xml,
getResourceFormat().contentType());
// String entity = EntityUtils.toString(response.getEntity());
try {
connection.checkHttpStatus(response);
return true;
} catch (ResourceInvalid e) {
return false;
}
}
/**
* create the resource if it is new, otherwise update it
*
* @param r
* @throws ClientProtocolException
* @throws IOException
* @throws URISyntaxException
* @throws HttpException
* @throws InterruptedException
*/
public boolean save(ActiveResource r) throws ClientProtocolException,
IOException, URISyntaxException, HttpException,
InterruptedException {
if (r.isNew())
return create(r);
else
return update(r);
}
/**
* repopulate a local object with data from the service
*
* @param r
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
public void reload(ActiveResource r) throws HttpException, IOException,
InterruptedException, URISyntaxException {
log.trace("reloading class=" + r.getClass().toString() + " id="
+ r.getId());
URLBuilder url = getCollectionURL().add(
r.getId() + getResourceFormat().extension());
fetchOne(url.toString(), r);
}
/**
* delete a resource
*
* @param r
* @throws ClientError
* @throws ServerError
* @throws ClientProtocolException
* @throws IOException
*/
public void delete(ActiveResource r) throws ClientError, ServerError,
ClientProtocolException, IOException {
URLBuilder url = getCollectionURL().add(
r.getId() + getResourceFormat().extension());
log.trace("deleting class=" + r.getClass().toString() + " id="
+ r.getId());
connection.delete(url.toString());
}
/**
* Create one object from the response of a given url. If your subclass
* wants to create a bunch of cool find methods that each generate a proper
* URL, they can then use this method to get the data and create the objects
* from the response.
*
* @param <T>
* @param url
* @return a new object representing the data returned by the url
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
public <T extends ActiveResource> T fetchOne(Object url)
throws HttpException, IOException, InterruptedException,
URISyntaxException {
return this.<T> deserializeOne(connection.get(url.toString()));
}
/**
* Inflate (or unmarshall) an object from serialized data
*
* @param <T>
* @param data
* a string of serialized data
* @return a new object
* @throws IOException
*/
@SuppressWarnings("unchecked")
public <T extends ActiveResource> T deserializeOne(String data)
throws IOException {
T obj = (T) xstream.fromXML(data);
log.trace("deserializeOne(String data) creates new object class="
+ obj.getClass().toString());
obj.setFactory(this);
return obj;
}
/**
* Update an existing object with data from the given url
*
* @param <T>
* @param url
* @param resource
* the object to update
* @return the updated resource object you passed in
* @throws HttpException
* @throws IOException
* @throws InterruptedException
* @throws URISyntaxException
*/
public <T extends ActiveResource> T fetchOne(String url, T resource)
throws HttpException, IOException, InterruptedException,
URISyntaxException {
return deserializeAndUpdateOne(connection.get(url), resource);
}
/**
* Weasel method to update an existing object with serialized data.
*
* @param <T>
* @param data
* serialized data
* @param resource
* the object to update
* @return the updated resource object you passed in
* @throws IOException
*/
public <T extends ActiveResource> T deserializeAndUpdateOne(String data,
T resource) throws IOException {
xstream.fromXML(data, resource);
log.trace("deserializeAndUpdateOne(String data) updates object of class="
+ resource.getClass().toString() + " id=" + resource.getId());
resource.setFactory(this);
return resource;
}
/**
* Create an array of objects from the response of a given url.
*
* @param <T>
* @param url
* @return an array of objects
* @throws HttpException
* @throws IOException
* @throws InterruptedExceptionInflate
* (or unmarshall) a list of objects from a stream
* @throws URISyntaxException
*/
public <T extends ActiveResource> ArrayList<T> fetchMany(Object url)
throws HttpException, IOException, InterruptedException,
URISyntaxException {
return deserializeMany(connection.getStream(url.toString()));
}
/**
* Inflate (or unmarshall) a list of objects from a stream using XStream.
* This method exhausts and closes the stream.
*
* @param <T>
* @param stream
* an open input stream
* @return a list of objects
* @throws IOException
*/
@SuppressWarnings("unchecked")
public <T extends ActiveResource> ArrayList<T> deserializeMany(
BufferedReader stream) throws IOException {
ObjectInputStream ostream = xstream.createObjectInputStream(stream);
ArrayList<T> list = new ArrayList<T>();
T obj;
while (true) {
try {
obj = (T) ostream.readObject();
obj.setFactory(this);
list.add(obj);
} catch (EOFException e) {
break;
} catch (ClassNotFoundException e) {
// do nothing
}
}
ostream.close();
log.trace("deserializeMany(BufferedReader stream) deserialized "
+ list.size() + " objects");
return list;
}
/**
* by default, we use XML as the format for data exchange
*
* You can override this in your subclasses to change it
*
* @return a resource format
*/
protected ResourceFormat getResourceFormat() {
return ResourceFormat.XML;
}
/**
* figure out the name of the collection of resources generated by the main
* class of this factory.
*
* This method first looks for a CollectionName annotation on the class it
* knows how to create. If there is no annotation, then it guesses based on
* the name of the class.
*
* @return the name of the collection
*/
protected String getCollectionName() {
String name;
CollectionName cn = clazz.getAnnotation(CollectionName.class);
if (cn != null) {
name = cn.value();
} else {
name = Inflector.underscore(clazz.getSimpleName());
name = Inflector.pluralize(name);
}
return name;
}
/**
* create a new URLBuilder object with the base collection present
*
* @return
*/
private URLBuilder getCollectionURL() {
return new URLBuilder(getCollectionName());
}
} |
package org.javarosa.xpath;
import org.javarosa.core.log.FatalException;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IConditionExpr;
import org.javarosa.core.model.condition.pivot.UnpivotableExpressionException;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.expr.FunctionUtils;
import org.javarosa.xpath.expr.XPathBinaryOpExpr;
import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.javarosa.xpath.expr.XPathPathExpr;
import org.javarosa.xpath.expr.XPathUnaryOpExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
public class XPathConditional implements IConditionExpr {
private XPathExpression expr;
public String xpath; //not serialized!
private boolean hasNow; //indicates whether this XpathConditional contains the now() function (used for timestamping)
public XPathConditional(String xpath) throws XPathSyntaxException {
hasNow = xpath.contains("now()");
this.expr = XPathParseTool.parseXPath(xpath);
this.xpath = xpath;
}
public XPathConditional(XPathExpression expr) {
this.expr = expr;
}
@SuppressWarnings("unused")
public XPathConditional() {
}
@Override
public Object evalRaw(DataInstance model, EvaluationContext evalContext) {
try {
return FunctionUtils.unpack(expr.eval(model, evalContext));
} catch (XPathUnsupportedException e) {
if (xpath != null) {
throw new XPathUnsupportedException(xpath);
} else {
String contextMessage = String.format(" Question with id: \'%s\' has issue with condition expression: \'%s\'",
evalContext.getContextRef().getNameLast(), expr);
e.setMessagePrefix(contextMessage);
throw e;
}
}
}
@Override
public boolean eval(DataInstance model, EvaluationContext evalContext) {
return FunctionUtils.toBoolean(evalRaw(model, evalContext));
}
@Override
public String evalReadable(DataInstance model, EvaluationContext evalContext) {
return FunctionUtils.toString(evalRaw(model, evalContext));
}
@Override
public Vector<TreeReference> evalNodeset(DataInstance model, EvaluationContext evalContext) {
if (expr instanceof XPathPathExpr) {
XPathNodeset evaluated = (XPathNodeset)expr.eval(model, evalContext);
return evaluated.getReferences();
} else {
throw new FatalException("evalNodeset: must be path expression");
}
}
/**
* Gather the references that affect the outcome of evaluating this
* conditional expression.
*
* @param originalContextRef context reference pointing to the nodeset
* reference; used for expanding 'current()'
* @return References of which this conditional expression depends on. Used
* for retriggering the expression's evaluation if any of these references
* value or relevancy calculations once.
*/
@Override
public Vector<TreeReference> getExprsTriggers(TreeReference originalContextRef) {
Vector<TreeReference> triggers = new Vector<>();
getExprsTriggersAccumulator(expr, triggers, null, originalContextRef);
return triggers;
}
/**
* Recursive helper to getExprsTriggers with an accumulator trigger vector.
*
* @param expr Current expression we are collecting triggers from
* @param triggers Accumulates the references that this object's
* expression value depends upon.
* @param contextRef Use this updated context; used, for instance,
* when we move into handling predicates
* @param originalContextRef Context reference pointing to the nodeset
* reference; used for expanding 'current()'
*/
private static void getExprsTriggersAccumulator(XPathExpression expr,
Vector<TreeReference> triggers,
TreeReference contextRef,
TreeReference originalContextRef) {
if (expr instanceof XPathPathExpr) {
TreeReference ref = ((XPathPathExpr)expr).getReference();
TreeReference contextualized = ref;
if (ref.getContextType() == TreeReference.CONTEXT_ORIGINAL ||
(contextRef == null && !ref.isAbsolute())) {
// Expr's ref begins with 'current()' or is relative and the
// context ref is missing.
contextualized = ref.contextualize(originalContextRef);
} else if (contextRef != null) {
contextualized = ref.contextualize(contextRef);
}
// find the references this reference depends on inside of predicates
for (int i = 0; i < ref.size(); i++) {
Vector<XPathExpression> predicates = ref.getPredicate(i);
if (predicates == null) {
continue;
}
// contextualizing with ../'s present means we need to
// calculate an offset to grab the appropriate predicates
int basePredIndex = contextualized.size() - ref.size();
TreeReference predicateContext = contextualized.getSubReference(basePredIndex + i);
for (XPathExpression predicate : predicates) {
getExprsTriggersAccumulator(predicate, triggers,
predicateContext, originalContextRef);
}
}
if (!triggers.contains(contextualized)) {
triggers.addElement(contextualized);
}
} else if (expr instanceof XPathBinaryOpExpr) {
getExprsTriggersAccumulator(((XPathBinaryOpExpr)expr).a, triggers,
contextRef, originalContextRef);
getExprsTriggersAccumulator(((XPathBinaryOpExpr)expr).b, triggers,
contextRef, originalContextRef);
} else if (expr instanceof XPathUnaryOpExpr) {
getExprsTriggersAccumulator(((XPathUnaryOpExpr)expr).a, triggers,
contextRef, originalContextRef);
} else if (expr instanceof XPathFuncExpr) {
XPathFuncExpr fx = (XPathFuncExpr)expr;
for (int i = 0; i < fx.args.length; i++)
getExprsTriggersAccumulator(fx.args[i], triggers,
contextRef, originalContextRef);
}
}
@Override
public int hashCode() {
return expr.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof XPathConditional) {
XPathConditional cond = (XPathConditional)o;
return expr.equals(cond.expr);
} else {
return false;
}
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
expr = (XPathExpression)ExtUtil.read(in, new ExtWrapTagged(), pf);
hasNow = ExtUtil.readBool(in);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
ExtUtil.write(out, new ExtWrapTagged(expr));
ExtUtil.writeBool(out, hasNow);
}
@Override
public String toString() {
return "xpath[" + expr.toString() + "]";
}
@Override
public Vector<Object> pivot(DataInstance model, EvaluationContext evalContext) throws UnpivotableExpressionException {
return expr.pivot(model, evalContext);
}
} |
package org.lantern.http;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.lantern.Censored;
import org.lantern.ConnectivityChangedEvent;
import org.lantern.JsonUtils;
import org.lantern.LanternClientConstants;
import org.lantern.LanternFeedback;
import org.lantern.LanternUtils;
import org.lantern.XmppHandler;
import org.lantern.event.Events;
import org.lantern.event.InvitesChangedEvent;
import org.lantern.event.ResetEvent;
import org.lantern.state.Connectivity;
import org.lantern.state.InternalState;
import org.lantern.state.InviteQueue;
import org.lantern.state.JsonModelModifier;
import org.lantern.state.LocationChangedEvent;
import org.lantern.state.Modal;
import org.lantern.state.Mode;
import org.lantern.state.Model;
import org.lantern.state.ModelIo;
import org.lantern.state.ModelService;
import org.lantern.state.Notification.MessageType;
import org.lantern.state.Settings;
import org.lantern.state.SyncPath;
import org.lantern.util.Desktop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class InteractionServlet extends HttpServlet {
private final InternalState internalState;
// XXX DRY: these are also defined in lantern-ui/app/js/constants.js
private enum Interaction {
GET,
GIVE,
INVITE,
CONTINUE,
SETTINGS,
CLOSE,
RESET,
SET,
PROXIEDSITES,
CANCEL,
LANTERNFRIENDS,
RETRY,
REQUESTINVITE,
CONTACT,
ABOUT,
ACCEPT,
DECLINE,
UNEXPECTEDSTATERESET,
UNEXPECTEDSTATEREFRESH,
URL,
EXCEPTION
}
// modals the user can switch to from other modals
private static final HashSet<Modal> switchModals = new HashSet<Modal>();
static {
switchModals.add(Modal.about);
switchModals.add(Modal.contact);
switchModals.add(Modal.settings);
switchModals.add(Modal.proxiedSites);
switchModals.add(Modal.lanternFriends);
}
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* Generated serialization ID.
*/
private static final long serialVersionUID = -8820179746803371322L;
private final ModelService modelService;
private final Model model;
private final ModelIo modelIo;
private final XmppHandler xmppHandler;
private final Censored censored;
private final LanternFeedback lanternFeedback;
private final InviteQueue inviteQueue;
/* only open external urls to these hosts: */
private static final HashSet<String> allowedDomains = new HashSet<String>(
Arrays.asList("google.com", "github.com", "getlantern.org"));
@Inject
public InteractionServlet(final Model model,
final ModelService modelService,
final InternalState internalState,
final ModelIo modelIo, final XmppHandler xmppHandler,
final Censored censored, final LanternFeedback lanternFeedback,
final InviteQueue inviteQueue) {
this.model = model;
this.modelService = modelService;
this.internalState = internalState;
this.modelIo = modelIo;
this.xmppHandler = xmppHandler;
this.censored = censored;
this.lanternFeedback = lanternFeedback;
this.inviteQueue = inviteQueue;
Events.register(this);
}
@Override
protected void doGet(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
@Override
protected void doPost(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
processRequest(req, resp);
}
protected void processRequest(final HttpServletRequest req,
final HttpServletResponse resp) {
LanternUtils.addCSPHeader(resp);
final String uri = req.getRequestURI();
log.debug("Received URI: {}", uri);
final String interactionStr = StringUtils.substringAfterLast(uri, "/");
if (StringUtils.isBlank(interactionStr)) {
log.debug("blank interaction");
HttpUtils.sendClientError(resp, "blank interaction");
return;
}
log.debug("Headers: "+HttpUtils.getRequestHeaders(req));
if (!"XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
log.debug("invalid X-Requested-With");
HttpUtils.sendClientError(resp, "invalid X-Requested-With");
return;
}
if (!model.getXsrfToken().equals(req.getHeader("X-XSRF-TOKEN"))) {
log.debug("X-XSRF-TOKEN wrong: got {} expected {}", req.getHeader("X-XSRF-TOKEN"), model.getXsrfToken());
HttpUtils.sendClientError(resp, "invalid X-XSRF-TOKEN");
return;
}
final int cl = req.getContentLength();
String json = "";
if (cl > 0) {
try {
json = IOUtils.toString(req.getInputStream());
} catch (final IOException e) {
log.error("Could not parse json?");
}
}
log.debug("Body: '"+json+"'");
final Interaction inter =
Interaction.valueOf(interactionStr.toUpperCase());
if (inter == Interaction.CLOSE) {
if (handleClose(json)) {
return;
}
}
if (inter == Interaction.URL) {
final String url = JsonUtils.getValueFromJson("url", json);
final URL url_;
if (!StringUtils.startsWith(url, "http:
!StringUtils.startsWith(url, "https:
log.error("http(s) url expected, got {}", url);
HttpUtils.sendClientError(resp, "http(s) urls only");
return;
}
try {
url_ = new URL(url);
} catch (MalformedURLException e) {
log.error("invalid url: {}", url);
HttpUtils.sendClientError(resp, "invalid url");
return;
}
final String host = url_.getHost();
final String[] hostParts = StringUtils.split(host, ".");
final String domain = hostParts[hostParts.length-2] + "." +
hostParts[hostParts.length-1];
if (!allowedDomains.contains(domain)) {
log.error("domain not allowed: {}", domain);
HttpUtils.sendClientError(resp, "domain not allowed");
return;
}
final String cmd;
if (SystemUtils.IS_OS_MAC_OSX) {
cmd = "open";
} else if (SystemUtils.IS_OS_LINUX) {
cmd = "gnome-open";
} else if (SystemUtils.IS_OS_WINDOWS) {
cmd = "start";
} else {
log.error("unsupported OS");
HttpUtils.sendClientError(resp, "unsupported OS");
return;
}
try {
if (SystemUtils.IS_OS_WINDOWS) {
// On Windows, we have to quote the url to allow for
// e.g. ? and & characters in query string params.
// To quote the url, we supply a dummy first argument,
// since otherwise start treats the first argument as a
// title for the new console window when it's quoted.
LanternUtils.runCommand(cmd, "\"\"", "\""+url+"\"");
} else {
// on OS X and Linux, special characters in the url make
// it through this call without our having to quote them.
LanternUtils.runCommand(cmd, url);
}
} catch (IOException e) {
log.error("open url failed");
HttpUtils.sendClientError(resp, "open url failed");
return;
}
return;
}
final Modal modal = this.model.getModal();
log.debug("processRequest: modal = {}, inter = {}, mode = {}",
modal, inter, this.model.getSettings().getMode());
if (handleExceptionalInteractions(modal, inter, json)) {
return;
}
Modal switchTo = null;
try {
// XXX a map would make this more robust
switchTo = Modal.valueOf(interactionStr);
} catch (IllegalArgumentException e) { }
if (switchTo != null && switchModals.contains(switchTo)) {
if (!switchTo.equals(modal)) {
if (!switchModals.contains(modal)) {
this.internalState.setLastModal(modal);
}
Events.syncModal(model, switchTo);
}
return;
}
switch (modal) {
case welcome:
this.model.getSettings().setMode(Mode.unknown);
switch (inter) {
case GET:
log.debug("Setting get mode");
handleSetModeWelcome(Mode.get);
break;
case GIVE:
log.debug("Setting give mode");
handleSetModeWelcome(Mode.give);
break;
}
break;
case authorize:
log.debug("Processing authorize modal...");
this.internalState.setModalCompleted(Modal.authorize);
this.internalState.advanceModal(null);
break;
case finished:
this.internalState.setCompletedTo(Modal.finished);
switch (inter) {
case CONTINUE:
log.debug("Processing continue");
this.model.setShowVis(true);
Events.sync(SyncPath.SHOWVIS, true);
this.internalState.setModalCompleted(Modal.finished);
this.internalState.advanceModal(null);
break;
case SET:
log.debug("Processing set in finished modal...applying JSON\n{}",
json);
applyJson(json);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case firstInviteReceived:
log.error("Processing invite received...");
break;
case lanternFriends:
this.internalState.setCompletedTo(Modal.lanternFriends);
switch (inter) {
case INVITE:
invite(json);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
break;
case CONTINUE:
/* fall-through */
case CLOSE:
log.debug("Processing continue/close for friends dialog");
this.internalState.setModalCompleted(Modal.lanternFriends);
this.internalState.advanceModal(null);
break;
case ACCEPT:
acceptInvite(json);
Events.syncModal(model, Modal.lanternFriends);
break;
case DECLINE:
declineInvite(json);
Events.syncModal(model, Modal.lanternFriends);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case none:
break;
case notInvited:
switch (inter) {
case RETRY:
Events.syncModal(model, Modal.authorize);
break;
case REQUESTINVITE:
Events.syncModal(model, Modal.requestInvite);
break;
default:
log.error("Unexpected interaction: " + inter);
break;
}
break;
case proxiedSites:
this.internalState.setCompletedTo(Modal.proxiedSites);
switch (inter) {
case CONTINUE:
this.internalState.setModalCompleted(Modal.proxiedSites);
this.internalState.advanceModal(null);
break;
case LANTERNFRIENDS:
log.debug("Processing lanternFriends from proxiedSites");
Events.syncModal(model, Modal.lanternFriends);
break;
case SET:
if (!model.getSettings().isSystemProxy()) {
String msg = "Because you are using manual proxy "
+ "configuration, you may have to restart your "
+ "browser for your updated proxied sites list "
+ "to take effect.";
model.addNotification(msg, MessageType.info, 30);
Events.sync(SyncPath.NOTIFICATIONS,
model.getNotifications());
}
applyJson(json);
break;
case SETTINGS:
log.debug("Processing settings from proxiedSites");
Events.syncModal(model, Modal.settings);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "unexpected interaction for proxied sites");
break;
}
break;
case requestInvite:
log.info("Processing request invite");
switch (inter) {
case CANCEL:
this.internalState.setModalCompleted(Modal.requestInvite);
this.internalState.advanceModal(Modal.notInvited);
break;
case CONTINUE:
applyJson(json);
this.internalState.setModalCompleted(Modal.proxiedSites);
//TODO: need to do something here
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "unexpected interaction for request invite");
break;
}
break;
case requestSent:
log.debug("Process request sent");
break;
case settings:
switch (inter) {
case GET:
log.debug("Setting get mode");
// Only deal with a mode change if the mode has changed!
if (modelService.getMode() == Mode.give) {
// Break this out because it's set in the subsequent
// setMode call
final boolean everGet = model.isEverGetMode();
this.modelService.setMode(Mode.get);
if (!everGet) {
// need to do more setup to switch to get mode from
// give mode
model.setSetupComplete(false);
model.setModal(Modal.proxiedSites);
Events.syncModel(model);
} else {
// This primarily just triggers a setup complete event,
// which triggers connecting to proxies, setting up
// the local system proxy, etc.
model.setSetupComplete(true);
}
}
break;
case GIVE:
log.debug("Setting give mode");
this.modelService.setMode(Mode.give);
break;
case CLOSE:
log.debug("Processing settings close");
Events.syncModal(model, Modal.none);
break;
case SET:
log.debug("Processing set in setting...applying JSON\n{}", json);
applyJson(json);
break;
case RESET:
log.debug("Processing reset");
Events.syncModal(model, Modal.confirmReset);
break;
case PROXIEDSITES:
log.debug("Processing proxied sites in settings");
Events.syncModal(model, Modal.proxiedSites);
break;
case LANTERNFRIENDS:
log.debug("Processing friends in settings");
Events.syncModal(model, Modal.lanternFriends);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
break;
}
break;
case settingsLoadFailure:
switch (inter) {
case RETRY:
modelIo.reload();
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
Events.syncModal(model, model.getModal());
break;
case RESET:
backupSettings();
Events.syncModal(model, Modal.welcome);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
}
break;
case systemProxy:
this.internalState.setCompletedTo(Modal.systemProxy);
switch (inter) {
case CONTINUE:
log.debug("Processing continue in systemProxy", json);
applyJson(json);
Events.sync(SyncPath.SYSTEMPROXY, model.getSettings().isSystemProxy());
this.internalState.setModalCompleted(Modal.systemProxy);
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp, "error setting system proxy pref");
break;
}
break;
case updateAvailable:
switch (inter) {
case CLOSE:
this.internalState.setModalCompleted(Modal.updateAvailable);
this.internalState.advanceModal(null);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
}
break;
case authorizeLater:
log.error("Did not handle interaction {} for modal {}", inter, modal);
break;
case confirmReset:
log.debug("Handling confirm reset interaction");
switch (inter) {
case CANCEL:
log.debug("Processing cancel");
Events.syncModal(model, Modal.settings);
break;
case RESET:
handleReset();
Events.syncModel(this.model);
break;
default:
log.error("Did not handle interaction {} for modal {}", inter, modal);
HttpUtils.sendClientError(resp,
"Interaction not handled for modal: "+modal+
" and interaction: "+inter);
}
break;
case about:
switch (inter) {
case CLOSE:
Events.syncModal(model, this.internalState.getLastModal());
break;
default:
HttpUtils.sendClientError(resp, "invalid interaction "+inter);
}
break;
case contact:
switch(inter) {
case CONTINUE:
String msg;
MessageType messageType;
try {
lanternFeedback.submit(json,
this.model.getProfile().getEmail());
msg = "Thank you for contacting Lantern.";
messageType = MessageType.info;
} catch(Exception e) {
log.error("Error submitting contact form: {}", e);
msg = "Error sending message. Please check your "+
"connection and try again.";
messageType = MessageType.error;
}
model.addNotification(msg, messageType, 30);
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
// fall through because this should be done in both cases:
case CANCEL:
Events.syncModal(model, this.internalState.getLastModal());
break;
default:
HttpUtils.sendClientError(resp, "invalid interaction "+inter);
}
break;
case giveModeForbidden:
if (inter == Interaction.CONTINUE) {
// need to do more setup to switch to get mode from give mode
model.setSetupComplete(false);
this.internalState.advanceModal(null);
Events.syncModal(model, Modal.proxiedSites);
Events.sync(SyncPath.SETUPCOMPLETE, false);
}
break;
default:
log.error("No matching modal for {}", modal);
}
this.modelIo.write();
}
private void backupSettings() {
try {
File backup = new File(Desktop.getDesktopPath(), "lantern-model-backup");
FileUtils.copyFile(LanternClientConstants.DEFAULT_MODEL_FILE, backup);
} catch (final IOException e) {
log.warn("Could not backup model file.");
}
}
private boolean handleExceptionalInteractions(
final Modal modal, final Interaction inter, final String json) {
boolean handled = false;
Map<String, Object> map;
Boolean notify;
switch(inter) {
case EXCEPTION:
handleException(json);
handled = true;
break;
case UNEXPECTEDSTATERESET:
log.debug("Handling unexpected state reset.");
backupSettings();
handleReset();
Events.syncModel(this.model);
// fall through because this should be done in both cases:
case UNEXPECTEDSTATEREFRESH:
try {
map = jsonToMap(json);
} catch(Exception e) {
log.error("Bad json payload in inter '{}': {}", inter, json);
return true;
}
notify = (Boolean)map.get("notify");
if(notify) {
try {
lanternFeedback.submit((String)map.get("report"),
this.model.getProfile().getEmail());
} catch(Exception e) {
log.error("Could not submit unexpected state report: {}\n {}",
e.getMessage(), (String)map.get("report"));
}
}
handled = true;
break;
}
return handled;
}
private void handleException(final String json) {
StringBuilder logMessage = new StringBuilder();
Map<String, Object> map;
try {
map = jsonToMap(json);
} catch(Exception e) {
log.error("UI Exception (unable to parse json)");
return;
}
for(Map.Entry<String, Object> entry : map.entrySet()) {
logMessage.append(
String.format("\t%s: %s\n",
entry.getKey(), entry.getValue()
)
);
}
log.error("UI Exception:\n {}", logMessage.toString());
}
private Map<String, Object> jsonToMap(final String json)
throws JsonParseException, JsonMappingException, IOException {
final ObjectMapper om = new ObjectMapper();
Map<String, Object> map;
map = om.readValue(json, Map.class);
return map;
}
private boolean handleClose(String json) {
if (StringUtils.isBlank(json)) {
return false;
}
final ObjectMapper om = new ObjectMapper();
Map<String, Object> map;
try {
map = om.readValue(json, Map.class);
final String notification = (String) map.get("notification");
model.closeNotification(Integer.parseInt(notification));
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
return true;
} catch (JsonParseException e) {
log.warn("Exception closing notifications {}", e);
} catch (JsonMappingException e) {
log.warn("Exception closing notifications {}", e);
} catch (IOException e) {
log.warn("Exception closing notifications {}", e);
}
return false;
}
private void declineInvite(final String json) {
final String email = JsonUtils.getValueFromJson("email", json);
this.xmppHandler.unsubscribed(email);
}
private void acceptInvite(final String json) {
final String email = JsonUtils.getValueFromJson("email", json);
this.xmppHandler.subscribed(email);
// We also automatically subscribe to them in turn so we know about
// their presence.
this.xmppHandler.subscribe(email);
}
static class Invite {
List<String> invite;
public Invite() {}
public List<String> getInvite() {
return invite;
}
public void setInvite(List<String> invite) {
this.invite = invite;
}
}
private void invite(String json) {
ObjectMapper om = new ObjectMapper();
try {
if (json.length() == 0) {
return;//nobody to invite
}
ArrayList<String> invites = om.readValue(json, ArrayList.class);
inviteQueue.invite(invites);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void handleSetModeWelcome(final Mode mode) {
this.model.setModal(Modal.authorize);
this.internalState.setModalCompleted(Modal.welcome);
this.modelService.setMode(mode);
Events.syncModal(model);
}
private void applyJson(final String json) {
final JsonModelModifier mod = new JsonModelModifier(modelService);
mod.applyJson(json);
}
private void handleReset() {
// This posts the reset event to any classes that need to take action,
// avoiding coupling this class to those classes.
Events.eventBus().post(new ResetEvent());
if (LanternClientConstants.DEFAULT_MODEL_FILE.isFile()) {
try {
FileUtils.forceDelete(LanternClientConstants.DEFAULT_MODEL_FILE);
} catch (final IOException e) {
log.warn("Could not delete model file?");
}
}
final Model base = new Model();
model.setLaunchd(base.isLaunchd());
model.setModal(base.getModal());
model.setNinvites(base.getNinvites());
model.setNodeId(base.getNodeId());
model.setProfile(base.getProfile());
model.setNproxiedSitesMax(base.getNproxiedSitesMax());
//we need to keep clientID and clientSecret, because they are application-level settings
String clientID = model.getSettings().getClientID();
String clientSecret = model.getSettings().getClientSecret();
model.setSettings(base.getSettings());
model.getSettings().setClientID(clientID);
model.getSettings().setClientSecret(clientSecret);
model.setSetupComplete(base.isSetupComplete());
model.setShowVis(base.isShowVis());
model.clearNotifications();
modelIo.write();
}
@Subscribe
public void onLocationChanged(final LocationChangedEvent e) {
Events.sync(SyncPath.LOCATION, e.getNewLocation());
if (censored.isCountryCodeCensored(e.getNewCountry())) {
if (!censored.isCountryCodeCensored(e.getOldCountry())) {
//moving from uncensored to censored
if (model.getSettings().getMode() == Mode.give) {
Events.syncModal(model, Modal.giveModeForbidden);
}
}
}
}
@Subscribe
public void onInvitesChanged(final InvitesChangedEvent e) {
int newInvites = e.getNewInvites();
if (e.getOldInvites() == 0) {
String invitation = newInvites == 1 ? "invitation" : "invitations";
String text = "You now have " + newInvites + " " + invitation;
model.addNotification(text, MessageType.info);
} else if (newInvites == 0 && e.getOldInvites() > 0) {
model.addNotification("You have no more invitations. You will be notified when you receive more.", MessageType.important);
}
Events.sync(SyncPath.NOTIFICATIONS, model.getNotifications());
}
@Subscribe
public void onConnectivityChanged(final ConnectivityChangedEvent e) {
Connectivity connectivity = model.getConnectivity();
if (!e.isConnected()) {
connectivity.setInternet(false);
Events.sync(SyncPath.CONNECTIVITY_INTERNET, false);
return;
}
InetAddress ip = e.getNewIp();
connectivity.setIp(ip.getHostAddress());
connectivity.setInternet(true);
Events.sync(SyncPath.CONNECTIVITY, model.getConnectivity());
Settings set = model.getSettings();
if (set.getMode() == null || set.getMode() == Mode.unknown) {
if (censored.isCensored()) {
set.setMode(Mode.get);
} else {
set.setMode(Mode.give);
}
} else if (set.getMode() == Mode.give && censored.isCensored()) {
// want to set the mode to get now so that we don't mistakenly
// proxy any more than necessary
set.setMode(Mode.get);
log.info("Disconnected; setting giveModeForbidden");
Events.syncModal(model, Modal.giveModeForbidden);
}
}
} |
package org.lightmare.utils;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Utility class to work with {@link Collection} instances
*
* @author Levan Tsinadze
* @since 0.0.81-SNAPSHOT
*/
public abstract class CollectionUtils {
// First index of array
public static final int FIRST_INDEX = 0;
// Second index of array
public static final int SECOND_INDEX = 1;
// Index of not existing data in collection
public static final int NOT_EXISTING_INDEX = -1;
// Length of empty array
public static final int EMPTY_ARRAY_LENGTH = 0;
// Empty array of objects
public static final Object[] EMPTY_ARRAY = {};
/**
* Checks if passed {@link Collection} instance is not empty
*
* @param collection
* @return <code>boolean</code>
*/
public static boolean notEmpty(Collection<?> collection) {
return !collection.isEmpty();
}
/**
* Checks passed {@link Collection} instance on null and on emptiness
* returns true if it is not null and is not empty
*
* @param collection
* @return <code></code>
*/
public static boolean valid(Collection<?> collection) {
return collection != null && !collection.isEmpty();
}
/**
* Checks passed {@link Map} instance on null and emptiness returns true if
* it is not null and is not empty
*
* @param map
* @return <code>boolean</code>
*/
public static boolean valid(Map<?, ?> map) {
return map != null && !map.isEmpty();
}
/**
* Checks if passed {@link Map} instance is null or is empty
*
* @param map
* @return <code>boolean</code>
*/
public static boolean invalid(Map<?, ?> map) {
return !valid(map);
}
/**
* Checks if passed {@link Collection} instance is null or is empty
*
* @param collection
* @return <code>boolean</code>
*/
public static boolean invalid(Collection<?> collection) {
return !valid(collection);
}
/**
* Checks if there is null or empty {@link Collection} instance is passed
* collections
*
* @param collections
* @return <code>boolean</code>
*/
public static boolean invalidAll(Collection<?>... collections) {
return !valid(collections);
}
/**
* Checks if each of passed {@link Map} instances is not null and is not
* empty
*
* @param maps
* @return <code>boolean</code>
*/
public static boolean validAll(Map<?, ?>... maps) {
boolean avaliable = ObjectUtils.notNull(maps);
if (avaliable) {
Map<?, ?> map;
for (int i = FIRST_INDEX; i < maps.length && avaliable; i++) {
map = maps[i];
avaliable = avaliable && valid(map);
}
}
return avaliable;
}
/**
* Checks if passed array of {@link Object}'s instances is not null and is
* not empty
*
* @param array
* @return <code>boolean</code>
*/
public static boolean valid(Object[] array) {
return array != null && array.length > EMPTY_ARRAY_LENGTH;
}
/**
* Checks if passed {@link Object} array is null or is empty
*
* @param array
* @return <code>boolean</code>
*/
public static boolean invalid(Object[] array) {
return !valid(array);
}
/**
* Checks if each of passed {@link Collection} instances is not null and is
* not empty
*
* @param collections
* @return <code>boolean</code>
*/
public static boolean validAll(Collection<?>... collections) {
boolean avaliable = ObjectUtils.notNull(collections);
if (avaliable) {
Collection<?> collection;
for (int i = FIRST_INDEX; i < collections.length && avaliable; i++) {
collection = collections[i];
avaliable = avaliable && valid(collection);
}
}
return avaliable;
}
/**
* * Checks if each of passed {@link Object} array instances is not null and
* is not empty
*
* @param arrays
* @return <code>boolean</code>
*/
public static boolean validAll(Object[]... arrays) {
boolean avaliable = ObjectUtils.notNull(arrays);
if (avaliable) {
Object[] collection;
int length = arrays.length;
for (int i = FIRST_INDEX; i < length && avaliable; i++) {
collection = arrays[i];
avaliable = avaliable && valid(collection);
}
}
return avaliable;
}
/**
* Gets value from passed {@link Map} as other {@link Map} instance
*
* @param key
* @param from
* @return {@link Map}<K,V>
*/
public static <K, V> Map<K, V> getAsMap(Object key, Map<?, ?> from) {
Map<K, V> result;
if (valid(from)) {
Object objectValue = from.get(key);
if (objectValue instanceof Map) {
result = ObjectUtils.cast(objectValue);
} else {
result = null;
}
} else {
result = null;
}
return result;
}
/**
* Gets values from passed {@link Map} as other {@link Map} instance
* recursively by passed keys array
*
* @param from
* @param keys
* @return {@link Map}
*/
public static Map<?, ?> getAsMap(Map<?, ?> from, Object... keys) {
Map<?, ?> result = from;
int length = keys.length;
Object key;
for (int i = FIRST_INDEX; i < length && ObjectUtils.notNull(result); i++) {
key = keys[i];
result = getAsMap(key, result);
}
return result;
}
/**
* Gets values from passed {@link Map} as other {@link Map} instance
* recursively by passed keys array and for first key get value from last
* {@link Map} instance
*
* @param from
* @param keys
* @return <code>V</code>
*/
public static <V> V getSubValue(Map<?, ?> from, Object... keys) {
V value;
int length = keys.length - 1;
Object[] subKeys = new Object[length];
Object key = keys[length];
for (int i = FIRST_INDEX; i < length; i++) {
subKeys[i] = keys[i];
}
Map<?, ?> result = getAsMap(from, subKeys);
if (valid(result)) {
value = ObjectUtils.cast(result.get(key));
} else {
value = null;
}
return value;
}
/**
* Puts passed value to passed {@link Map} instance on passed key of such
* does not contained
*
* @param map
* @param key
* @param value
*/
public static <K, V> void putIfAbscent(Map<K, V> map, K key, V value) {
boolean contained = map.containsKey(key);
if (ObjectUtils.notTrue(contained)) {
map.put(key, value);
}
}
/**
* Creates new {@link Set} from passed {@link Collection} instance
*
* @param collection
* @return {@link Set}<code><T></code>
*/
public static <T> Set<T> translateToSet(Collection<T> collection) {
Set<T> set;
if (valid(collection)) {
set = new HashSet<T>(collection);
} else {
set = Collections.emptySet();
}
return set;
}
/**
* Creates new {@link Set} from passed array instance
*
* @param array
* @return {@link Set}<code><T></code>
*/
public static <T> Set<T> translateToSet(T[] array) {
List<T> collection;
if (valid(array)) {
collection = Arrays.asList(array);
} else {
collection = null;
}
return translateToSet(collection);
}
/**
* Creates new {@link List} from passed {@link Collection} instance
*
* @param collection
* @return {@link List}<code><T></code>
*/
public static <T> List<T> translateToList(Collection<T> collection) {
List<T> list;
if (valid(collection)) {
list = new ArrayList<T>(collection);
} else {
list = Collections.emptyList();
}
return list;
}
/**
* Creates array of generic type <code>T</code> of specific size
*
* @param type
* @param size
* @return <code>T[]</code>
*/
private static <T> T[] toArray(Class<T> type, int size) {
T[] array;
Object arrayObject = Array.newInstance(type, size);
array = ObjectUtils.cast(arrayObject);
return array;
}
/**
* Checks if passed {@link Object} is array
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isArray(final Object data) {
boolean valid = (data instanceof Object[] || data instanceof boolean[]
|| data instanceof byte[] || data instanceof short[]
|| data instanceof char[] || data instanceof int[]
|| data instanceof long[] || data instanceof float[] || data instanceof double[]);
return valid;
}
/**
* Checks if passed {@link Object} is {@link Object} types array
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isObjectArray(final Object data) {
boolean valid = (data instanceof Object[]);
return valid;
}
/**
* Checks if passed {@link Object} is array of primitives
*
* @param data
* @return <code>boolean</code>
*/
public static boolean isPrimitiveArray(final Object data) {
boolean valid = (data instanceof boolean[] || data instanceof byte[]
|| data instanceof short[] || data instanceof char[]
|| data instanceof int[] || data instanceof long[]
|| data instanceof float[] || data instanceof double[]);
return valid;
}
/**
* Converts passed {@link Collection} to array of appropriated {@link Class}
* types
*
* @param collection
* @param type
* @return <code>T[]</code>
*/
public static <T> T[] toArray(Collection<T> collection, Class<T> type) {
T[] array;
if (ObjectUtils.notNull(collection)) {
array = toArray(type, collection.size());
array = collection.toArray(array);
} else {
array = null;
}
return array;
}
/**
* Creates empty array of passed type
*
* @param type
* @return <code>T[]</code>
*/
public static <T> T[] emptyArray(Class<T> type) {
T[] empty = toArray(type, EMPTY_ARRAY_LENGTH);
return empty;
}
/**
* Peaks first element from list
*
* @param list
* @return T
*/
private static <T> T getFirstFromList(List<T> list) {
T value;
if (valid(list)) {
value = list.get(FIRST_INDEX);
} else {
value = null;
}
return value;
}
/**
* Peaks first element from collection
*
* @param collection
* @return T
*/
public static <T> T getFirst(Collection<T> collection) {
T value;
if (valid(collection)) {
if (collection instanceof List) {
value = getFirstFromList(((List<T>) collection));
} else {
Iterator<T> iterator = collection.iterator();
value = iterator.next();
}
} else {
value = null;
}
return value;
}
/**
* Peaks first element from array
*
* @param collection
* @return T
*/
public static <T> T getFirst(T[] values) {
T value;
if (valid(values)) {
value = values[FIRST_INDEX];
} else {
value = null;
}
return value;
}
} |
package lombok.eclipse.agent;
import org.eclipse.jdt.internal.compiler.ast.ASTNode;
import org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.eclipse.jdt.internal.compiler.ast.Expression;
import org.eclipse.jdt.internal.compiler.ast.ForeachStatement;
import org.eclipse.jdt.internal.compiler.ast.ImportReference;
import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration;
import org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.lookup.ArrayBinding;
import org.eclipse.jdt.internal.compiler.lookup.Binding;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.eclipse.jdt.internal.compiler.lookup.ImportBinding;
import org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.eclipse.jdt.internal.compiler.lookup.Scope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.eclipse.jdt.internal.compiler.lookup.TypeConstants;
import org.eclipse.jdt.internal.compiler.lookup.TypeIds;
import lombok.permit.Permit;
import java.lang.reflect.Field;
import static lombok.eclipse.Eclipse.poss;
import static lombok.eclipse.handlers.EclipseHandlerUtil.makeType;
public class PatchVal {
// This is half of the work for 'val' support - the other half is in PatchValEclipse. This half is enough for ecj.
// Creates a copy of the 'initialization' field on a LocalDeclaration if the type of the LocalDeclaration is 'val', because the completion parser will null this out,
// which in turn stops us from inferring the intended type for 'val x = 5;'. We look at the copy.
// Also patches local declaration to not call .resolveType() on the initializer expression if we've already done so (calling it twice causes weird errors),
// and patches .resolve() on LocalDeclaration itself to just-in-time replace the 'val' vartype with the right one.
public static TypeBinding skipResolveInitializerIfAlreadyCalled(Expression expr, BlockScope scope) {
if (expr.resolvedType != null) return expr.resolvedType;
try {
return expr.resolveType(scope);
} catch (NullPointerException e) {
return null;
} catch (ArrayIndexOutOfBoundsException e) {
// This will occur internally due to for example 'val x = mth("X");', where mth takes 2 arguments.
return null;
}
}
public static TypeBinding skipResolveInitializerIfAlreadyCalled2(Expression expr, BlockScope scope, LocalDeclaration decl) {
if (decl != null && LocalDeclaration.class.equals(decl.getClass()) && expr.resolvedType != null) return expr.resolvedType;
try {
return expr.resolveType(scope);
} catch (NullPointerException e) {
return null;
} catch (ArrayIndexOutOfBoundsException e) {
// This will occur internally due to for example 'val x = mth("X");', where mth takes 2 arguments.
return null;
}
}
public static boolean matches(String key, char[] array) {
if (array == null || key.length() != array.length) return false;
for (int i = 0; i < array.length; i++) {
if (key.charAt(i) != array[i]) return false;
}
return true;
}
public static boolean couldBe(ImportBinding[] imports, String key, TypeReference ref) {
String[] keyParts = key.split("\\.");
if (ref instanceof SingleTypeReference) {
char[] token = ((SingleTypeReference)ref).token;
if (!matches(keyParts[keyParts.length - 1], token)) return false;
if (imports == null) return true;
top:
for (ImportBinding ib : imports) {
ImportReference ir = ib.reference;
if (ir == null) continue;
if (ir.isStatic()) continue;
boolean star = ((ir.bits & ASTNode.OnDemand) != 0);
int len = keyParts.length - (star ? 1 : 0);
char[][] t = ir.tokens;
if (len != t.length) continue;
for (int i = 0; i < len; i++) {
if (keyParts[i].length() != t[i].length) continue top;
for (int j = 0; j < t[i].length; j++) if (keyParts[i].charAt(j) != t[i][j]) continue top;
}
return true;
}
return false;
}
if (ref instanceof QualifiedTypeReference) {
char[][] tokens = ((QualifiedTypeReference)ref).tokens;
if (keyParts.length != tokens.length) return false;
for(int i = 0; i < tokens.length; ++i) {
String part = keyParts[i];
char[] token = tokens[i];
if (!matches(part, token)) return false;
}
return true;
}
return false;
}
public static boolean couldBe(ImportReference[] imports, String key, TypeReference ref) {
String[] keyParts = key.split("\\.");
if (ref instanceof SingleTypeReference) {
char[] token = ((SingleTypeReference)ref).token;
if (!matches(keyParts[keyParts.length - 1], token)) return false;
if (imports == null) return true;
top:
for (ImportReference ir : imports) {
if (ir.isStatic()) continue;
boolean star = ((ir.bits & ASTNode.OnDemand) != 0);
int len = keyParts.length - (star ? 1 : 0);
char[][] t = ir.tokens;
if (len != t.length) continue;
for (int i = 0; i < len; i++) {
if (keyParts[i].length() != t[i].length) continue top;
for (int j = 0; j < t[i].length; j++) if (keyParts[i].charAt(j) != t[i][j]) continue top;
}
return true;
}
return false;
}
if (ref instanceof QualifiedTypeReference) {
char[][] tokens = ((QualifiedTypeReference)ref).tokens;
if (keyParts.length != tokens.length) return false;
for(int i = 0; i < tokens.length; ++i) {
String part = keyParts[i];
char[] token = tokens[i];
if (!matches(part, token)) return false;
}
return true;
}
return false;
}
private static boolean is(TypeReference ref, BlockScope scope, String key) {
Scope s = scope.parent;
while (s != null && !(s instanceof CompilationUnitScope)) {
Scope ns = s.parent;
s = ns == s ? null : ns;
}
ImportBinding[] imports = null;
if (s instanceof CompilationUnitScope) imports = ((CompilationUnitScope) s).imports;
if (!couldBe(imports, key, ref)) return false;
TypeBinding resolvedType = ref.resolvedType;
if (resolvedType == null) resolvedType = ref.resolveType(scope, false);
if (resolvedType == null) return false;
char[] pkg = resolvedType.qualifiedPackageName();
char[] nm = resolvedType.qualifiedSourceName();
int pkgFullLength = pkg.length > 0 ? pkg.length + 1: 0;
char[] fullName = new char[pkgFullLength + nm.length];
if(pkg.length > 0) {
System.arraycopy(pkg, 0, fullName, 0, pkg.length);
fullName[pkg.length] = '.';
}
System.arraycopy(nm, 0, fullName, pkgFullLength, nm.length);
return matches(key, fullName);
}
public static final class Reflection {
private static final Field initCopyField, iterableCopyField;
static {
Field a = null, b = null;
try {
a = Permit.getField(LocalDeclaration.class, "$initCopy");
b = Permit.getField(LocalDeclaration.class, "$iterableCopy");
} catch (Throwable t) {
//ignore - no $initCopy exists when running in ecj.
}
initCopyField = a;
iterableCopyField = b;
}
}
public static boolean handleValForLocalDeclaration(LocalDeclaration local, BlockScope scope) {
if (local == null || !LocalDeclaration.class.equals(local.getClass())) return false;
boolean decomponent = false;
boolean val = isVal(local, scope);
boolean var = isVar(local, scope);
if (!(val || var)) return false;
StackTraceElement[] st = new Throwable().getStackTrace();
for (int i = 0; i < st.length - 2 && i < 10; i++) {
if (st[i].getClassName().equals("lombok.launch.PatchFixesHider$Val")) {
boolean valInForStatement = val &&
st[i + 1].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") &&
st[i + 2].getClassName().equals("org.eclipse.jdt.internal.compiler.ast.ForStatement");
if (valInForStatement) return false;
break;
}
}
Expression init = local.initialization;
if (init == null && Reflection.initCopyField != null) {
try {
init = (Expression) Reflection.initCopyField.get(local);
} catch (Exception e) {
// init remains null.
}
}
if (init == null && Reflection.iterableCopyField != null) {
try {
init = (Expression) Reflection.iterableCopyField.get(local);
decomponent = true;
} catch (Exception e) {
// init remains null.
}
}
TypeReference replacement = null;
if (init != null) {
if (init.getClass().getName().equals("org.eclipse.jdt.internal.compiler.ast.LambdaExpression")) {
return false;
}
TypeBinding resolved = null;
try {
resolved = decomponent ? getForEachComponentType(init, scope) : resolveForExpression(init, scope);
} catch (NullPointerException e) {
// This definitely occurs if as part of resolving the initializer expression, a
// lambda expression in it must also be resolved (such as when lambdas are part of
// a ternary expression). This can't result in a viable 'val' matching, so, we
// just go with 'Object' and let the IDE print the appropriate errors.
resolved = null;
}
if (resolved != null) {
try {
replacement = makeType(resolved, local.type, false);
if (!decomponent) init.resolvedType = replacement.resolveType(scope);
} catch (Exception e) {
// Some type thing failed.
}
}
}
if (val) local.modifiers |= ClassFileConstants.AccFinal;
local.annotations = addValAnnotation(local.annotations, local.type, scope);
local.type = replacement != null ? replacement : new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(local.type, 3));
return false;
}
private static boolean isVar(LocalDeclaration local, BlockScope scope) {
return is(local.type, scope, "lombok.experimental.var") || is(local.type, scope, "lombok.var");
}
private static boolean isVal(LocalDeclaration local, BlockScope scope) {
return is(local.type, scope, "lombok.val");
}
public static boolean handleValForForEach(ForeachStatement forEach, BlockScope scope) {
if (forEach.elementVariable == null) return false;
boolean val = isVal(forEach.elementVariable, scope);
boolean var = isVar(forEach.elementVariable, scope);
if (!(val || var)) return false;
TypeBinding component = getForEachComponentType(forEach.collection, scope);
if (component == null) return false;
TypeReference replacement = makeType(component, forEach.elementVariable.type, false);
if (val) forEach.elementVariable.modifiers |= ClassFileConstants.AccFinal;
forEach.elementVariable.annotations = addValAnnotation(forEach.elementVariable.annotations, forEach.elementVariable.type, scope);
forEach.elementVariable.type = replacement != null ? replacement :
new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(forEach.elementVariable.type, 3));
return false;
}
private static Annotation[] addValAnnotation(Annotation[] originals, TypeReference originalRef, BlockScope scope) {
Annotation[] newAnn;
if (originals != null) {
newAnn = new Annotation[1 + originals.length];
System.arraycopy(originals, 0, newAnn, 0, originals.length);
} else {
newAnn = new Annotation[1];
}
newAnn[newAnn.length - 1] = new org.eclipse.jdt.internal.compiler.ast.MarkerAnnotation(originalRef, originalRef.sourceStart);
return newAnn;
}
private static TypeBinding getForEachComponentType(Expression collection, BlockScope scope) {
if (collection != null) {
TypeBinding resolved = collection.resolvedType;
if (resolved == null) resolved = resolveForExpression(collection, scope);
if (resolved == null) return null;
if (resolved.isArrayType()) {
resolved = ((ArrayBinding) resolved).elementsType();
return resolved;
} else if (resolved instanceof ReferenceBinding) {
ReferenceBinding iterableType = ((ReferenceBinding) resolved).findSuperTypeOriginatingFrom(TypeIds.T_JavaLangIterable, false);
TypeBinding[] arguments = null;
if (iterableType != null) switch (iterableType.kind()) {
case Binding.GENERIC_TYPE : // for (T t : Iterable<T>) - in case used inside Iterable itself
arguments = iterableType.typeVariables();
break;
case Binding.PARAMETERIZED_TYPE : // for(E e : Iterable<E>)
arguments = ((ParameterizedTypeBinding)iterableType).arguments;
break;
case Binding.RAW_TYPE : // for(Object e : Iterable)
return null;
}
if (arguments != null && arguments.length == 1) {
return arguments[0];
}
}
}
return null;
}
private static TypeBinding resolveForExpression(Expression collection, BlockScope scope) {
try {
return collection.resolveType(scope);
} catch (ArrayIndexOutOfBoundsException e) {
// Known cause of issues; for example: val e = mth("X"), where mth takes 2 arguments.
return null;
}
}
} |
package org.narwhal.core;
import org.narwhal.annotation.Column;
import org.narwhal.annotation.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* <p>
* The <code>DatabaseConnection</code> represents connection to the relational database.
* This class includes methods for retrieve particular information from the relational databases.
* It automatically maps retrieved result set to the particular entity (java class).
* DatabaseConnection class also manages all resources like database connection,
* prepared statements, result sets etc.
* It also provides basic logging using slf4j library for this case.
* </p>
*
* <p>
* For using this class properly, all mapped classes have to annotate all fields
* that map to the database columns.
*
* Here's an example how to use the annotation:
*
* <p><code>
* public class Person {
* {@literal @}Column("person_id")
* private int id;
* {@literal @}Column("name)
* private String name;
*
* // get and set methods.
* }
* </code></p>
*
* The methods of the <code>DatabaseConnection</code> class use annotations and annotated fields
* to retrieve necessary information from database and to invoke set methods through reflection api.
* </p>
* <p>Here are some examples how DatabaseConnection can be used:</p>
* <p><code>
* DatabaseConnection connection = new DatabaseConnection(new DatabaseInformation(driver, url, username, password));
*
* connection.executeUpdate("UPDATE person SET name = ? WHERE id = ?", name, id);
*
* Person person = connection.executeQuery("SELECT * FROM person WHERE id = ?", Person.class, id);
* </code>
* </p>
*
* @author Miron Aseev
* @see DatabaseInformation
*/
public class DatabaseConnection {
/**
* The <code>MappedClassInformation</code> class keeps all the information about particular class.
* Instance of this class holds data about set methods, constructors and columns name of the database
* tables that mapped to the fields of class.
* */
private static class MappedClassInformation<T> {
private Constructor<T> constructor;
private List<Method> setMethods;
private List<String> columns;
private Map<Character, String> queries;
/**
* Initializes a new instance of the MappedClassInformation class.
* Instance is specified by the value of the Class<T>.
* This constructor tries to retrieve all the necessary information about the class.
*
* @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc.
* @throws NoSuchMethodException If there is no appropriate method to invoke
* */
public MappedClassInformation(Class<T> mappedClass) throws NoSuchMethodException {
List<Field> annotatedFields = getAnnotatedFields(mappedClass, Column.class);
constructor = mappedClass.getConstructor();
setMethods = getSetMethods(mappedClass, annotatedFields);
columns = getColumnsName(annotatedFields);
queries = getQueries(mappedClass);
}
/**
* Returns list of the set methods for corresponding fields of the class.
*
* @return List of set methods.
* */
public List<Method> getSetMethods() {
return setMethods;
}
/**
* Returns list of the columns that have been retrieved from the annotated fields.
*
* @return Columns of the database table.
* */
public List<String> getColumns() {
return columns;
}
/**
* Returns default constructor of the class.
*
* @return Default constructor of the class.
* */
public Constructor<T> getConstructor() {
return constructor;
}
/**
* Retrieves columns name of the database table from the annotated fields.
*
* @param annotatedFields Fields of class that have been annotated by {@literal @}Column annotation.
* @return Columns of the database table.
* */
private List<String> getColumnsName(List<Field> annotatedFields) {
List<String> columns = new ArrayList<String>();
for (Field field : annotatedFields) {
columns.add(field.getAnnotation(Column.class).value());
}
return columns;
}
private <T> String getTableName(Class<T> mappedClass) {
if (mappedClass.isAnnotationPresent(Table.class)) {
return mappedClass.getAnnotation(Table.class).value();
}
throw new IllegalArgumentException("Class " + mappedClass.toString() +
" wasn't annotated by " + Table.class + " annotation");
}
/**
* Retrieves all fields of the class that have been annotated by a particular annotation.
*
* @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc.
* @param annotation Annotation which is used as a condition to filter annotated fields of the class.
* @return Fields that have been annotated by a particular annotation.
* */
private <T, V extends Annotation> List<Field> getAnnotatedFields(Class<T> mappedClass, Class<V> annotation) {
Field[] fields = mappedClass.getDeclaredFields();
List<Field> annotatedFields = new ArrayList<Field>();
for (Field field : fields) {
if (field.isAnnotationPresent(annotation)) {
annotatedFields.add(field);
}
}
return annotatedFields;
}
private String getMethodName(String fieldName, String prefix) {
char[] fieldNameArray = fieldName.toCharArray();
fieldNameArray[0] = Character.toUpperCase(fieldNameArray[0]);
return prefix + new String(fieldNameArray);
}
/**
* Creates and returns name of the set method from string representation of the field.
*
* @param fieldName String representation of class field.
* @return String representation of the set method.
* */
private String getSetMethodName(String fieldName) {
return getMethodName(fieldName, "set");
}
private String getGetMethodName(String fieldName) {
return getMethodName(fieldName, "get");
}
/**
* Returns all set methods from the class. This method uses list of fields
* which is used for retrieving set methods from the class.
*
* @param mappedClass A Class, which is used for retrieving information about constructors, set methods etc.
* @param fields Fields of the class that.
* @return Set methods of the class.
* @throws NoSuchMethodException If there is no appropriate method to invoke.
* */
private <T> List<Method> getSetMethods(Class<T> mappedClass, List<Field> fields) throws NoSuchMethodException {
List<Method> methods = new ArrayList<Method>();
for (Field field : fields) {
String methodName = getSetMethodName(field.getName());
Method method = mappedClass.getMethod(methodName, field.getType());
methods.add(method);
}
return methods;
}
private <T> Map<Character, String> getQueries(Class<T> mappedClass) {
String tableName = getTableName(mappedClass);
Map<Character, String> queries = new HashMap<Character, String>();
String selectQuery = "SELECT (columns) FROM ? WHERE primary_key = ?";
String insertQuery = "INSERT INTO ? (columns) VALUES (columns)";
String deleteQuery = "DELETE FROM ? WHERE primary_key = ?";
String updateQuery = "UPDATE ? SET column = ?, ... WHERE primary_key = ?";
return queries;
}
private String makeSelectQuery() {
StringBuilder builder = new StringBuilder("SELECT (");
for (int i = 0; i < columns.size(); ++i) {
if (i > 0 && i < columns.size() - 1) {
builder.append(',');
}
builder.append(columns.get(i));
}
builder.append(") FROM ? WHERE ? = ?");
return builder.toString();
}
}
/**
* The <code>Cache</code> class is an implementation of the thread-safe cache that
* keeps pair of mapped class and mapped class information correspondingly.
* Actually, this cache is an implementation of the thread safe hash map.
* */
private static class Cache {
private ReadWriteLock lock;
private Lock readLock;
private Lock writeLock;
private Map<Class, MappedClassInformation> entityCache;
/**
* Initializes a new instance of the Cache class.
* */
public Cache() {
lock = new ReentrantReadWriteLock();
readLock = lock.readLock();
writeLock = lock.writeLock();
entityCache = new HashMap<Class, MappedClassInformation>();
}
/**
* Tests whether cache contains a particular key or not.
*
* @param key Key whose presence in this map is to be tested
* @return True if cache contains the key. False otherwise.
* */
public boolean containsKey(Object key) {
readLock.lock();
try {
return entityCache.containsKey(key);
} finally {
readLock.unlock();
}
}
/**
* Associates the specified value with the specified key in the map If the map already
* contained the key in the map then the associated is replaced by new value.
*
* @param mappedClass The value of Class that uses as a key in the map.
* @param classInformation The instance of MappedClassInformation that uses as value in the map.
* @return The value of MappedClassInformation that was associated with a particular key.
* */
public MappedClassInformation put(Class mappedClass, MappedClassInformation classInformation) {
writeLock.lock();
try {
return entityCache.put(mappedClass, classInformation);
} finally {
writeLock.unlock();
}
}
/**
* Returns the value to which the specified key is mapped.
*
* @param key Key whose presence in this map is to be tested
* @return Instance of the MappedClassInformation if the key is presence in the map. Null otherwise.
* */
public MappedClassInformation get(Object key) {
readLock.lock();
try {
return entityCache.get(key);
} finally {
readLock.unlock();
}
}
}
private static Logger logger = LoggerFactory.getLogger(DatabaseConnection.class);
private static Cache cache = new Cache();
private Connection connection;
/**
* Initializes a new instance of the DatabaseConnection class and trying to connect to the database.
* Instance is specified by the value of DatabaseInformation class that keeps all the information needed to connect.
*
* @param databaseInformation instance of {@code DatabaseInformation} class that includes
* all the information for making connection to the database.
* @throws SQLException If any database access problems happened.
* @throws ClassNotFoundException If any problem with register JDBC driver occurs.
* */
public DatabaseConnection(DatabaseInformation databaseInformation) throws ClassNotFoundException, SQLException {
connection = getConnection(databaseInformation);
}
public int persist(Object object) {
"INSERT INTO <Table name> (columns name) VALUES ()"
}
public int remove(Object object) {
}
public <T> T find(Class<T> mappedClass, Object column) {
}
/**
* Builds and executes update SQL query. This method returns the number of rows that have been affected.
*
* Here is an example of usage:
* <p>
* <code>
* connection.executeUpdate("DELETE FROM person WHERE id = ? AND name = ?", id, name);
* </code>
* </p>
*
* As you could see in the example above, this method takes the string representation of SQL update query
* and the arbitrary number of parameters.
* This method combines two parameters, so let's assume that <code>id </code> variable is assigned to 1
* and <code>name</code> variable is assigned to "John".
*
* Then you'll get the following SQL query:
*
* <p>
* <code>
* "DELETE FROM person WHERE id = 1 AND name = 'John'"
* </code>
* </p>
*
* @param query SQL update query (UPDATE, DELETE, INSERT) that can include wildcard symbol - "?".
* @param parameters Arbitrary number of parameters that will be used to substitute wildcard
* symbols in the SQL query parameter.
* @return Number of rows that have been affected.
* @throws SQLException If any database access error happened
* */
public int executeUpdate(String query, Object... parameters) throws SQLException {
PreparedStatement preparedStatement = null;
int result = 0;
try {
try {
preparedStatement = createPreparedStatement(query, parameters);
result = preparedStatement.executeUpdate();
} finally {
close(preparedStatement);
}
} catch (SQLException ex) {
logger.error("Database access error has occurred", ex);
close();
}
return result;
}
public <T> T executeQuery(String query, Class<T> mappedClass, Object... parameters) throws SQLException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
T result = null;
try {
try {
preparedStatement = createPreparedStatement(query, parameters);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
result = createEntity(resultSet, mappedClass);
}
} finally {
close(resultSet);
close(preparedStatement);
}
} catch (SQLException ex) {
logger.error("Database access error has occurred", ex);
close();
}
return result;
}
public <T> List<T> executeQueryForCollection(String query, Class<T> mappedClass, Object... parameters) throws SQLException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<T> collection = new ArrayList<T>();
try {
try {
preparedStatement = createPreparedStatement(query, parameters);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
collection.add(createEntity(resultSet, mappedClass));
}
} finally {
close(resultSet);
close(preparedStatement);
}
} catch (SQLException ex) {
logger.error("Database access error has occurred", ex);
close();
}
return collection;
}
/**
* Makes connection to the database.
*
* @param databaseInformation Instance of the DatabaseInformation class that keeps all the information
* about database connection like database driver's name, url, username and password.
* @throws SQLException If any database access problems happened.
* @throws ClassNotFoundException If any problem with register JDBC driver occurs.
* */
public void connect(DatabaseInformation databaseInformation) throws SQLException, ClassNotFoundException {
connection = getConnection(databaseInformation);
}
/**
* Closes database connection.
*
* @throws SQLException If any database access problems happened.
* */
public void close() throws SQLException {
connection.close();
logger.info("Database connection has been closed");
}
/**
* Tests whether database connection is closed or not.
*
* @return true if database connection is closed. false otherwise
* @throws SQLException If any database access problems happened.
* */
public boolean isClosed() throws SQLException {
return connection.isClosed();
}
/**
* Returns raw connection object.
*
* @return Connection object corresponding to the DatabaseConnection object.
* */
public Connection getRawConnection() {
return connection;
}
/**
* Builds prepared statement. This method takes the string representation of SQL query and the arbitrary
* number of wildcard parameters.
* This method substitutes every wildcard symbol in the SQL query on the corresponding wildcard
* parameter that was placed like the second and subsequent argument after SQL query.
*
* Here's how it works:
* In the example below, there are two wildcard symbols and two wildcard parameters.
*
* <code>
* createPreparedStatement("SELECT * FROM person WHERE id = ? AND name = ?", 1, "John");
* </code>
*
* The query above will be converted to the following representation:
* <code>
* "SELECT * FROM person WHERE id = 1 AND name = 'John'"
* </code>
*
* @param query SQL query that can keep wildcard symbols.
* @param parameters Arbitrary number of parameters that will be used
* to substitute the wildcard symbols in the SQL query.
* @return object of the PreparedStatement class.
* @throws SQLException If any database access problems happened.
* */
private PreparedStatement createPreparedStatement(String query, Object... parameters) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(query);
for (int parameterIndex = 0; parameterIndex < parameters.length; ++parameterIndex) {
preparedStatement.setObject(parameterIndex + 1, parameters[parameterIndex]);
}
return preparedStatement;
}
/**
* Closes result set object
*
* @throws SQLException If any database access problems happened.
* */
private void close(ResultSet resultSet) throws SQLException {
if (resultSet != null) {
resultSet.close();
}
}
/**
* Closes prepared statement object
*
* @throws SQLException If any database access problems happened.
* */
private void close(Statement statement) throws SQLException {
if (statement != null) {
statement.close();
}
}
/**
* Registers JDBC driver and trying to connect to the database.
*
* @param databaseInformation Instance of the DatabaseInformation class that keeps all the information
* about database connection like database driver's name, url, username and password.
* @return A new Connection object associated with particular database.
* @throws SQLException If any database access problems happened.
* @throws ClassNotFoundException If any problem with register JDBC driver occurs.
* */
private Connection getConnection(DatabaseInformation databaseInformation) throws ClassNotFoundException, SQLException {
String url = databaseInformation.getUrl();
String username = databaseInformation.getUsername();
String password = databaseInformation.getPassword();
Class.forName(databaseInformation.getDriver());
connection = DriverManager.getConnection(url, username, password);
logger.info("Database connection has been opened");
return connection;
}
@SuppressWarnings("unchecked")
private <T> T createEntity(ResultSet resultSet, Class<T> mappedClass) throws SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
T result;
if (cache.containsKey(mappedClass)) {
MappedClassInformation<T> classInformation = cache.get(mappedClass);
result = createEntitySupporter(resultSet, classInformation);
} else {
MappedClassInformation<T> classInformation = new MappedClassInformation<T>(mappedClass);
cache.put(mappedClass, classInformation);
result = createEntitySupporter(resultSet, classInformation);
}
return result;
}
private <T> T createEntitySupporter(ResultSet resultSet, MappedClassInformation<T> classInformation) throws IllegalAccessException, InvocationTargetException, InstantiationException, SQLException {
List<Method> setMethods = classInformation.getSetMethods();
List<String> columns = classInformation.getColumns();
T result = classInformation.getConstructor().newInstance();
for (int i = 0; i < columns.size(); ++i) {
Object data = resultSet.getObject(columns.get(i));
setMethods.get(i).invoke(result, data);
}
return result;
}
} |
package org.opencloudb.mpp;
import org.apache.log4j.Logger;
import org.opencloudb.MycatServer;
import org.opencloudb.mpp.tmp.RowDataSorter;
import org.opencloudb.mysql.nio.handler.MultiNodeQueryHandler;
import org.opencloudb.net.mysql.RowDataPacket;
import org.opencloudb.route.RouteResultset;
import org.opencloudb.route.RouteResultsetNode;
import org.opencloudb.server.NonBlockingSession;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
/**
* Data merge service handle data Min,Max,AVG group order by limit
*
* @author wuzhih
*
*/
public class DataMergeService {
private static final Logger LOGGER = Logger
.getLogger(DataMergeService.class);
private RowDataPacketGrouper grouper = null;
private RowDataPacketSorter sorter = null;
private Collection<RowDataPacket> result = new ConcurrentLinkedQueue<RowDataPacket>();
private volatile boolean temniated = false;
// private final Map<String, DataNodeResultInf> dataNodeResultSumMap;
private final Map<String, AtomicReferenceArray<byte[]>> batchedNodeRows;
private final ReentrantLock lock = new ReentrantLock();
private final LinkedTransferQueue<Runnable> jobQueue = new LinkedTransferQueue<Runnable>();
private volatile boolean jobRuninng = false;
private final MultiNodeQueryHandler multiQueryHandler;
private int fieldCount;
private final RouteResultset rrs;
public DataMergeService(MultiNodeQueryHandler queryHandler,
RouteResultset rrs) {
this.rrs = rrs;
this.multiQueryHandler = queryHandler;
batchedNodeRows = new HashMap<String, AtomicReferenceArray<byte[]>>();
for (RouteResultsetNode node : rrs.getNodes()) {
batchedNodeRows.put(node.getName(),
new AtomicReferenceArray<byte[]>(100));
}
}
public RouteResultset getRrs() {
return this.rrs;
}
public void outputMergeResult(final NonBlockingSession session,
final byte[] eof) {
// handle remains batch data
for (Entry<String, AtomicReferenceArray<byte[]>> entry : batchedNodeRows
.entrySet()) {
Runnable job = this.createJob(entry.getKey(), entry.getValue());
if (job != null) {
this.jobQueue.offer(job);
}
}
// add output job
Runnable outPutJob = new Runnable() {
@Override
public void run() {
multiQueryHandler.outputMergeResult(session.getSource(), eof);
}
};
jobQueue.offer(outPutJob);
if (jobRuninng == false && !jobQueue.isEmpty()) {
MycatServer.getInstance().getBusinessExecutor()
.execute(jobQueue.poll());
}
}
/**
* return merged data
*
* @return (i*(offset+size))
*/
public Collection<RowDataPacket> getResults(final byte[] eof) {
Collection<RowDataPacket> tmpResult = result;
if (this.grouper != null) {
tmpResult = grouper.getResult();
grouper = null;
}
if (sorter != null) {
//grouper
if (tmpResult != null) {
Iterator<RowDataPacket> itor = tmpResult.iterator();
while (itor.hasNext()) {
sorter.addRow(itor.next());
itor.remove();
}
}
tmpResult = sorter.getSortedResult();
sorter = null;
}
if(LOGGER.isDebugEnabled())
{
LOGGER.debug("prepare mpp merge result for "+rrs.getStatement());
}
return tmpResult;
}
public void onRowMetaData(Map<String, ColMeta> columToIndx, int fieldCount) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("field metadata inf:"
+ Arrays.toString(columToIndx.entrySet().toArray()));
}
int[] groupColumnIndexs = null;
this.fieldCount = fieldCount;
if (rrs.getGroupByCols() != null) {
groupColumnIndexs = toColumnIndex(rrs.getGroupByCols(),
columToIndx);
}
if (rrs.isHasAggrColumn()) {
List<MergeCol> mergCols = new LinkedList<MergeCol>();
Map<String, Integer> mergeColsMap = rrs.getMergeCols();
if (mergeColsMap != null) {
for (Map.Entry<String, Integer> mergEntry : mergeColsMap
.entrySet()) {
String colName = mergEntry.getKey().toUpperCase();
int type= mergEntry.getValue();
if(MergeCol.MERGE_AVG== type)
{
ColMeta sumColMeta = columToIndx.get(colName + "SUM");
ColMeta countColMeta = columToIndx.get(colName + "COUNT");
if(sumColMeta!=null&&countColMeta!=null)
{
ColMeta colMeta =new ColMeta(sumColMeta.colIndex,countColMeta.colIndex,sumColMeta.getColType()) ;
mergCols.add(new MergeCol(colMeta, mergEntry.getValue()));
}
} else
{
ColMeta colMeta = columToIndx.get(colName);
mergCols.add(new MergeCol(colMeta, mergEntry.getValue()));
}
}
}
// add no alias merg column
for (Map.Entry<String, ColMeta> fieldEntry : columToIndx.entrySet()) {
String colName = fieldEntry.getKey();
int result = MergeCol.tryParseAggCol(colName);
if (result != MergeCol.MERGE_UNSUPPORT
&& result != MergeCol.MERGE_NOMERGE) {
mergCols.add(new MergeCol(fieldEntry.getValue(), result));
}
}
grouper = new RowDataPacketGrouper(groupColumnIndexs,
mergCols.toArray(new MergeCol[mergCols.size()]));
}
if (rrs.getOrderByCols() != null) {
LinkedHashMap<String, Integer> orders = rrs.getOrderByCols();
OrderCol[] orderCols = new OrderCol[orders.size()];
int i = 0;
for (Map.Entry<String, Integer> entry : orders.entrySet()) {
ColMeta colMeta = columToIndx.get(entry.getKey().toUpperCase());
if (colMeta == null) {
throw new java.lang.IllegalArgumentException(
"all columns in order by clause should be in the selected column list!" + entry.getKey().toUpperCase());
}
orderCols[i++] = new OrderCol(columToIndx.get(entry.getKey()
.toUpperCase()), entry.getValue());
}
// sorter = new RowDataPacketSorter(orderCols);
RowDataSorter tmp = new RowDataSorter(orderCols);
tmp.setLimit(rrs.getLimitStart(), rrs.getLimitSize());
sorter = tmp;
} else {
new ConcurrentLinkedQueue<RowDataPacket>();
}
}
/**
* process new record (mysql binary data),if data can output to client
* ,return true
*
* @param dataNode
* DN's name (data from this dataNode)
* @param rowData
* raw data
*/
public boolean onNewRecord(String dataNode, byte[] rowData) {
if (temniated) {
return true;
}
Runnable batchJob = null;
AtomicReferenceArray<byte[]> batchedArray = batchedNodeRows
.get(dataNode);
if (putBatchFailed(rowData, batchedArray)) {
try {
lock.lock();
if (batchedArray.get(batchedArray.length() - 1) != null) {// full
batchJob = createJob(dataNode, batchedArray);
}
putBatchFailed(rowData, batchedArray);
} finally {
lock.unlock();
}
}
if (batchJob != null && jobRuninng == false) {
MycatServer.getInstance().getBusinessExecutor().execute(batchJob);
} else if (batchJob != null) {
jobQueue.offer(batchJob);
}
return false;
}
private boolean handleRowData(String dataNode, byte[] rowData) {
RowDataPacket rowDataPkg = new RowDataPacket(fieldCount);
rowDataPkg.read(rowData);
if (grouper != null) {
grouper.addRow(rowDataPkg);
} else if (sorter != null) {
sorter.addRow(rowDataPkg);
} else {
result.add(rowDataPkg);
}
return false;
}
private Runnable createJob(final String dnName,
AtomicReferenceArray<byte[]> batchedArray) {
final ArrayList<byte[]> rows = new ArrayList<byte[]>(
batchedArray.length());
for (int i = 0; i < batchedArray.length(); i++) {
byte[] val = batchedArray.getAndSet(i, null);
if (val != null) {
rows.add(val);
}
}
if (rows.isEmpty()) {
return null;
}
Runnable job = new Runnable() {
public void run() {
try {
jobRuninng = true;
for (byte[] row : rows) {
if (handleRowData(dnName, row)) {
break;
}
}
// for next job
Runnable newJob = jobQueue.poll();
if (newJob != null) {
MycatServer.getInstance().getBusinessExecutor()
.execute(newJob);
} else {
jobRuninng = false;
}
} catch (Exception e) {
jobRuninng = false;
LOGGER.warn("data Merge error:", e);
}
}
};
return job;
}
private boolean putBatchFailed(byte[] rowData,
AtomicReferenceArray<byte[]> array) {
int len = array.length();
int i = 0;
for (i = 0; i < len; i++) {
if (array.compareAndSet(i, null, rowData))
break;
}
return i == len;
}
private static int[] toColumnIndex(String[] columns,
Map<String, ColMeta> toIndexMap) {
int[] result = new int[columns.length];
ColMeta curColMeta;
for (int i = 0; i < columns.length; i++) {
curColMeta = toIndexMap.get(columns[i].toUpperCase());
if (curColMeta == null) {
throw new java.lang.IllegalArgumentException(
"all columns in group by clause should be in the selected column list.!" + columns[i]);
}
result[i] = curColMeta.colIndex;
}
return result;
}
/**
* release resources
*/
public void clear() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("clear data ");
}
temniated = true;
grouper = null;
sorter = null;
result = null;
jobQueue.clear();
}
}
class DataNodeResultInf {
public RowDataPacket firstRecord;
public RowDataPacket lastRecord;
public int rowCount;
} |
package edu.mit.streamjit.impl.compiler2;
import com.google.common.base.Function;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Primitives;
import com.google.common.reflect.TypeResolver;
import com.google.common.reflect.TypeToken;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.IllegalStreamGraphException;
import edu.mit.streamjit.api.Input;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.Output;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.StreamCompilationFailedException;
import edu.mit.streamjit.api.StreamCompiler;
import edu.mit.streamjit.api.WeightedRoundrobinJoiner;
import edu.mit.streamjit.api.WeightedRoundrobinSplitter;
import edu.mit.streamjit.api.Worker;
import edu.mit.streamjit.impl.blob.Blob;
import edu.mit.streamjit.impl.blob.Blob.Token;
import edu.mit.streamjit.impl.blob.Buffer;
import edu.mit.streamjit.impl.blob.DrainData;
import edu.mit.streamjit.impl.blob.PeekableBuffer;
import edu.mit.streamjit.impl.common.Configuration;
import edu.mit.streamjit.impl.common.Configuration.IntParameter;
import edu.mit.streamjit.impl.common.Configuration.SwitchParameter;
import edu.mit.streamjit.impl.common.InputBufferFactory;
import edu.mit.streamjit.impl.common.OutputBufferFactory;
import edu.mit.streamjit.impl.common.Workers;
import edu.mit.streamjit.impl.compiler.Schedule;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.DrainInstruction;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.ReadInstruction;
import edu.mit.streamjit.impl.compiler2.Compiler2BlobHost.WriteInstruction;
import edu.mit.streamjit.test.Benchmark;
import edu.mit.streamjit.test.Benchmarker;
import edu.mit.streamjit.test.apps.fmradio.FMRadio;
import edu.mit.streamjit.util.CollectionUtils;
import edu.mit.streamjit.util.bytecode.methodhandles.Combinators;
import static edu.mit.streamjit.util.bytecode.methodhandles.LookupUtils.findStatic;
import edu.mit.streamjit.util.Pair;
import edu.mit.streamjit.util.ReflectionUtils;
import edu.mit.streamjit.util.bytecode.Module;
import edu.mit.streamjit.util.bytecode.ModuleClassLoader;
import edu.mit.streamjit.util.bytecode.methodhandles.ProxyFactory;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author Jeffrey Bosboom <jbosboom@csail.mit.edu>
* @since 9/22/2013
*/
public class Compiler2 {
public static final ImmutableSet<Class<?>> REMOVABLE_WORKERS = ImmutableSet.<Class<?>>of(
RoundrobinSplitter.class, WeightedRoundrobinSplitter.class, DuplicateSplitter.class,
RoundrobinJoiner.class, WeightedRoundrobinJoiner.class);
public static final ImmutableSet<IndexFunctionTransformer> INDEX_FUNCTION_TRANSFORMERS = ImmutableSet.<IndexFunctionTransformer>of(
new IdentityIndexFunctionTransformer()
// new ArrayifyIndexFunctionTransformer(false),
// new ArrayifyIndexFunctionTransformer(true)
);
public static final RemovalStrategy REMOVAL_STRATEGY = new BitsetRemovalStrategy();
public static final FusionStrategy FUSION_STRATEGY = new BitsetFusionStrategy();
public static final UnboxingStrategy UNBOXING_STRATEGY = new BitsetUnboxingStrategy();
public static final AllocationStrategy ALLOCATION_STRATEGY = new SubsetBiasAllocationStrategy(8);
public static final StorageStrategy INTERNAL_STORAGE_STRATEGY = new TuneInternalStorageStrategy();
public static final StorageStrategy EXTERNAL_STORAGE_STRATEGY = new TuneExternalStorageStrategy();
public static final SwitchingStrategy SWITCHING_STRATEGY = SwitchingStrategy.tunePerWorker();
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final AtomicInteger PACKAGE_NUMBER = new AtomicInteger();
private final ImmutableSet<Worker<?, ?>> workers;
private final ImmutableSet<ActorArchetype> archetypes;
private final NavigableSet<Actor> actors;
private ImmutableSortedSet<ActorGroup> groups;
private ImmutableSortedSet<WorkerActor> actorsToBeRemoved;
private final Configuration config;
private final int maxNumCores;
private final DrainData initialState;
/**
* If the blob is the entire graph, this is the overall input; else null.
*/
private final Input<?> overallInput;
/**
* If the blob is the entire graph, this is the overall output; else null.
*/
private final Output<?> overallOutput;
private Buffer overallInputBuffer, overallOutputBuffer;
private ImmutableMap<Token, Buffer> precreatedBuffers;
private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap;
private final Set<Storage> storage;
private ImmutableMap<ActorGroup, Integer> externalSchedule;
private final Module module = new Module();
private final ModuleClassLoader classloader = new ModuleClassLoader(module);
private final String packageName = "compiler"+PACKAGE_NUMBER.getAndIncrement();
private ImmutableMap<ActorGroup, Integer> initSchedule;
/**
* For each token in the blob, the number of items live on that edge after
* the init schedule, without regard to removals. (We could recover this
* information from Actor.inputSlots when we're creating drain instructions,
* but storing it simplifies the code and permits asserting we didn't lose
* any items.)
*/
private ImmutableMap<Token, Integer> postInitLiveness;
/**
* ConcreteStorage instances used during initialization (bound into the
* initialization code).
*/
private ImmutableMap<Storage, ConcreteStorage> initStorage;
/**
* ConcreteStorage instances used during the steady-state (bound into the
* steady-state code).
*/
private ImmutableMap<Storage, ConcreteStorage> steadyStateStorage;
/**
* Code to run the initialization schedule. (Initialization is
* single-threaded.)
*/
private MethodHandle initCode;
/**
* Code to run the steady state schedule. The blob host takes care of
* filling/flushing buffers, adjusting storage and the global barrier.
*/
private ImmutableList<MethodHandle> steadyStateCode;
private final List<ReadInstruction> initReadInstructions = new ArrayList<>();
private final List<WriteInstruction> initWriteInstructions = new ArrayList<>();
private final List<Runnable> migrationInstructions = new ArrayList<>();
private final List<ReadInstruction> readInstructions = new ArrayList<>();
private final List<WriteInstruction> writeInstructions = new ArrayList<>();
private final List<DrainInstruction> drainInstructions = new ArrayList<>();
public Compiler2(Set<Worker<?, ?>> workers, Configuration config, int maxNumCores, DrainData initialState, Input<?> input, Output<?> output) {
this.workers = ImmutableSet.copyOf(workers);
Map<Class<?>, ActorArchetype> archetypesBuilder = new HashMap<>();
Map<Worker<?, ?>, WorkerActor> workerActors = new HashMap<>();
for (Worker<?, ?> w : workers) {
@SuppressWarnings("unchecked")
Class<? extends Worker<?, ?>> wClass = (Class<? extends Worker<?, ?>>)w.getClass();
if (archetypesBuilder.get(wClass) == null)
archetypesBuilder.put(wClass, new ActorArchetype(wClass, module));
WorkerActor actor = new WorkerActor(w, archetypesBuilder.get(wClass));
workerActors.put(w, actor);
}
this.archetypes = ImmutableSet.copyOf(archetypesBuilder.values());
Map<Token, TokenActor> tokenActors = new HashMap<>();
Table<Actor, Actor, Storage> storageTable = HashBasedTable.create();
int[] inputTokenId = new int[]{Integer.MIN_VALUE}, outputTokenId = new int[]{Integer.MAX_VALUE};
for (WorkerActor a : workerActors.values())
a.connect(ImmutableMap.copyOf(workerActors), tokenActors, storageTable, inputTokenId, outputTokenId);
this.actors = new TreeSet<>();
this.actors.addAll(workerActors.values());
this.actors.addAll(tokenActors.values());
this.storage = new HashSet<>(storageTable.values());
this.config = config;
this.maxNumCores = maxNumCores;
this.initialState = initialState;
ImmutableMap.Builder<Token, ImmutableList<Object>> initialStateDataMapBuilder = ImmutableMap.builder();
if (initialState != null) {
for (Table.Cell<Actor, Actor, Storage> cell : storageTable.cellSet()) {
Token tok;
if (cell.getRowKey() instanceof TokenActor)
tok = ((TokenActor)cell.getRowKey()).token();
else if (cell.getColumnKey() instanceof TokenActor)
tok = ((TokenActor)cell.getColumnKey()).token();
else
tok = new Token(((WorkerActor)cell.getRowKey()).worker(),
((WorkerActor)cell.getColumnKey()).worker());
ImmutableList<Object> data = initialState.getData(tok);
if (data != null && !data.isEmpty()) {
initialStateDataMapBuilder.put(tok, data);
cell.getValue().initialData().add(Pair.make(data, MethodHandles.identity(int.class)));
}
}
}
this.initialStateDataMap = initialStateDataMapBuilder.build();
this.overallInput = input;
this.overallOutput = output;
}
public Blob compile() {
findRemovals();
fuse();
schedule();
// identityRemoval();
splitterRemoval();
joinerRemoval();
inferTypes();
unbox();
generateArchetypalCode();
createBuffers();
createInitCode();
createSteadyStateCode();
return instantiateBlob();
}
private void findRemovals() {
ImmutableSortedSet.Builder<WorkerActor> builder = ImmutableSortedSet.naturalOrder();
next_worker: for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) {
if (!REMOVABLE_WORKERS.contains(a.worker().getClass())) continue;
for (Storage s : a.outputs())
if (!s.initialData().isEmpty())
continue next_worker;
for (Storage s : a.inputs())
if (!s.initialData().isEmpty())
continue next_worker;
if (!REMOVAL_STRATEGY.remove(a, config)) continue;
builder.add(a);
}
this.actorsToBeRemoved = builder.build();
}
/**
* Fuses actors into groups as directed by the configuration.
*/
private void fuse() {
List<ActorGroup> actorGroups = new ArrayList<>();
for (Actor a : actors)
actorGroups.add(ActorGroup.of(a));
//Fuse as much as possible.
just_fused: do {
try_fuse: for (Iterator<ActorGroup> it = actorGroups.iterator(); it.hasNext();) {
ActorGroup g = it.next();
if (g.isTokenGroup())
continue try_fuse;
for (ActorGroup pg : g.predecessorGroups())
if (pg.isTokenGroup())
continue try_fuse;
if (g.isPeeking() || g.predecessorGroups().size() > 1)
continue try_fuse;
for (Storage s : g.inputs())
if (!s.initialData().isEmpty())
continue try_fuse;
//We are assuming FusionStrategies are all happy to work
//group-by-group. If later we want to make all decisions at
//once, we'll refactor existing FusionStrategies to inherit from
//a base class containing this loop.
if (!FUSION_STRATEGY.fuseUpward(g, config))
continue try_fuse;
ActorGroup gpred = Iterables.getOnlyElement(g.predecessorGroups());
ActorGroup fusedGroup = ActorGroup.fuse(g, gpred);
it.remove();
actorGroups.remove(gpred);
actorGroups.add(fusedGroup);
continue just_fused;
}
break;
} while (true);
this.groups = ImmutableSortedSet.copyOf(actorGroups);
Boolean reportFusion = (Boolean)config.getExtraData("reportFusion");
if (reportFusion != null && reportFusion) {
for (ActorGroup g : groups) {
if (g.isTokenGroup()) continue;
List<Integer> list = new ArrayList<>();
for (Actor a : g.actors())
list.add(a.id());
System.out.println(com.google.common.base.Joiner.on(' ').join(list));
}
System.out.flush();
System.exit(0);
}
}
/**
* Computes each group's internal schedule and the external schedule.
*/
private void schedule() {
for (ActorGroup g : groups)
internalSchedule(g);
externalSchedule();
initSchedule();
}
private void externalSchedule() {
Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(groups);
for (ActorGroup g : groups) {
for (Storage e : g.outputs()) {
Actor upstream = Iterables.getOnlyElement(e.upstream());
Actor downstream = Iterables.getOnlyElement(e.downstream());
ActorGroup other = downstream.group();
int upstreamAdjust = g.schedule().get(upstream);
int downstreamAdjust = other.schedule().get(downstream);
scheduleBuilder.connect(g, other)
.push(e.push() * upstreamAdjust)
.pop(e.pop() * downstreamAdjust)
.peek(e.peek() * downstreamAdjust)
.bufferExactly(0);
}
}
int multiplier = config.getParameter("multiplier", IntParameter.class).getValue();
scheduleBuilder.multiply(multiplier);
try {
externalSchedule = scheduleBuilder.build().getSchedule();
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find external schedule; mult = "+multiplier, ex);
}
}
/**
* Computes the internal schedule for the given group.
*/
private void internalSchedule(ActorGroup g) {
Schedule.Builder<Actor> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(g.actors());
for (Actor a : g.actors())
scheduleBuilder.executeAtLeast(a, 1);
for (Storage s : g.internalEdges()) {
scheduleBuilder.connect(Iterables.getOnlyElement(s.upstream()), Iterables.getOnlyElement(s.downstream()))
.push(s.push())
.pop(s.pop())
.peek(s.peek())
.bufferExactly(0);
}
try {
Schedule<Actor> schedule = scheduleBuilder.build();
g.setSchedule(schedule.getSchedule());
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find internal schedule for group "+g+"\n"+scheduleBuilder.toString(), ex);
}
}
private void initSchedule() {
Schedule.Builder<ActorGroup> scheduleBuilder = Schedule.builder();
scheduleBuilder.addAll(groups);
for (Storage s : storage) {
if (s.isInternal()) continue;
Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream());
int upstreamAdjust = upstream.group().schedule().get(upstream);
int downstreamAdjust = downstream.group().schedule().get(downstream);
int throughput, excessPeeks;
//TODO: avoid double-buffering token groups here?
if (actorsToBeRemoved.contains(downstream) && false)
throughput = excessPeeks = 0;
else {
throughput = s.push() * upstreamAdjust * externalSchedule.get(upstream.group());
excessPeeks = Math.max(s.peek() - s.pop(), 0);
}
int initialDataSize = Iterables.getOnlyElement(s.initialData(), new Pair<>(ImmutableList.<Object>of(), (MethodHandle)null)).first.size();
scheduleBuilder.connect(upstream.group(), downstream.group())
.push(s.push() * upstreamAdjust)
.pop(s.pop() * downstreamAdjust)
.peek(s.peek() * downstreamAdjust)
.bufferAtLeast(throughput + excessPeeks - initialDataSize);
}
IntParameter initBufferingCostParam = config.getParameter("InitBufferingCost", IntParameter.class);
int initBufferCost = initBufferingCostParam.getValue(), fireCost = initBufferingCostParam.getMax() - initBufferCost;
scheduleBuilder.costs(fireCost, initBufferCost);
try {
Schedule<ActorGroup> schedule = scheduleBuilder.build();
this.initSchedule = schedule.getSchedule();
} catch (Schedule.ScheduleException ex) {
throw new StreamCompilationFailedException("couldn't find init schedule", ex);
}
ImmutableMap.Builder<Token, Integer> postInitLivenessBuilder = ImmutableMap.builder();
for (Storage s : storage) {
if (s.isInternal()) continue;
Actor upstream = Iterables.getOnlyElement(s.upstream()), downstream = Iterables.getOnlyElement(s.downstream());
int upstreamExecutions = upstream.group().schedule().get(upstream) * initSchedule.get(upstream.group());
int downstreamExecutions = downstream.group().schedule().get(downstream) * initSchedule.get(downstream.group());
int liveItems = s.push() * upstreamExecutions - s.pop() * downstreamExecutions + s.initialDataIndices().size();
assert liveItems >= 0 : s;
int index = downstream.inputs().indexOf(s);
assert index != -1;
Token token;
if (downstream instanceof WorkerActor) {
Worker<?, ?> w = ((WorkerActor)downstream).worker();
token = downstream.id() == 0 ? Token.createOverallInputToken(w) :
new Token(Workers.getPredecessors(w).get(index), w);
} else
token = ((TokenActor)downstream).token();
for (int i = 0; i < liveItems; ++i)
downstream.inputSlots(index).add(StorageSlot.live(token, i));
postInitLivenessBuilder.put(token, liveItems);
}
this.postInitLiveness = postInitLivenessBuilder.build();
int initScheduleSize = 0;
for (int i : initSchedule.values())
initScheduleSize += i;
// System.out.println("init schedule size "+initScheduleSize);
int totalBuffering = 0;
for (int i : postInitLiveness.values())
totalBuffering += i;
// System.out.println("total items buffered "+totalBuffering);
}
private void splitterRemoval() {
for (WorkerActor splitter : actorsToBeRemoved) {
if (!(splitter.worker() instanceof Splitter)) continue;
List<MethodHandle> transfers = splitterTransferFunctions(splitter);
Storage survivor = Iterables.getOnlyElement(splitter.inputs());
//Remove all instances of splitter, not just the first.
survivor.downstream().removeAll(ImmutableList.of(splitter));
MethodHandle Sin = Iterables.getOnlyElement(splitter.inputIndexFunctions());
List<StorageSlot> drainInfo = splitter.inputSlots(0);
for (int i = 0; i < splitter.outputs().size(); ++i) {
Storage victim = splitter.outputs().get(i);
MethodHandle t = transfers.get(i);
for (Actor a : victim.downstream()) {
List<Storage> inputs = a.inputs();
List<MethodHandle> inputIndices = a.inputIndexFunctions();
for (int j = 0; j < inputs.size(); ++j)
if (inputs.get(j).equals(victim)) {
inputs.set(j, survivor);
survivor.downstream().add(a);
inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), t));
if (splitter.push(i) > 0)
for (int idx = 0, q = a.translateInputIndex(j, idx); q < drainInfo.size(); ++idx, q = a.translateInputIndex(j, idx)) {
a.inputSlots(j).add(drainInfo.get(q));
drainInfo.set(q, drainInfo.get(q).duplify());
}
inputIndices.set(j, MethodHandles.filterReturnValue(inputIndices.get(j), Sin));
}
}
for (Pair<ImmutableList<Object>, MethodHandle> item : victim.initialData())
survivor.initialData().add(new Pair<>(item.first, MethodHandles.filterReturnValue(item.second, t)));
storage.remove(victim);
}
removeActor(splitter);
assert consistency();
}
}
/**
* Returns transfer functions for the given splitter.
*
* A splitter has one transfer function for each output that maps logical
* output indices to logical input indices (representing the splitter's
* distribution pattern).
* @param a an actor
* @return transfer functions, or null
*/
private List<MethodHandle> splitterTransferFunctions(WorkerActor a) {
assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass();
if (a.worker() instanceof RoundrobinSplitter || a.worker() instanceof WeightedRoundrobinSplitter) {
int[] weights = new int[a.outputs().size()];
for (int i = 0; i < weights.length; ++i)
weights[i] = a.push(i);
return roundrobinTransferFunctions(weights);
} else if (a.worker() instanceof DuplicateSplitter) {
return Collections.nCopies(a.outputs().size(), MethodHandles.identity(int.class));
} else
throw new AssertionError();
}
private void joinerRemoval() {
for (WorkerActor joiner : actorsToBeRemoved) {
if (!(joiner.worker() instanceof Joiner)) continue;
List<MethodHandle> transfers = joinerTransferFunctions(joiner);
Storage survivor = Iterables.getOnlyElement(joiner.outputs());
//Remove all instances of joiner, not just the first.
survivor.upstream().removeAll(ImmutableList.of(joiner));
MethodHandle Jout = Iterables.getOnlyElement(joiner.outputIndexFunctions());
for (int i = 0; i < joiner.inputs().size(); ++i) {
Storage victim = joiner.inputs().get(i);
MethodHandle t = transfers.get(i);
MethodHandle t2 = MethodHandles.filterReturnValue(t, Jout);
for (Actor a : victim.upstream()) {
List<Storage> outputs = a.outputs();
List<MethodHandle> outputIndices = a.outputIndexFunctions();
for (int j = 0; j < outputs.size(); ++j)
if (outputs.get(j).equals(victim)) {
outputs.set(j, survivor);
outputIndices.set(j, MethodHandles.filterReturnValue(outputIndices.get(j), t2));
survivor.upstream().add(a);
}
}
for (Pair<ImmutableList<Object>, MethodHandle> item : victim.initialData())
survivor.initialData().add(new Pair<>(item.first, MethodHandles.filterReturnValue(item.second, t2)));
storage.remove(victim);
}
//Linearize drain info from the joiner's inputs.
int maxIdx = 0;
for (int i = 0; i < joiner.inputs().size(); ++i) {
MethodHandle t = transfers.get(i);
for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx)
try {
maxIdx = Math.max(maxIdx, (int)t.invokeExact(joiner.inputSlots(i).size()-1));
} catch (Throwable ex) {
throw new AssertionError("Can't happen! transfer function threw?", ex);
}
}
List<StorageSlot> linearizedInput = new ArrayList<>(Collections.nCopies(maxIdx+1, StorageSlot.hole()));
for (int i = 0; i < joiner.inputs().size(); ++i) {
MethodHandle t = transfers.get(i);
for (int idx = 0; idx < joiner.inputSlots(i).size(); ++idx)
try {
linearizedInput.set((int)t.invokeExact(idx), joiner.inputSlots(i).get(idx));
} catch (Throwable ex) {
throw new AssertionError("Can't happen! transfer function threw?", ex);
}
joiner.inputSlots(i).clear();
joiner.inputSlots(i).trimToSize();
}
if (!linearizedInput.isEmpty()) {
for (Actor a : survivor.downstream())
for (int j = 0; j < a.inputs().size(); ++j)
if (a.inputs().get(j).equals(survivor))
for (int idx = 0, q = a.translateInputIndex(j, idx); q < linearizedInput.size(); ++idx, q = a.translateInputIndex(j, idx)) {
StorageSlot slot = linearizedInput.get(q);
a.inputSlots(j).add(slot);
linearizedInput.set(q, slot.duplify());
}
}
// System.out.println("removed "+joiner);
removeActor(joiner);
assert consistency();
}
}
private List<MethodHandle> joinerTransferFunctions(WorkerActor a) {
assert REMOVABLE_WORKERS.contains(a.worker().getClass()) : a.worker().getClass();
if (a.worker() instanceof RoundrobinJoiner || a.worker() instanceof WeightedRoundrobinJoiner) {
int[] weights = new int[a.inputs().size()];
for (int i = 0; i < weights.length; ++i)
weights[i] = a.pop(i);
return roundrobinTransferFunctions(weights);
} else
throw new AssertionError();
}
private List<MethodHandle> roundrobinTransferFunctions(int[] weights) {
int[] weightPrefixSum = new int[weights.length + 1];
for (int i = 1; i < weightPrefixSum.length; ++i)
weightPrefixSum[i] = weightPrefixSum[i-1] + weights[i-1];
int N = weightPrefixSum[weightPrefixSum.length-1];
//t_x(i) = N(i/w[x]) + sum_0_x-1{w} + (i mod w[x])
//where the first two terms select a "window" and the third is the
//index into that window.
ImmutableList.Builder<MethodHandle> transfer = ImmutableList.builder();
for (int x = 0; x < weights.length; ++x)
transfer.add(MethodHandles.insertArguments(ROUNDROBIN_TRANSFER_FUNCTION, 0, weights[x], weightPrefixSum[x], N));
return transfer.build();
}
private final MethodHandle ROUNDROBIN_TRANSFER_FUNCTION = findStatic(LOOKUP, "_roundrobinTransferFunction");
//TODO: build this directly out of MethodHandles?
private static int _roundrobinTransferFunction(int weight, int prefixSum, int N, int i) {
//assumes nonnegative indices
return N*(i/weight) + prefixSum + (i % weight);
}
/**
* Removes an Actor from this compiler's data structures. The Actor should
* already have been unlinked from the graph (no incoming edges); this takes
* care of removing it from the actors set, its actor group (possibly
* removing the group if it's now empty), and the schedule.
* @param a the actor to remove
*/
private void removeActor(Actor a) {
assert actors.contains(a) : a;
actors.remove(a);
ActorGroup g = a.group();
g.remove(a);
if (g.actors().isEmpty()) {
groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g)));
externalSchedule = ImmutableMap.copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
initSchedule = ImmutableMap.copyOf(Maps.difference(initSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
}
}
private boolean consistency() {
Set<Storage> usedStorage = new HashSet<>();
for (Actor a : actors) {
usedStorage.addAll(a.inputs());
usedStorage.addAll(a.outputs());
}
if (!storage.equals(usedStorage)) {
Set<Storage> unused = Sets.difference(storage, usedStorage);
Set<Storage> untracked = Sets.difference(usedStorage, storage);
throw new AssertionError(String.format("inconsistent storage:%n\tunused: %s%n\tuntracked:%s%n", unused, untracked));
}
return true;
}
//<editor-fold defaultstate="collapsed" desc="Unimplemented optimization stuff">
// /**
// * Removes Identity instances from the graph, unless doing so would make the
// * graph empty.
// */
// private void identityRemoval() {
// //TODO: remove from group, possibly removing the group if it becomes empty
// for (Iterator<Actor> iter = actors.iterator(); iter.hasNext();) {
// if (actors.size() == 1)
// break;
// Actor actor = iter.next();
// if (!actor.archetype().workerClass().equals(Identity.class))
// continue;
// iter.remove();
// assert actor.predecessors().size() == 1 && actor.successors().size() == 1;
// Object upstream = actor.predecessors().get(0), downstream = actor.successors().get(0);
// if (upstream instanceof Actor)
// replace(((Actor)upstream).successors(), actor, downstream);
// if (downstream instanceof Actor)
// replace(((Actor)downstream).predecessors(), actor, upstream);
// //No index function changes required for Identity actors.
// private static int replace(List<Object> list, Object target, Object replacement) {
// int replacements = 0;
// for (int i = 0; i < list.size(); ++i)
// if (Objects.equals(list.get(0), target)) {
// list.set(i, replacement);
// ++replacements;
// return replacements;
//</editor-fold>
/**
* Performs type inference to replace type variables with concrete types.
* For now, we only care about wrapper types.
*/
public void inferTypes() {
while (inferUpward() || inferDownward());
}
private boolean inferUpward() {
boolean changed = false;
//For each storage, if a reader's input type is a final type, all
//writers' output types must be that final type. (Wrappers are final,
//so this works for wrappers, and maybe detects errors related to other
//types.)
for (Storage s : storage) {
Set<TypeToken<?>> finalInputTypes = new HashSet<>();
for (Actor a : s.downstream())
if (Modifier.isFinal(a.inputType().getRawType().getModifiers()))
finalInputTypes.add(a.inputType());
if (finalInputTypes.isEmpty()) continue;
if (finalInputTypes.size() > 1)
throw new IllegalStreamGraphException("Type mismatch among readers: "+s.downstream());
TypeToken<?> inputType = finalInputTypes.iterator().next();
for (Actor a : s.upstream())
if (!a.outputType().equals(inputType)) {
TypeToken<?> oldOutputType = a.outputType();
TypeResolver resolver = new TypeResolver().where(oldOutputType.getType(), inputType.getType());
TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType()));
if (!oldOutputType.equals(newOutputType)) {
a.setOutputType(newOutputType);
// System.out.println("inferUpward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType);
changed = true;
}
TypeToken<?> oldInputType = a.inputType();
TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType()));
if (!oldInputType.equals(newInputType)) {
a.setInputType(newInputType);
// System.out.println("inferUpward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType);
changed = true;
}
}
}
return changed;
}
private boolean inferDownward() {
boolean changed = false;
//For each storage, find the most specific common type among all the
//writers' output types, then if it's final, unify with any variable or
//wildcard reader input type. (We only unify if final to avoid removing
//a type variable too soon. We could also refine concrete types like
//Object to a more specific subclass.)
for (Storage s : storage) {
Set<? extends TypeToken<?>> commonTypes = null;
for (Actor a : s.upstream())
if (commonTypes == null)
commonTypes = a.outputType().getTypes();
else
commonTypes = Sets.intersection(commonTypes, a.outputType().getTypes());
if (commonTypes.isEmpty())
throw new IllegalStreamGraphException("No common type among writers: "+s.upstream());
TypeToken<?> mostSpecificType = commonTypes.iterator().next();
if (!Modifier.isFinal(mostSpecificType.getRawType().getModifiers()))
continue;
for (Actor a : s.downstream()) {
TypeToken<?> oldInputType = a.inputType();
//TODO: this isn't quite right?
if (!ReflectionUtils.containsVariableOrWildcard(oldInputType.getType())) continue;
TypeResolver resolver = new TypeResolver().where(oldInputType.getType(), mostSpecificType.getType());
TypeToken<?> newInputType = TypeToken.of(resolver.resolveType(oldInputType.getType()));
if (!oldInputType.equals(newInputType)) {
a.setInputType(newInputType);
// System.out.println("inferDownward: inferred "+a+" input type: "+oldInputType+" -> "+newInputType);
changed = true;
}
TypeToken<?> oldOutputType = a.outputType();
TypeToken<?> newOutputType = TypeToken.of(resolver.resolveType(oldOutputType.getType()));
if (!oldOutputType.equals(newOutputType)) {
a.setOutputType(newOutputType);
// System.out.println("inferDownward: inferred "+a+" output type: "+oldOutputType+" -> "+newOutputType);
changed = true;
}
}
}
return changed;
}
/**
* Unboxes storage types and Actor input and output types.
*/
private void unbox() {
for (Storage s : storage) {
if (isUnboxable(s.contentType()) && UNBOXING_STRATEGY.unboxStorage(s, config)) {
TypeToken<?> contents = s.contentType();
Class<?> type = contents.unwrap().getRawType();
s.setType(type);
// if (!s.type().equals(contents.getRawType()))
// System.out.println("unboxed "+s+" to "+type);
}
}
for (WorkerActor a : Iterables.filter(actors, WorkerActor.class)) {
if (isUnboxable(a.inputType()) && UNBOXING_STRATEGY.unboxInput(a, config)) {
TypeToken<?> oldType = a.inputType();
a.setInputType(oldType.unwrap());
// if (!a.inputType().equals(oldType))
// System.out.println("unboxed input of "+a+": "+oldType+" -> "+a.inputType());
}
if (isUnboxable(a.outputType()) && UNBOXING_STRATEGY.unboxOutput(a, config)) {
TypeToken<?> oldType = a.outputType();
a.setOutputType(oldType.unwrap());
// if (!a.outputType().equals(oldType))
// System.out.println("unboxed output of "+a+": "+oldType+" -> "+a.outputType());
}
}
}
private boolean isUnboxable(TypeToken<?> type) {
return Primitives.isWrapperType(type.getRawType()) && !type.getRawType().equals(Void.class);
}
private void generateArchetypalCode() {
for (final ActorArchetype archetype : archetypes) {
Iterable<WorkerActor> workerActors = FluentIterable.from(actors)
.filter(WorkerActor.class)
.filter(wa -> wa.archetype().equals(archetype));
archetype.generateCode(packageName, classloader, workerActors);
for (WorkerActor wa : workerActors)
wa.setStateHolder(archetype.makeStateHolder(wa));
}
}
/**
* If we're compiling an entire graph, create the overall input and output
* buffers now so we can take advantage of
* PeekableBuffers/PokeableBuffers. Otherwise we must pre-init()
* our read/write instructions to refer to these buffers, since they won't
* be passed to the blob's installBuffers().
*/
private void createBuffers() {
assert (overallInput == null) == (overallOutput == null);
if (overallInput == null) {
this.precreatedBuffers = ImmutableMap.of();
return;
}
ActorGroup inputGroup = null, outputGroup = null;
Token inputToken = null, outputToken = null;
for (ActorGroup g : groups)
if (g.isTokenGroup()) {
assert g.actors().size() == 1;
TokenActor ta = (TokenActor)g.actors().iterator().next();
assert g.schedule().get(ta) == 1;
if (ta.isInput()) {
assert inputGroup == null;
inputGroup = g;
inputToken = ta.token();
}
if (ta.isOutput()) {
assert outputGroup == null;
outputGroup = g;
outputToken = ta.token();
}
}
this.overallInputBuffer = InputBufferFactory.unwrap(overallInput).createReadableBuffer(
Math.max(initSchedule.get(inputGroup), externalSchedule.get(inputGroup)));
this.overallOutputBuffer = OutputBufferFactory.unwrap(overallOutput).createWritableBuffer(
Math.max(initSchedule.get(outputGroup), externalSchedule.get(outputGroup)));
this.precreatedBuffers = ImmutableMap.<Token, Buffer>builder()
.put(inputToken, overallInputBuffer)
.put(outputToken, overallOutputBuffer)
.build();
}
private void createInitCode() {
ImmutableMap<Actor, ImmutableList<MethodHandle>> indexFxnBackup = adjustOutputIndexFunctions(Storage::initialDataIndices);
this.initStorage = createStorage(false, new PeekPokeStorageFactory(InternalArrayConcreteStorage.initFactory(initSchedule)));
initReadInstructions.add(new InitDataReadInstruction(initStorage, initialStateDataMap));
ImmutableMap<Storage, ConcreteStorage> internalStorage = createStorage(true, InternalArrayConcreteStorage.initFactory(initSchedule));
IndexFunctionTransformer ift = new IdentityIndexFunctionTransformer();
ImmutableTable.Builder<Actor, Integer, IndexFunctionTransformer> inputTransformers = ImmutableTable.builder(),
outputTransformers = ImmutableTable.builder();
for (Actor a : Iterables.filter(actors, WorkerActor.class)) {
for (int i = 0; i < a.inputs().size(); ++i)
inputTransformers.put(a, i, ift);
for (int i = 0; i < a.outputs().size(); ++i)
outputTransformers.put(a, i, ift);
}
ImmutableMap.Builder<ActorGroup, Integer> unrollFactors = ImmutableMap.builder();
for (ActorGroup g : groups)
unrollFactors.put(g, 1);
/**
* During init, all (nontoken) groups are assigned to the same Core in
* topological order (via the ordering on ActorGroups). At the same
* time we build the token init schedule information required by the
* blob host.
*/
Core initCore = new Core(CollectionUtils.union(initStorage, internalStorage), (table, wa) -> Combinators.lookupswitch(table), unrollFactors.build(), inputTransformers.build(), outputTransformers.build(), new ProxyFactory(classloader, packageName+".init"));
for (ActorGroup g : groups)
if (!g.isTokenGroup())
initCore.allocate(g, Range.closedOpen(0, initSchedule.get(g)));
else {
assert g.actors().size() == 1;
TokenActor ta = (TokenActor)g.actors().iterator().next();
assert g.schedule().get(ta) == 1;
ConcreteStorage storage = initStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs()));
int executions = initSchedule.get(g);
if (ta.isInput())
initReadInstructions.add(makeReadInstruction(ta, storage, executions));
else
initWriteInstructions.add(makeWriteInstruction(ta, storage, executions));
}
this.initCode = initCore.code();
restoreOutputIndexFunctions(indexFxnBackup);
}
private void createSteadyStateCode() {
for (Actor a : actors) {
for (int i = 0; i < a.outputs().size(); ++i) {
Storage s = a.outputs().get(i);
if (s.isInternal()) continue;
int itemsWritten = a.push(i) * initSchedule.get(a.group()) * a.group().schedule().get(a);
a.outputIndexFunctions().set(i, MethodHandles.filterArguments(
a.outputIndexFunctions().get(i), 0, Combinators.adder(itemsWritten)));
}
for (int i = 0; i < a.inputs().size(); ++i) {
Storage s = a.inputs().get(i);
if (s.isInternal()) continue;
int itemsRead = a.pop(i) * initSchedule.get(a.group()) * a.group().schedule().get(a);
a.inputIndexFunctions().set(i, MethodHandles.filterArguments(
a.inputIndexFunctions().get(i), 0, Combinators.adder(itemsRead)));
}
}
for (Storage s : storage)
s.computeSteadyStateRequirements(externalSchedule);
this.steadyStateStorage = createStorage(false, new PeekPokeStorageFactory(EXTERNAL_STORAGE_STRATEGY.asFactory(config)));
ImmutableMap<Storage, ConcreteStorage> internalStorage = createStorage(true, INTERNAL_STORAGE_STRATEGY.asFactory(config));
List<Core> ssCores = new ArrayList<>(maxNumCores);
IndexFunctionTransformer ift = new IdentityIndexFunctionTransformer();
for (int i = 0; i < maxNumCores; ++i) {
ImmutableTable.Builder<Actor, Integer, IndexFunctionTransformer> inputTransformers = ImmutableTable.builder(),
outputTransformers = ImmutableTable.builder();
for (Actor a : Iterables.filter(actors, WorkerActor.class)) {
for (int j = 0; j < a.inputs().size(); ++j) {
// String name = String.format("Core%dWorker%dInput%dIndexFxnTransformer", i, a.id(), j);
// SwitchParameter<IndexFunctionTransformer> param = config.getParameter(name, SwitchParameter.class, IndexFunctionTransformer.class);
inputTransformers.put(a, j, ift);
}
for (int j = 0; j < a.outputs().size(); ++j) {
// String name = String.format("Core%dWorker%dOutput%dIndexFxnTransformer", i, a.id(), j);
// SwitchParameter<IndexFunctionTransformer> param = config.getParameter(name, SwitchParameter.class, IndexFunctionTransformer.class);
outputTransformers.put(a, j, ift);
}
}
ImmutableMap.Builder<ActorGroup, Integer> unrollFactors = ImmutableMap.builder();
for (ActorGroup g : groups) {
if (g.isTokenGroup()) continue;
IntParameter param = config.getParameter(String.format("UnrollCore%dGroup%d", i, g.id()), IntParameter.class);
unrollFactors.put(g, param.getValue());
}
ssCores.add(new Core(CollectionUtils.union(steadyStateStorage, internalStorage), (table, wa) -> SWITCHING_STRATEGY.createSwitch(table, wa, config), unrollFactors.build(), inputTransformers.build(), outputTransformers.build(), new ProxyFactory(classloader, packageName+".steadystate.")));
}
int throughputPerSteadyState = 0;
for (ActorGroup g : groups)
if (!g.isTokenGroup())
ALLOCATION_STRATEGY.allocateGroup(g, Range.closedOpen(0, externalSchedule.get(g)), ssCores, config);
else {
assert g.actors().size() == 1;
TokenActor ta = (TokenActor)g.actors().iterator().next();
assert g.schedule().get(ta) == 1;
ConcreteStorage storage = steadyStateStorage.get(Iterables.getOnlyElement(ta.isInput() ? g.outputs() : g.inputs()));
int executions = externalSchedule.get(g);
if (ta.isInput())
readInstructions.add(makeReadInstruction(ta, storage, executions));
else {
writeInstructions.add(makeWriteInstruction(ta, storage, executions));
throughputPerSteadyState += executions;
}
}
ImmutableList.Builder<MethodHandle> steadyStateCodeBuilder = ImmutableList.builder();
for (Core c : ssCores)
if (!c.isEmpty())
steadyStateCodeBuilder.add(c.code());
//Provide at least one core of code, even if it doesn't do anything; the
//blob host will still copy inputs to outputs.
this.steadyStateCode = steadyStateCodeBuilder.build();
if (steadyStateCode.isEmpty())
this.steadyStateCode = ImmutableList.of(Combinators.nop());
createMigrationInstructions();
createDrainInstructions();
Boolean reportThroughput = (Boolean)config.getExtraData("reportThroughput");
if (reportThroughput != null && reportThroughput) {
ReportThroughputInstruction rti = new ReportThroughputInstruction(throughputPerSteadyState);
readInstructions.add(rti);
writeInstructions.add(rti);
}
}
private ReadInstruction makeReadInstruction(TokenActor a, ConcreteStorage cs, int count) {
assert a.isInput();
Storage s = Iterables.getOnlyElement(a.outputs());
MethodHandle idxFxn = Iterables.getOnlyElement(a.outputIndexFunctions());
ReadInstruction retval;
if (count == 0)
retval = new NopReadInstruction(a.token());
else if (cs instanceof PeekableBufferConcreteStorage)
retval = new PeekReadInstruction(a, count);
else if (!s.type().isPrimitive() &&
cs instanceof BulkWritableConcreteStorage &&
contiguouslyIncreasing(idxFxn, 0, count)) {
retval = new BulkReadInstruction(a, (BulkWritableConcreteStorage)cs, count);
} else
retval = new TokenReadInstruction(a, cs, count);
// System.out.println("Made a "+retval+" for "+a.token());
retval.init(precreatedBuffers);
return retval;
}
private WriteInstruction makeWriteInstruction(TokenActor a, ConcreteStorage cs, int count) {
assert a.isOutput();
Storage s = Iterables.getOnlyElement(a.inputs());
MethodHandle idxFxn = Iterables.getOnlyElement(a.inputIndexFunctions());
WriteInstruction retval;
if (count == 0)
retval = new NopWriteInstruction(a.token());
else if (!s.type().isPrimitive() &&
cs instanceof BulkReadableConcreteStorage &&
contiguouslyIncreasing(idxFxn, 0, count)) {
retval = new BulkWriteInstruction(a, (BulkReadableConcreteStorage)cs, count);
} else
retval = new TokenWriteInstruction(a, cs, count);
// System.out.println("Made a "+retval+" for "+a.token());
retval.init(precreatedBuffers);
return retval;
}
private boolean contiguouslyIncreasing(MethodHandle idxFxn, int start, int count) {
try {
int prev = (int)idxFxn.invokeExact(start);
for (int i = start+1; i < count; ++i) {
int next = (int)idxFxn.invokeExact(i);
if (next != (prev + 1))
return false;
prev = next;
}
return true;
} catch (Throwable ex) {
throw new AssertionError("index functions should not throw", ex);
}
}
/**
* Create migration instructions: Runnables that move live items from
* initialization to steady-state storage.
*/
private void createMigrationInstructions() {
for (Storage s : initStorage.keySet()) {
ConcreteStorage init = initStorage.get(s), steady = steadyStateStorage.get(s);
if (steady instanceof PeekableBufferConcreteStorage)
migrationInstructions.add(new PeekMigrationInstruction(
s, (PeekableBufferConcreteStorage)steady));
else
migrationInstructions.add(new MigrationInstruction(s, init, steady));
}
}
/**
* Create drain instructions, which collect live items from steady-state
* storage when draining.
*/
private void createDrainInstructions() {
Map<Token, Pair<List<ConcreteStorage>, List<Integer>>> drainReads = new HashMap<>();
for (Map.Entry<Token, Integer> e : postInitLiveness.entrySet())
drainReads.put(e.getKey(), Pair.make(
new ArrayList<>(Collections.nCopies(e.getValue(), null)),
Ints.asList(new int[e.getValue()])));
for (Actor a : actors) {
for (int input = 0; input < a.inputs().size(); ++input) {
ConcreteStorage storage = steadyStateStorage.get(a.inputs().get(input));
for (int index = 0; index < a.inputSlots(input).size(); ++index) {
StorageSlot info = a.inputSlots(input).get(index);
if (info.isDrainable()) {
Pair<List<ConcreteStorage>, List<Integer>> dr = drainReads.get(info.token());
ConcreteStorage old = dr.first.set(info.index(), storage);
assert old == null : "overwriting "+info;
dr.second.set(info.index(), a.translateInputIndex(input, index));
}
}
}
}
for (Map.Entry<Token, Pair<List<ConcreteStorage>, List<Integer>>> e : drainReads.entrySet()) {
List<ConcreteStorage> storages = e.getValue().first;
List<Integer> indices = e.getValue().second;
assert !storages.contains(null) : "lost an element from "+e.getKey()+": "+e.getValue();
if (storages.stream().anyMatch(s -> s instanceof PeekableBufferConcreteStorage)) {
assert storages.stream().allMatch(s -> s instanceof PeekableBufferConcreteStorage)
: "mixed peeking and not? "+e.getKey()+": "+e.getValue();
//we still create a drain instruction, but it does nothing
storages.clear();
indices = Ints.asList();
}
drainInstructions.add(new XDrainInstruction(e.getKey(), storages, indices));
}
for (WorkerActor wa : Iterables.filter(actors, WorkerActor.class))
drainInstructions.add(wa.stateHolder());
}
//<editor-fold defaultstate="collapsed" desc="Output index function adjust/restore">
/**
* Adjust output index functions to avoid overwriting items in external
* storage. For any actor writing to external storage, we find the
* first item that doesn't hit the live index set and add that many
* (making that logical item 0 for writers).
* @param liveIndexExtractor a function that computes the relevant live
* index set for the given external storage
* @return the old output index functions, to be restored later
*/
private ImmutableMap<Actor, ImmutableList<MethodHandle>> adjustOutputIndexFunctions(Function<Storage, Set<Integer>> liveIndexExtractor) {
ImmutableMap.Builder<Actor, ImmutableList<MethodHandle>> backup = ImmutableMap.builder();
for (Actor a : actors) {
backup.put(a, ImmutableList.copyOf(a.outputIndexFunctions()));
for (int i = 0; i < a.outputs().size(); ++i) {
if (a.push(i) == 0) continue; //No writes -- nothing to adjust.
Storage s = a.outputs().get(i);
if (s.isInternal())
continue;
Set<Integer> liveIndices = liveIndexExtractor.apply(s);
assert liveIndices != null : s +" "+liveIndexExtractor;
int offset = 0;
while (liveIndices.contains(a.translateOutputIndex(i, offset)))
++offset;
//Check future indices are also open (e.g., that we aren't
//alternating hole/not-hole).
for (int check = 0; check < 100; ++check)
assert !liveIndices.contains(a.translateOutputIndex(i, offset + check)) : check;
a.outputIndexFunctions().set(i, Combinators.apply(a.outputIndexFunctions().get(i), Combinators.adder(offset)));
}
}
return backup.build();
}
/**
* Restores output index functions from a backup returned from
* {@link #adjustOutputIndexFunctions(com.google.common.base.Function)}.
* @param backup the backup to restore
*/
private void restoreOutputIndexFunctions(ImmutableMap<Actor, ImmutableList<MethodHandle>> backup) {
for (Actor a : actors) {
ImmutableList<MethodHandle> oldFxns = backup.get(a);
assert oldFxns != null : "no backup for "+a;
assert oldFxns.size() == a.outputIndexFunctions().size() : "backup for "+a+" is wrong size";
Collections.copy(a.outputIndexFunctions(), oldFxns);
}
}
//</editor-fold>
private ImmutableMap<Storage, ConcreteStorage> createStorage(boolean internal, StorageFactory factory) {
ImmutableMap.Builder<Storage, ConcreteStorage> builder = ImmutableMap.builder();
for (Storage s : storage)
if (s.isInternal() == internal)
builder.put(s, factory.make(s));
return builder.build();
}
/**
* Creates special ConcreteStorage implementations for PeekableBuffer and
* PokeableBuffer, or falls back to the given factory.
*/
private final class PeekPokeStorageFactory implements StorageFactory {
private final StorageFactory fallback;
private final boolean usePeekableBuffer;
private PeekPokeStorageFactory(StorageFactory fallback) {
this.fallback = fallback;
SwitchParameter<Boolean> usePeekableBufferParam = config.getParameter("UsePeekableBuffer", SwitchParameter.class, Boolean.class);
this.usePeekableBuffer = usePeekableBufferParam.getValue();
}
@Override
public ConcreteStorage make(Storage storage) {
if (storage.id().isOverallInput() && overallInputBuffer instanceof PeekableBuffer && usePeekableBuffer)
return PeekableBufferConcreteStorage.factory(ImmutableMap.of(storage.id(), (PeekableBuffer)overallInputBuffer)).make(storage);
//TODO: PokeableBuffer
return fallback.make(storage);
}
}
private static final class MigrationInstruction implements Runnable {
private final ConcreteStorage init, steady;
private final int[] indicesToMigrate;
private MigrationInstruction(Storage storage, ConcreteStorage init, ConcreteStorage steady) {
this.init = init;
this.steady = steady;
ImmutableSortedSet.Builder<Integer> builder = ImmutableSortedSet.naturalOrder();
for (Actor a : storage.downstream())
for (int i = 0; i < a.inputs().size(); ++i)
if (a.inputs().get(i).equals(storage))
for (int idx = 0; idx < a.inputSlots(i).size(); ++idx)
if (a.inputSlots(i).get(idx).isLive())
builder.add(a.translateInputIndex(i, idx));
this.indicesToMigrate = Ints.toArray(builder.build());
}
@Override
public void run() {
init.sync();
for (int i : indicesToMigrate)
steady.write(i, init.read(i));
steady.sync();
}
}
private static final class PeekMigrationInstruction implements Runnable {
private final PeekableBuffer buffer;
private final int itemsConsumedDuringInit;
private PeekMigrationInstruction(Storage storage, PeekableBufferConcreteStorage steady) {
this.buffer = steady.buffer();
this.itemsConsumedDuringInit = steady.minReadIndex();
}
@Override
public void run() {
buffer.consume(itemsConsumedDuringInit);
}
}
/**
* The X doesn't stand for anything. I just needed a different name.
*/
private static final class XDrainInstruction implements DrainInstruction {
private final Token token;
private final ConcreteStorage[] storage;
private final int[] storageSelector, index;
private XDrainInstruction(Token token, List<ConcreteStorage> storages, List<Integer> indices) {
assert storages.size() == indices.size() : String.format("%s %s %s", token, storages, indices);
this.token = token;
Set<ConcreteStorage> set = new HashSet<>(storages);
this.storage = set.toArray(new ConcreteStorage[set.size()]);
this.storageSelector = new int[indices.size()];
this.index = Ints.toArray(indices);
for (int i = 0; i < indices.size(); ++i)
storageSelector[i] = Arrays.asList(storage).indexOf(storages.get(i));
}
@Override
public Map<Token, Object[]> call() {
Object[] data = new Object[index.length];
int idx = 0;
for (int i = 0; i < index.length; ++i)
data[idx++] = storage[storageSelector[i]].read(index[i]);
return ImmutableMap.of(token, data);
}
}
/**
* PeekReadInstruction implements special handling for PeekableBuffer.
*/
private static final class PeekReadInstruction implements ReadInstruction {
private final Token token;
private final int count;
private PeekableBuffer buffer;
private PeekReadInstruction(TokenActor a, int count) {
assert a.isInput() : a;
this.token = a.token();
//If we "read" count new items, the maximum available index is given
//by the output index function.
this.count = a.translateOutputIndex(0, count);
}
@Override
public void init(Map<Token, Buffer> buffers) {
if (!buffers.containsKey(token)) return;
if (buffer != null)
checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token));
this.buffer = (PeekableBuffer)buffers.get(token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
//This shouldn't matter because we've already created the buffers.
return ImmutableMap.of(token, count);
}
@Override
public boolean load() {
//Ensure data is present for reading.
return buffer.size() >= count;
}
@Override
public Map<Token, Object[]> unload() {
//Data is not consumed from the underlying buffer until it's
//adjusted, so no work is necessary here.
return ImmutableMap.of();
}
}
private static final class BulkReadInstruction implements ReadInstruction {
private final Token token;
private final BulkWritableConcreteStorage storage;
private final int index, count;
private Buffer buffer;
private BulkReadInstruction(TokenActor a, BulkWritableConcreteStorage storage, int count) {
assert a.isInput() : a;
this.token = a.token();
this.storage = storage;
this.index = a.translateOutputIndex(0, 0);
this.count = count;
}
@Override
public void init(Map<Token, Buffer> buffers) {
if (!buffers.containsKey(token)) return;
if (buffer != null)
checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token));
this.buffer = buffers.get(token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public boolean load() {
if (buffer.size() < count)
return false;
storage.bulkWrite(buffer, index, count);
storage.sync();
return true;
}
@Override
public Map<Token, Object[]> unload() {
Object[] data = new Object[count];
for (int i = index; i < count; ++i) {
data[i - index] = storage.read(i);
}
return ImmutableMap.of(token, data);
}
}
/**
* TODO: consider using read/write handles instead of read(), write()?
*/
private static final class TokenReadInstruction implements ReadInstruction {
private final Token token;
private final MethodHandle idxFxn;
private final ConcreteStorage storage;
private final int count;
private Buffer buffer;
private TokenReadInstruction(TokenActor a, ConcreteStorage storage, int count) {
assert a.isInput() : a;
this.token = a.token();
this.storage = storage;
this.idxFxn = Iterables.getOnlyElement(a.outputIndexFunctions());
this.count = count;
}
@Override
public void init(Map<Token, Buffer> buffers) {
if (!buffers.containsKey(token)) return;
if (buffer != null)
checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token));
this.buffer = buffers.get(token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public boolean load() {
Object[] data = new Object[count];
if (!buffer.readAll(data))
return false;
for (int i = 0; i < data.length; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
storage.write(idx, data[i]);
}
storage.sync();
return true;
}
@Override
public Map<Token, Object[]> unload() {
Object[] data = new Object[count];
for (int i = 0; i < data.length; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
data[i] = storage.read(idx);
}
return ImmutableMap.of(token, data);
}
}
/**
* Doesn't read anything, but does respond to getMinimumBufferCapacity().
*/
private static final class NopReadInstruction implements ReadInstruction {
private final Token token;
private NopReadInstruction(Token token) {
this.token = token;
}
@Override
public void init(Map<Token, Buffer> buffers) {
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, 0);
}
@Override
public boolean load() {
return true;
}
@Override
public Map<Token, Object[]> unload() {
return ImmutableMap.of();
}
}
private static final class BulkWriteInstruction implements WriteInstruction {
private final Token token;
private final BulkReadableConcreteStorage storage;
private final int index, count;
private Buffer buffer;
private int written;
private BulkWriteInstruction(TokenActor a, BulkReadableConcreteStorage storage, int count) {
assert a.isOutput(): a;
this.token = a.token();
this.storage = storage;
this.index = a.translateInputIndex(0, 0);
this.count = count;
}
@Override
public void init(Map<Token, Buffer> buffers) {
if (!buffers.containsKey(token)) return;
if (buffer != null)
checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token));
this.buffer = buffers.get(token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public Boolean call() {
written += storage.bulkRead(buffer, index + written, count);
if (written < count)
return false;
written = 0;
return true;
}
}
/**
* TODO: consider using read handles instead of read()?
*/
private static final class TokenWriteInstruction implements WriteInstruction {
private final Token token;
private final MethodHandle idxFxn;
private final ConcreteStorage storage;
private final int count;
private Buffer buffer;
private int written;
private TokenWriteInstruction(TokenActor a, ConcreteStorage storage, int count) {
assert a.isOutput() : a;
this.token = a.token();
this.storage = storage;
this.idxFxn = Iterables.getOnlyElement(a.inputIndexFunctions());
this.count = count;
}
@Override
public void init(Map<Token, Buffer> buffers) {
if (!buffers.containsKey(token)) return;
if (buffer != null)
checkState(buffers.get(token) == buffer, "reassigning %s from %s to %s", token, buffer, buffers.get(token));
this.buffer = buffers.get(token);
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, count);
}
@Override
public Boolean call() {
Object[] data = new Object[count];
for (int i = 0; i < count; ++i) {
int idx;
try {
idx = (int)idxFxn.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
data[i] = storage.read(idx);
}
written += buffer.write(data, written, data.length-written);
if (written < count)
return false;
written = 0;
return true;
}
}
/**
* Doesn't write anything, but does respond to getMinimumBufferCapacity().
*/
private static final class NopWriteInstruction implements WriteInstruction {
private final Token token;
private NopWriteInstruction(Token token) {
this.token = token;
}
@Override
public void init(Map<Token, Buffer> buffers) {
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of(token, 0);
}
@Override
public Boolean call() {
return true;
}
}
/**
* Writes initial data into init storage, or "unloads" it (just returning it
* as it was in the DrainData, not actually reading the storage) if we drain
* during init. (Any remaining data after init will be migrated as normal.)
* There's only one of these per blob because it returns all the data, and
* it should be the first initReadInstruction.
*/
private static final class InitDataReadInstruction implements ReadInstruction {
private final ImmutableMap<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWrite;
private final ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap;
private InitDataReadInstruction(Map<Storage, ConcreteStorage> initStorage, ImmutableMap<Token, ImmutableList<Object>> initialStateDataMap) {
ImmutableMap.Builder<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> toWriteBuilder = ImmutableMap.builder();
for (Map.Entry<Storage, ConcreteStorage> e : initStorage.entrySet()) {
Storage s = e.getKey();
if (s.isInternal()) continue;
if (s.initialData().isEmpty()) continue;
toWriteBuilder.put(e.getValue(), ImmutableList.copyOf(s.initialData()));
}
this.toWrite = toWriteBuilder.build();
this.initialStateDataMap = initialStateDataMap;
}
@Override
public void init(Map<Token, Buffer> buffers) {
}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of();
}
@Override
public boolean load() {
for (Map.Entry<ConcreteStorage, ImmutableList<Pair<ImmutableList<Object>, MethodHandle>>> e : toWrite.entrySet())
for (Pair<ImmutableList<Object>, MethodHandle> p : e.getValue())
for (int i = 0; i < p.first.size(); ++i) {
int idx;
try {
idx = (int)p.second.invokeExact(i);
} catch (Throwable ex) {
throw new AssertionError("Can't happen! Index functions should not throw", ex);
}
e.getKey().write(idx, p.first.get(i));
}
return true;
}
@Override
public Map<Token, Object[]> unload() {
Map<Token, Object[]> r = new HashMap<>();
for (Map.Entry<Token, ImmutableList<Object>> e : initialStateDataMap.entrySet())
r.put(e.getKey(), e.getValue().toArray());
return r;
}
}
private static final class ReportThroughputInstruction implements ReadInstruction, WriteInstruction {
private static final long WARMUP_NANOS = TimeUnit.NANOSECONDS.convert(10, TimeUnit.SECONDS);
private static final long TIMING_NANOS = TimeUnit.NANOSECONDS.convert(5, TimeUnit.SECONDS);
private final long throughputPerSteadyState;
private int steadyStates = 0;
private long firstNanoTime = Long.MIN_VALUE, afterWarmupNanoTime = Long.MIN_VALUE;
private ReportThroughputInstruction(long throughputPerSteadyState) {
this.throughputPerSteadyState = throughputPerSteadyState;
}
@Override
public void init(Map<Token, Buffer> buffers) {}
@Override
public Map<Token, Integer> getMinimumBufferCapacity() {
return ImmutableMap.of();
}
@Override
public Map<Token, Object[]> unload() {
return ImmutableMap.of();
}
@Override
public boolean load() {
long currentTime = time();
if (firstNanoTime == Long.MIN_VALUE)
firstNanoTime = currentTime;
else if (afterWarmupNanoTime == Long.MIN_VALUE && currentTime - firstNanoTime > WARMUP_NANOS)
afterWarmupNanoTime = currentTime;
return true;
}
@Override
public Boolean call() {
if (afterWarmupNanoTime != Long.MIN_VALUE) {
++steadyStates;
long currentTime = time();
long elapsed = currentTime - afterWarmupNanoTime;
if (elapsed > TIMING_NANOS) {
long itemsOutput = steadyStates * throughputPerSteadyState;
System.out.format("%d/%d/%d/%d#%n", steadyStates, itemsOutput, elapsed, elapsed/itemsOutput);
System.out.flush();
System.exit(0);
}
}
return true;
}
private static long time() {
// return System.currentTimeMillis()*1000000;
return System.nanoTime();
}
}
/**
* Creates the blob host. This mostly involves shuffling our state into the
* form the blob host wants.
* @return the blob
*/
public Blob instantiateBlob() {
ImmutableSortedSet.Builder<Token> inputTokens = ImmutableSortedSet.naturalOrder(),
outputTokens = ImmutableSortedSet.naturalOrder();
for (TokenActor ta : Iterables.filter(actors, TokenActor.class))
(ta.isInput() ? inputTokens : outputTokens).add(ta.token());
ImmutableList.Builder<MethodHandle> storageAdjusts = ImmutableList.builder();
for (ConcreteStorage s : steadyStateStorage.values())
storageAdjusts.add(s.adjustHandle());
return new Compiler2BlobHost(workers, config,
inputTokens.build(), outputTokens.build(),
initCode, steadyStateCode,
storageAdjusts.build(),
initReadInstructions, initWriteInstructions, migrationInstructions,
readInstructions, writeInstructions, drainInstructions,
precreatedBuffers);
}
public static void main(String[] args) {
StreamCompiler sc;
Benchmark bm;
if (args.length == 3) {
String benchmarkName = args[0];
int cores = Integer.parseInt(args[1]);
int multiplier = Integer.parseInt(args[2]);
sc = new Compiler2StreamCompiler().maxNumCores(cores).multiplier(multiplier);
bm = Benchmarker.getBenchmarkByName(benchmarkName);
} else {
sc = new Compiler2StreamCompiler().multiplier(384).maxNumCores(4);
bm = new FMRadio.FMRadioBenchmarkProvider().iterator().next();
}
Benchmarker.runBenchmark(bm, sc).get(0).print(System.out);
}
private void printDot(String stage) {
try (FileWriter fw = new FileWriter(stage+".dot");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("digraph {\n");
for (ActorGroup g : groups) {
bw.write("subgraph cluster_"+Integer.toString(g.id()).replace('-', '_')+" {\n");
for (Actor a : g.actors())
bw.write(String.format("\"%s\";\n", nodeName(a)));
bw.write("label = \"x"+externalSchedule.get(g)+"\";\n");
bw.write("}\n");
}
for (ActorGroup g : groups) {
for (Actor a : g.actors()) {
for (Storage s : a.outputs())
for (Actor b : s.downstream())
bw.write(String.format("\"%s\" -> \"%s\";\n", nodeName(a), nodeName(b)));
}
}
bw.write("}\n");
} catch (IOException ex) {
ex.printStackTrace();
}
}
private String nodeName(Actor a) {
if (a instanceof TokenActor)
return (((TokenActor)a).isInput()) ? "input" : "output";
WorkerActor wa = (WorkerActor)a;
String workerClassName = wa.worker().getClass().getSimpleName();
return workerClassName.replaceAll("[a-z]", "") + "@" + Integer.toString(wa.id()).replace('-', '_');
}
} |
package org.oucs.gaboto.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import org.oucs.gaboto.GabotoConfiguration;
import org.oucs.gaboto.GabotoLibrary;
import org.oucs.gaboto.exceptions.GabotoException;
import org.oucs.gaboto.model.events.GabotoEvent;
import org.oucs.gaboto.model.events.GabotoInsertionEvent;
import org.oucs.gaboto.model.events.GabotoRemovalEvent;
import org.oucs.gaboto.model.listener.UpdateListener;
import org.oucs.gaboto.timedim.index.SimpleTimeDimensionIndexer;
import org.oucs.gaboto.util.Performance;
import org.oucs.gaboto.vocabulary.RDFCON;
import com.hp.hpl.jena.db.DBConnection;
import com.hp.hpl.jena.db.IDBConnection;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;
import com.hp.hpl.jena.vocabulary.RDF;
import de.fuberlin.wiwiss.ng4j.NamedGraph;
import de.fuberlin.wiwiss.ng4j.NamedGraphSet;
import de.fuberlin.wiwiss.ng4j.Quad;
import de.fuberlin.wiwiss.ng4j.db.NamedGraphSetDB;
import de.fuberlin.wiwiss.ng4j.impl.NamedGraphSetImpl;
/**
* Factory class to create Gaboto objects.
*
*
* @author Arno Mittelbach
* @version 0.1
*/
public class GabotoFactory {
private static Gaboto persistentGaboto = null;
private static Gaboto inMemoryGaboto = null;
private static Model cdg = null;
/**
* Creates an empty in memory Gaboto model that is not linked to any persistent data store.
*
* <p>
* A time dimension indexer is set.
* </p>
*
* @return A new Gaboto object.
*/
public static Gaboto getEmptyInMemoryGaboto(){
// Create a new graphset and copy graphs
NamedGraphSet graphset = new NamedGraphSetImpl();
// create none db backed up cdg
cdg = ModelFactory.createDefaultModel();
// get config
GabotoConfiguration config = GabotoLibrary.getConfig();
// if graphset is empty, create special graphs
if(! graphset.containsGraph(config.getGKG()))
createGKG(graphset);
Gaboto test = new Gaboto(cdg, graphset, new SimpleTimeDimensionIndexer());
return test;
}
/**
* Creates a new in-memory Gaboto system that is kept in sync with the persistent Gaboto object.
*
* <p>
* A time dimension indexer is set.
* </p>
*
* <p>
* In memory objects should only be used for querying data.
* </p>
*
* @return An Gaboto object with an in-memory store.
* @throws GabotoException
*
* @see #getPersistentGaboto()
*/
@SuppressWarnings("unchecked")
public static Gaboto getInMemoryGaboto() {
if(null != inMemoryGaboto)
return inMemoryGaboto;
Gaboto po = getPersistentGaboto();
// Create a new graphset and copy graphs
NamedGraphSet graphset = new NamedGraphSetImpl();
Iterator graphIt = po.getNamedGraphSet().listGraphs();
while(graphIt.hasNext())
graphset.createGraph(((NamedGraph)graphIt.next()).getGraphName());
System.err.println("getInMemoryGaboto: have created graphs");
Iterator it = po.getNamedGraphSet().findQuads(Node.ANY, Node.ANY, Node.ANY, Node.ANY);
while(it.hasNext())
graphset.addQuad((Quad)it.next());
System.err.println("getInMemoryGaboto: have added quads");
inMemoryGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer());
System.err.println("getInMemoryGaboto: returning");
return inMemoryGaboto;
}
/**
* Creates a new Gaboto model with a persistent data store.
*
* <p>
* The connection to the database is configured in the {@link GabotoConfiguration}.
* </p>
*
* <p>
* A time dimension indexer is NOT set.
* </p>
*
* <p>
* The Persistent Gaboto object should only be used to add and change data. For
* querying the data, an in-memory Gaboto should be used.
* </p>
*
* @return A new persistent Gaboto
* @throws GabotoException
* @see #getInMemoryGaboto()
* @see GabotoConfiguration
*/
public static Gaboto getPersistentGaboto() {
// does it already exist?
if(persistentGaboto != null)
return persistentGaboto;
// get config
GabotoConfiguration config = GabotoLibrary.getConfig();
// create persistent gaboto
String URL = config.getDbURL();
String USER = config.getDbUser();
String PW = config.getDbPassword();
try {
Class.forName(config.getDbDriver());
} catch (ClassNotFoundException e1) {
throw new RuntimeException(e1);
}
Connection connection = null;
System.err.println("URL:"+URL + " USER:"+USER+ " PWD:"+PW);
try {
connection = DriverManager.getConnection(URL, USER, PW);
} catch (SQLException e) {
throw new RuntimeException(e);
}
// Create a new graphset
Performance.start("GabotoFactory new NamedGraphSetDB");
NamedGraphSet graphset = new NamedGraphSetDB(connection);
Performance.stop();
// if graphset is empty, create special graphs
if(! graphset.containsGraph(config.getGKG()))
createGKG(graphset);
// create object
Performance.start("GabotoFactory new Gaboto");
persistentGaboto = new Gaboto(createCDG(), graphset, new SimpleTimeDimensionIndexer());
Performance.stop();
Performance.start("GabotoFactory update listener");
// attach update listener
persistentGaboto.attachUpdateListener(new UpdateListener(){
public void updateOccured(GabotoEvent e) {
if(inMemoryGaboto instanceof Gaboto){
// try to cast event to insertion
if(e instanceof GabotoInsertionEvent){
GabotoInsertionEvent event = (GabotoInsertionEvent) e;
if(null != event.getTimespan())
inMemoryGaboto.add(event.getTimespan(), event.getTriple());
else
inMemoryGaboto.add(event.getTriple());
}
// try to cast event to removal
else if(e instanceof GabotoRemovalEvent){
GabotoRemovalEvent event = (GabotoRemovalEvent) e;
if(null != event.getQuad())
inMemoryGaboto.remove(event.getQuad());
else if(null != event.getTimespan() && null != event.getTriple())
inMemoryGaboto.remove(event.getTimespan(), event.getTriple());
else if(null != event.getTriple())
inMemoryGaboto.remove(event.getTriple());
}
}
}
});
Performance.stop();
return persistentGaboto;
}
/**
* adds the cdg to the graphset
* @param graphset
*/
private static Model createCDG() {
if(null != cdg)
return cdg;
// get config
GabotoConfiguration config = GabotoLibrary.getConfig();
String M_DB_URL = config.getDbURL();
String M_DB_USER = config.getDbUser();
String M_DB_PASSWD = config.getDbPassword();
String M_DB = config.getDbEngineName();
String M_DBDRIVER_CLASS = config.getDbDriver();
// load the the driver class
try {
Class.forName(M_DBDRIVER_CLASS);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
// create a database connection
IDBConnection conn = new DBConnection(M_DB_URL, M_DB_USER, M_DB_PASSWD, M_DB);
// create a model maker with the given connection parameters
ModelMaker maker = ModelFactory.createModelRDBMaker(conn);
// create cdg
if(maker.hasModel("cdg"))
cdg = maker.openModel("cdg");
else
cdg = maker.createModel("cdg");
return cdg;
}
/**
* adds the gkgg to the graphset
* @param graphset
*/
private static void createGKG(NamedGraphSet graphset) {
// get config
GabotoConfiguration config = GabotoLibrary.getConfig();
if(graphset.containsGraph(config.getGKG()))
throw new IllegalStateException("GKG already exists.");
// Create gkg
graphset.createGraph(config.getGKG());
// add gkg to cdg
createCDG().getGraph().add(new Triple(
Node.createURI(config.getGKG()),
Node.createURI(RDF.type.getURI()),
Node.createURI(RDFCON.GlobalKnowledgeGraph.getURI())
));
}
} |
package edu.psu.sweng500.team8.gui;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.filechooser.FileFilter;
import edu.psu.sweng500.team8.coreDataStructures.Board;
import edu.psu.sweng500.team8.coreDataStructures.Cell;
import edu.psu.sweng500.team8.coreDataStructures.CellCoordinates;
import edu.psu.sweng500.team8.coreDataStructures.CellGrid;
import edu.psu.sweng500.team8.coreDataStructures.Puzzle;
import edu.psu.sweng500.team8.coreDataStructures.Puzzle.DifficultyLevel;
import edu.psu.sweng500.team8.coreDataStructures.SavePackage;
import edu.psu.sweng500.team8.play.CellChangedListener;
import edu.psu.sweng500.team8.play.GameSession;
import edu.psu.sweng500.team8.puzzleGenerator.PuzzleRepository;
import edu.psu.sweng500.team8.solver.HintGenerator;
import edu.psu.sweng500.team8.solver.HintInfo;
import javax.swing.JLabel;
import javax.swing.UIManager;
public class SudokuGUI_Mark2 extends javax.swing.JFrame implements
CellChangedListener {
/* Not sure if there is a better place to put this */
private PuzzleRepository puzzleRepo = new PuzzleRepository();
/* we need to keep track of the current game */
private GameSession gameSession;
private static final String WIN_MESSAGE = "You won! Start a new game to play again.";
/**
* Creates new form SudokuGUI
*/
public SudokuGUI_Mark2() {
try {
this.puzzleRepo.initialize();
} catch (IOException e) {
e.printStackTrace();
}
initComponents();
}
public void setMessage(String message) {
this.txtAreaMessage.setText(message);
}
public void clearMessage() {
this.txtAreaMessage.setText("");
}
@Override
public void cellChanged(Cell cell, int newNumber) {
if (newNumber < 0) {
/* pencil mark change */
this.gameBoard.refreshPencilMarkDisplayOnRelatedCells(cell);
return;
}
/*
* Cell number changed. Clear the message and any highlighted incorrect
* numbers.
*/
this.clearMessage();
this.gameBoard.clearHighlightedIncorrectCells();
if (gameIsComplete()) {
// Player won the game
this.gameBoard.disableEditing();
setMessage(WIN_MESSAGE);
} else {
/*
* issue 225 - related pencil marks should be immediately cleared
* when a cell gets a number
*/
this.gameBoard.refreshPencilMarkDisplayOnRelatedCells(cell);
}
}
private boolean gameIsComplete() {
Board board = this.gameSession.getGameBoard();
return (!board.hasOpenCells() && board.getIncorrectCells().isEmpty());
}
/**
* 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")
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
radEasy = new javax.swing.JRadioButton();
radMedium = new javax.swing.JRadioButton();
radHard = new javax.swing.JRadioButton();
btnSave = new javax.swing.JButton();
btnLoad = new javax.swing.JButton();
btnUndo = new javax.swing.JButton();
btnRedo = new javax.swing.JButton();
jButton14 = new javax.swing.JButton();
btnNewGame = new javax.swing.JButton();
gameBoard = new BoardGUI();
btnHint = new javax.swing.JButton();
pencilMarkButton = new JToggleButton();
btnCheck = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
buttonGroup1.add(radEasy);
radEasy.setSelected(true);
radEasy.setText("Easy");
radEasy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radEasyActionPerformed(evt);
}
});
buttonGroup1.add(radMedium);
radMedium.setText("Medium");
buttonGroup1.add(radHard);
radHard.setText("Hard");
radHard.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radHardActionPerformed(evt);
}
});
this.btnSave.setText("Save");
this.btnSave.setEnabled(false);
this.btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
btnSaveActionPerformed(evt);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
this.btnLoad.setText("Load");
this.btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
this.btnUndo.setText("Undo");
this.btnUndo.setEnabled(false);
this.btnUndo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doUndo(evt);
}
});
this.btnRedo.setText("Redo");
this.btnRedo.setEnabled(false);
this.btnRedo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doRedo(evt);
}
});
this.jButton14.setText("Help");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
btnNewGame.setText("New Game");
btnNewGame.setName("btnNewGame"); // NOI18N
btnNewGame.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNewGameActionPerformed(evt);
}
});
this.btnHint.setText("Hint");
this.btnHint.setEnabled(false);
this.btnHint.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnHintActionPerformed(evt);
}
});
this.pencilMarkButton.setText("Pencil Mark");
this.pencilMarkButton.setEnabled(false);
this.pencilMarkButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pencilMarkMode(evt);
}
});
this.btnCheck.setText("Check");
this.btnCheck.setEnabled(false);
this.btnCheck.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCheckActionPerformed(evt);
}
});
txtAreaMessage = new JTextArea();
txtAreaMessage.setWrapStyleWord(true);
txtAreaMessage.setLineWrap(true);
txtAreaMessage.setEditable(false);
numberInputPad = new NumberButtonGUI();
JLabel label = new JLabel("");
Image img = new ImageIcon(this.getClass().getResource("/lion.png")).getImage();
label.setIcon(new ImageIcon(img));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
getContentPane());
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(gameBoard, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10)
.addComponent(txtAreaMessage, GroupLayout.PREFERRED_SIZE, 480, GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(numberInputPad, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(btnNewGame)
.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
.addGroup(Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(btnHint, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pencilMarkButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
.addComponent(btnLoad, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnRedo, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(btnSave, GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
.addComponent(btnCheck, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnUndo, GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
.addComponent(jButton14, GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
.addComponent(radEasy)
.addComponent(radMedium)
.addComponent(radHard)))
.addComponent(label, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 181, GroupLayout.PREFERRED_SIZE)))
.addContainerGap(93, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(gameBoard, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(txtAreaMessage, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
.addGap(42))
.addGroup(layout.createSequentialGroup()
.addGap(11)
.addComponent(numberInputPad, GroupLayout.PREFERRED_SIZE, 164, GroupLayout.PREFERRED_SIZE)
.addGap(18)
.addComponent(label, GroupLayout.PREFERRED_SIZE, 186, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(pencilMarkButton)
.addComponent(btnCheck))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnHint)
.addComponent(btnSave))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnLoad, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE)
.addComponent(btnUndo))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnRedo)
.addComponent(jButton14))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNewGame)
.addComponent(radEasy))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(radMedium)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(radHard)
.addGap(22))
);
getContentPane().setLayout(layout);
getContentPane().setPreferredSize(new Dimension(800, 600));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnHintActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnHintActionPerformed
// Get a hint
if (this.gameSession == null) {
return;
}
HintInfo hint = HintGenerator.getHint(this.gameSession.getGameBoard());
/* TODO - make this message constant */
String message = "Sorry, no hint available";
if (hint != null) {
CellCoordinates coordinates = hint.getCell().getCoordinates();
this.gameBoard.updateSelectedCellFromHint(coordinates,
hint.getNumber());
this.gameSession.enterNumber(hint.getCell(), hint.getNumber());
message = hint.getExplanation();
if (gameIsComplete()) {
// If hint resulted in completing the game, add the Win message
// and disable editing.
this.gameBoard.disableEditing();
message += " " + WIN_MESSAGE;
}
}
setMessage(message);
}
private void doUndo(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doUndo
this.setMessage("");
this.gameSession.doUndo();
this.gameBoard.populatePanel(this.gameSession, true, false,
this.numberInputPad);
}
private void doRedo(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doRedo
this.setMessage("");
this.gameSession.doRedo();
this.gameBoard.populatePanel(this.gameSession, true, false,
this.numberInputPad);
}
private void btnCheckActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnCheckActionPerformed
if (this.gameSession == null)
return;
Set<Cell> incorrectCells = this.gameSession.getGameBoard()
.getIncorrectCells();
String message = (incorrectCells.isEmpty()) ? "All values are correct so far!"
: "";
this.setMessage(message);
this.gameBoard.highlightIncorrectCells(incorrectCells);
}// GEN-LAST:event_btnCheckActionPerformed
private void radEasyActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_radEasyActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_radEasyActionPerformed
private void radHardActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_radHardActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_radHardActionPerformed
/**
* LOAD Action
*
* @param evt
*/
private void btnLoadActionPerformed(ActionEvent evt) {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.getName().toUpperCase().endsWith(".SUDOKU") || file
.isDirectory());
}
@Override
public String getDescription() {
return "Sudoku files";
}
});
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showOpenDialog(getComponent(0));
if (returnVal == JFileChooser.APPROVE_OPTION) {
SavePackage savePackage = null;
try {
FileInputStream fileIn = new FileInputStream(fc
.getSelectedFile().getAbsolutePath());
ObjectInputStream in = new ObjectInputStream(fileIn);
savePackage = (SavePackage) in.readObject();
in.close();
fileIn.close();
Puzzle puzzle = savePackage.getPuzzle();
DifficultyLevel difficulty = puzzle.getDifficulty();
if (difficulty == DifficultyLevel.Easy) {
radEasy.setSelected(true);
} else if (difficulty == DifficultyLevel.Medium) {
radMedium.setSelected(true);
} else {
radHard.setSelected(true);
}
CellGrid cellGrid = savePackage.getCellGrid();
this.loadSession(puzzle, cellGrid);
/* We need to populate non given cells */
} catch (IOException i) {
i.printStackTrace();
} catch (ClassNotFoundException c) {
c.printStackTrace();
}
}
}
/**
* SAVE Action
*
* @param evt
* @throws FileNotFoundException
*/
private void btnSaveActionPerformed(ActionEvent evt)
throws FileNotFoundException {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.getName().toUpperCase().endsWith(".SUDOKU") || file
.isDirectory());
}
@Override
public String getDescription() {
return "Sudoku files";
}
});
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(getComponent(0));
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
String path = f.getAbsolutePath();
if (f.exists()) {
int result = JOptionPane.showConfirmDialog(this,
"The file exists, overwrite?", "Existing file",
JOptionPane.YES_NO_CANCEL_OPTION);
switch (result) {
case JOptionPane.YES_OPTION:
fc.approveSelection();
savePuzzle(path);
/* Why do we need to remark given cells ?? */
// gameBoard.remarkGivenCells(this.gameSession.getGameBoard()
// .getCellGrid());
return;
case JOptionPane.NO_OPTION:
return;
case JOptionPane.CLOSED_OPTION:
return;
case JOptionPane.CANCEL_OPTION:
fc.cancelSelection();
return;
}
}
fc.approveSelection();
savePuzzle(path);
/* Why do we need to remark given cells ?? */
// gameBoard.remarkGivenCells(this.gameSession.getGameBoard()
// .getCellGrid());
/* Why do we need to re- populate ?? */
// this.pencilMarkGridPanel.populate(gameSession);
}
}
private void savePuzzle(String path) {
try {
if (!path.toLowerCase().endsWith(".sudoku")) {
path = path + ".sudoku";
}
SavePackage savePackage = new SavePackage();
savePackage.setCellGrid(this.gameSession.getGameBoard()
.getCellGrid());
savePackage.setPuzzle(this.gameSession.getGameBoard()
.getCurrentPuzzle());
FileOutputStream fileOut = new FileOutputStream(path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(savePackage);
out.close();
fileOut.close();
} catch (IOException i) {
i.printStackTrace();
}
}
private void loadSession(Puzzle puzzle, CellGrid overloadedCellGrid) {
this.gameSession = new GameSession(puzzle, overloadedCellGrid);
this.gameSession.subscribeForCellChanges(this);
this.numberInputPad.init(buildNumberInputMouseAdapter(),
this.gameSession);
this.gameBoard.populatePanel(gameSession, false, false,
this.numberInputPad);
this.btnSave.setEnabled(true);
this.btnHint.setEnabled(true);
this.btnCheck.setEnabled(true);
this.btnRedo.setEnabled(true);
this.btnUndo.setEnabled(true);
this.pencilMarkButton.setEnabled(true);
}
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton14ActionPerformed
// TODO add your handling code here:
openHelp();
}// GEN-LAST:event_jButton14ActionPerformed
private void openHelp() {
// TODO Auto-generated method stub
}
private void btnNewGameActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnNewGameActionPerformed
this.setMessage("");
DifficultyLevel difficulty = null;
if (radEasy.isSelected()) {
difficulty = DifficultyLevel.Easy;
} else if (radMedium.isSelected()) {
difficulty = DifficultyLevel.Medium;
} else {
difficulty = DifficultyLevel.Hard;
}
Puzzle puzzle = this.puzzleRepo.getPuzzle(difficulty);
loadSession(puzzle, null);
}
private void pencilMarkMode(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnHintActionPerformed
if (this.gameSession == null) {
return;
}
boolean isPencilMarkMode = this.pencilMarkButton.isSelected();
this.gameSession.setPencilMarkMode(isPencilMarkMode);
this.btnHint.setEnabled(!isPencilMarkMode);
this.btnRedo.setEnabled(!isPencilMarkMode);
this.btnUndo.setEnabled(!isPencilMarkMode);
this.btnCheck.setEnabled(!isPencilMarkMode);
this.gameBoard.populatePanel(gameSession, true, isPencilMarkMode,
this.numberInputPad);
}
/**
* @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) ">
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SudokuGUI_Mark2.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SudokuGUI_Mark2.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SudokuGUI_Mark2.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SudokuGUI_Mark2.class.getName())
.log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new SudokuGUI_Mark2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCheck;
private javax.swing.JButton btnHint;
private javax.swing.JButton btnNewGame;
private javax.swing.JButton btnRedo;
private javax.swing.JButton btnUndo;
private javax.swing.ButtonGroup buttonGroup1;
private BoardGUI gameBoard;
private javax.swing.JButton btnSave; /* name changed from jButton10 */
private javax.swing.JButton btnLoad; /* name changed from jButton11 */
private javax.swing.JButton jButton14;
private javax.swing.JRadioButton radEasy;
private javax.swing.JRadioButton radHard;
private javax.swing.JRadioButton radMedium;
private javax.swing.JTextArea txtAreaMessage;
// End of variables declaration//GEN-END:variables
private JToggleButton pencilMarkButton;
private NumberButtonGUI numberInputPad;
private MouseAdapter buildNumberInputMouseAdapter() {
return new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
gameBoard.mouseClickedTaskForNumberInput(mouseEvent);
}
};
}
} |
package org.pfaa.core.item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class ColoredBlockItem extends ItemBlock {
public ColoredBlockItem(Block block) {
super(block);
}
@Override
@SideOnly(Side.CLIENT)
public int getColorFromItemStack(ItemStack itemStack, int par2) {
return this.field_150939_a.colorMultiplier(null, 0, 0, 0);
}
} |
package edu.stanford.nlp.naturalli;
import edu.smu.tspell.wordnet.Synset;
import edu.smu.tspell.wordnet.SynsetType;
import edu.smu.tspell.wordnet.WordNetDatabase;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.semgraph.semgrex.SemgrexPattern;
import edu.stanford.nlp.util.Execution;
import edu.stanford.nlp.util.Interner;
import edu.stanford.nlp.util.Lazy;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
/**
* Static resources; e.g., indexers.
*
* TODO(gabor) handle numbers
*
* @author Gabor Angeli
*/
public class StaticResources {
@Execution.Option(name="vocab_file", gloss="The location of the vocabulary file")
private static Lazy<String> vocabFile = Lazy.of(() -> System.getenv("VOCAB_FILE") == null ? "etc/vocab.tab.gz" : System.getenv("VOCAB_FILE"));
@Execution.Option(name="sense_file", gloss="The location of the sense mapping file")
private static Lazy<String> senseFile = Lazy.of( () -> System.getenv("VOCAB_FILE") == null ? "etc/sense.tab.gz" : System.getenv("SENSE_FILE") );
@Execution.Option(name="wordnet_file", gloss="The location of the WordNet synset mapping file")
private static Lazy<String> wordnetFile = Lazy.of( () -> System.getenv("WORDNET_FILE") == null ? "etc/wordnet.tab.gz" : System.getenv("WORDNET_FILE") );
private static Map<String, Integer> PHRASE_INDEXER = new HashMap<String, Integer>() {{
long startTime = System.currentTimeMillis();
System.err.print("Reading phrase indexer...");
for (String line : IOUtils.readLines(vocabFile.get())) {
String[] fields = line.split("\t");
put(fields[1], Integer.parseInt(fields[0]));
}
System.err.println("done. [" + Redwood.formatTimeDifference(System.currentTimeMillis() - startTime) + "]");
}};
private static Map<String, Integer> LOWERCASE_PHRASE_INDEXER = new HashMap<String, Integer>() {{
long startTime = System.currentTimeMillis();
System.err.print("Reading lowercase phrase indexer...");
for (String line : IOUtils.readLines(vocabFile.get())) {
String[] fields = line.split("\t");
put(fields[1].toLowerCase(), Integer.parseInt(fields[0]));
}
System.err.println("done. [" + Redwood.formatTimeDifference(System.currentTimeMillis() - startTime) + "]");
}};
public static Function<String, Integer> INDEXER = (String gloss) -> {
boolean isLower = true;
for (int i = 0; i < gloss.length(); ++i) {
if (Character.isUpperCase(gloss.charAt(i))) {
isLower = false;
}
}
if (isLower) {
Integer index = PHRASE_INDEXER.get(gloss);
return index == null ? -1 : index;
} else {
String lower = gloss.toLowerCase();
Integer index = LOWERCASE_PHRASE_INDEXER.get(lower);
if (index != null) {
Integer betterIndex = PHRASE_INDEXER.get(gloss);
if (betterIndex != null) {
return betterIndex;
}
betterIndex = PHRASE_INDEXER.get(lower);
if (betterIndex != null) {
return betterIndex;
}
return index;
}
return -1;
}
};
public static Map<Integer, Map<String, Integer>> SENSE_INDEXER = Collections.unmodifiableMap(new HashMap<Integer, Map<String, Integer>>(){{
long startTime = System.currentTimeMillis();
System.err.print("Reading sense indexer...");
for (String line : IOUtils.readLines(senseFile.get())) {
String[] fields = line.split("\t");
int word = Integer.parseInt(fields[0]);
Map<String, Integer> definitions = this.get(word);
if (definitions == null) {
definitions = new HashMap<>();
put(word, definitions);
}
definitions.put(fields[2], Integer.parseInt(fields[1]));
}
System.err.println("done. [" + Redwood.formatTimeDifference(System.currentTimeMillis() - startTime) + "]");
}});
public static Map<Pair<String, Integer>, Synset[]> SYNSETS = new HashMap<>();
static {
long startTime = System.currentTimeMillis();
System.err.print("Reading synsets...");
String file = wordnetFile.get();
try {
SYNSETS = IOUtils.readObjectFromURLOrClasspathOrFileSystem(file);
} catch (IOException e) {
System.err.print("[no saved model; re-computing]...{");
Interner<MinimalSynset> interner = new Interner<>();
WordNetDatabase wordnet = WordNetDatabase.getFileInstance();
int count = 0;
int incr = PHRASE_INDEXER.size() / 100;
for (String entry : PHRASE_INDEXER.keySet()) {
if ( (++count % incr) == 0) {
System.err.print("-");
}
for (SynsetType type : SynsetType.ALL_TYPES) {
Synset[] synsets = wordnet.getSynsets(entry, type);
if (synsets != null && synsets.length > 0) {
for (int i = 0; i < synsets.length; ++i) {
synsets[i] = interner.intern(new MinimalSynset(synsets[i]));
}
SYNSETS.put(Pair.makePair(entry, type.getCode()), synsets);
}
}
Synset[] allSynsets = wordnet.getSynsets(entry);
if (allSynsets != null) {
for (int i = 0; i < allSynsets.length; ++i) {
allSynsets[i] = interner.intern(new MinimalSynset(allSynsets[i]));
}
SYNSETS.put(Pair.makePair(entry, null), allSynsets);
}
}
System.err.print("}...");
try {
IOUtils.writeObjectToFile(SYNSETS, file);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
System.err.println("done. [" + Redwood.formatTimeDifference(System.currentTimeMillis() - startTime) + "]");
}
/**
* A set of Semgrex patterns which indicate that the target can move in the meronymy relation.
*/
public static Map<String, Set<SemgrexPattern>> MERONYM_TRIGGERS = Collections.unmodifiableMap(new HashMap<String,Set<SemgrexPattern>>() {{
if (!containsKey("arrive")) { put("arrive", new HashSet<>()); }
get("arrive").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:arrive} > prep_in {}=place)"));
if (!containsKey("say")) { put("say", new HashSet<>()); }
get("say").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:say} > prep_in {}=place)"));
if (!containsKey("visit")) { put("visit", new HashSet<>()); }
get("visit").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:visit} > dobj {}=place)"));
if (!containsKey("be")) { put("be", new HashSet<>()); }
get("be").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:be} > prep_in {}=place)"));
if (!containsKey("bear")) { put("bear", new HashSet<>()); }
get("bear").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:bear} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("bear")) { put("bear", new HashSet<>()); }
get("bear").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:bear} > prep_in {}=place)"));
if (!containsKey("tell")) { put("tell", new HashSet<>()); }
get("tell").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:tell} > prep_in {}=place)"));
if (!containsKey("win")) { put("win", new HashSet<>()); }
get("win").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:win} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < prep_with ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("arrest")) { put("arrest", new HashSet<>()); }
get("arrest").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:arrest} > prep_in {}=place)"));
if (!containsKey("report")) { put("report", new HashSet<>()); }
get("report").add(SemgrexPattern.compile("{}=person < prep_from ({lemma:report} > prep_from {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < prep_with ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < prep_in ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("report")) { put("report", new HashSet<>()); }
get("report").add(SemgrexPattern.compile("{}=person < prep_from ({lemma:report} > prep_from {}=place)"));
if (!containsKey("report")) { put("report", new HashSet<>()); }
get("report").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:report} > prep_from {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < dobj ({lemma:meet} > rcmod {}=place)"));
if (!containsKey("win")) { put("win", new HashSet<>()); }
get("win").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:win} > prep_in {}=place)"));
if (!containsKey("be")) { put("be", new HashSet<>()); }
get("be").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:be} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < dobj ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("live")) { put("live", new HashSet<>()); }
get("live").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:live} > prep_in {}=place)"));
if (!containsKey("launch")) { put("launch", new HashSet<>()); }
get("launch").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:launch} > prep_in {}=place)"));
if (!containsKey("hold")) { put("hold", new HashSet<>()); }
get("hold").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:hold} > prep_in {}=place)"));
if (!containsKey("grow")) { put("grow", new HashSet<>()); }
get("grow").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:grow} > prep_in {}=place)"));
if (!containsKey("disappear")) { put("disappear", new HashSet<>()); }
get("disappear").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:disappear} > prep_in {}=place)"));
if (!containsKey("attend")) { put("attend", new HashSet<>()); }
get("attend").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:attend} > prep_in {}=place)"));
if (!containsKey("serve")) { put("serve", new HashSet<>()); }
get("serve").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:serve} > rcmod {}=place)"));
if (!containsKey("write")) { put("write", new HashSet<>()); }
get("write").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:write} > prep_in {}=place)"));
if (!containsKey("be")) { put("be", new HashSet<>()); }
get("be").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:be} > prep_in {}=place)"));
if (!containsKey("warn")) { put("warn", new HashSet<>()); }
get("warn").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:warn} > prep_in {}=place)"));
if (!containsKey("visit")) { put("visit", new HashSet<>()); }
get("visit").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:visit} > prep_in {}=place)"));
if (!containsKey("visit")) { put("visit", new HashSet<>()); }
get("visit").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:visit} > prep_in {}=place)"));
if (!containsKey("vanish")) { put("vanish", new HashSet<>()); }
get("vanish").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:vanish} > prep_in {}=place)"));
if (!containsKey("tell")) { put("tell", new HashSet<>()); }
get("tell").add(SemgrexPattern.compile("{}=person < dobj ({lemma:tell} > prep_in {}=place)"));
if (!containsKey("spend")) { put("spend", new HashSet<>()); }
get("spend").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:spend} > prep_in {}=place)"));
if (!containsKey("spend")) { put("spend", new HashSet<>()); }
get("spend").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:spend} > prep_in {}=place)"));
if (!containsKey("serve")) { put("serve", new HashSet<>()); }
get("serve").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:serve} > prep_in {}=place)"));
if (!containsKey("serve")) { put("serve", new HashSet<>()); }
get("serve").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:serve} > prep_in {}=place)"));
if (!containsKey("remain")) { put("remain", new HashSet<>()); }
get("remain").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:remain} > prep_in {}=place)"));
if (!containsKey("release")) { put("release", new HashSet<>()); }
get("release").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:release} > prep_in {}=place)"));
if (!containsKey("reach")) { put("reach", new HashSet<>()); }
get("reach").add(SemgrexPattern.compile("{}=person < prep_in ({lemma:reach} > prep_in {}=place)"));
if (!containsKey("preach")) { put("preach", new HashSet<>()); }
get("preach").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:preach} > prep_in {}=place)"));
if (!containsKey("open")) { put("open", new HashSet<>()); }
get("open").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:open} > prep_in {}=place)"));
if (!containsKey("mob")) { put("mob", new HashSet<>()); }
get("mob").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:mob} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("meet")) { put("meet", new HashSet<>()); }
get("meet").add(SemgrexPattern.compile("{}=person < dobj ({lemma:meet} > prep_in {}=place)"));
if (!containsKey("live")) { put("live", new HashSet<>()); }
get("live").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:live} > prep_in {}=place)"));
if (!containsKey("kill")) { put("kill", new HashSet<>()); }
get("kill").add(SemgrexPattern.compile("{}=person < prep_by ({lemma:kill} > prep_in {}=place)"));
if (!containsKey("kill")) { put("kill", new HashSet<>()); }
get("kill").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:kill} > prep_in {}=place)"));
if (!containsKey("kidnap")) { put("kidnap", new HashSet<>()); }
get("kidnap").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:kidnap} > prep_in {}=place)"));
if (!containsKey("jail")) { put("jail", new HashSet<>()); }
get("jail").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:jail} > prep_in {}=place)"));
if (!containsKey("be")) { put("be", new HashSet<>()); }
get("be").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:be} > prep_in {}=place)"));
if (!containsKey("be")) { put("be", new HashSet<>()); }
get("be").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:be} > prep_in {}=place)"));
if (!containsKey("imprison")) { put("imprison", new HashSet<>()); }
get("imprison").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:imprison} > prep_in {}=place)"));
if (!containsKey("hospitalize")) { put("hospitalize", new HashSet<>()); }
get("hospitalize").add(SemgrexPattern.compile("{}=person < prep_in ({lemma:hospitalize} > prep_in {}=place)"));
if (!containsKey("hospitalise")) { put("hospitalise", new HashSet<>()); }
get("hospitalise").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:hospitalise} > prep_in {}=place)"));
if (!containsKey("hide")) { put("hide", new HashSet<>()); }
get("hide").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:hide} > prep_in {}=place)"));
if (!containsKey("hold")) { put("hold", new HashSet<>()); }
get("hold").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:hold} > prep_in {}=place)"));
if (!containsKey("hold")) { put("hold", new HashSet<>()); }
get("hold").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:hold} > prep_in {}=place)"));
if (!containsKey("grow")) { put("grow", new HashSet<>()); }
get("grow").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:grow} > prep_in {}=place)"));
if (!containsKey("give")) { put("give", new HashSet<>()); }
get("give").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:give} > prep_in {}=place)"));
if (!containsKey("find")) { put("find", new HashSet<>()); }
get("find").add(SemgrexPattern.compile("{}=person < agent ({lemma:find} > prep_in {}=place)"));
if (!containsKey("fight")) { put("fight", new HashSet<>()); }
get("fight").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:fight} > prep_in {}=place)"));
if (!containsKey("eliminate")) { put("eliminate", new HashSet<>()); }
get("eliminate").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:eliminate} > prep_in {}=place)"));
if (!containsKey("educate")) { put("educate", new HashSet<>()); }
get("educate").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:educate} > prep_in {}=place)"));
if (!containsKey("die")) { put("die", new HashSet<>()); }
get("die").add(SemgrexPattern.compile("{}=person < pobj ({lemma:die} > prep_in {}=place)"));
if (!containsKey("die")) { put("die", new HashSet<>()); }
get("die").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:die} > prep_in {}=place)"));
if (!containsKey("cremate")) { put("cremate", new HashSet<>()); }
get("cremate").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:cremate} > prep_in {}=place)"));
if (!containsKey("capture")) { put("capture", new HashSet<>()); }
get("capture").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:capture} > prep_in {}=place)"));
if (!containsKey("bury")) { put("bury", new HashSet<>()); }
get("bury").add(SemgrexPattern.compile("{}=person < partmod ({lemma:bury} > prep_in {}=place)"));
if (!containsKey("bury")) { put("bury", new HashSet<>()); }
get("bury").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:bury} > prep_in {}=place)"));
if (!containsKey("bear")) { put("bear", new HashSet<>()); }
if (!containsKey("bear")) { put("bear", new HashSet<>()); }
get("bear").add(SemgrexPattern.compile("{}=person < prep_in ({lemma:bear} > prep_in {}=place)"));
if (!containsKey("beat")) { put("beat", new HashSet<>()); }
get("beat").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:beat} > prep_in {}=place)"));
if (!containsKey("apprehend")) { put("apprehend", new HashSet<>()); }
get("apprehend").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:apprehend} > prep_in {}=place)"));
if (!containsKey("admit")) { put("admit", new HashSet<>()); }
get("admit").add(SemgrexPattern.compile("{}=person < nsubjpass ({lemma:admit} > prep_in {}=place)"));
if (!containsKey("host")) { put("host", new HashSet<>()); }
get("host").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:host} > prep_from {}=place)"));
if (!containsKey("triumph")) { put("triumph", new HashSet<>()); }
get("triumph").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:triumph} > prep_at {}=place)"));
if (!containsKey("torture")) { put("torture", new HashSet<>()); }
get("torture").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:torture} > prep_at {}=place)"));
if (!containsKey("start")) { put("start", new HashSet<>()); }
get("start").add(SemgrexPattern.compile("{}=person < nsubj ({lemma:start} > prep_at {}=place)"));
if (!containsKey("injure")) { put("injure", new HashSet<>()); }
get("injure").add(SemgrexPattern.compile("{}=person < rcmod ({lemma:injure} > prep_at {}=place)"));
}});
/**
* Load the static resources (this really just amounts to loading the class via the classloader).
*/
public static void load() { }
/**
* Test out loading the static resources. This function doesn't actually do anything interesting
*/
public static void main(String[] args) {
System.err.println("Static resources loaded.");
}
} |
package edu.wustl.cab2b.client.ui.util;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.tree.DefaultMutableTreeNode;
import org.jdesktop.swingx.JXErrorDialog;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.wustl.cab2b.client.ui.MainSearchPanel;
import edu.wustl.cab2b.client.ui.controls.Cab2bLabel;
import edu.wustl.cab2b.client.ui.mainframe.UserValidator;
import edu.wustl.cab2b.common.BusinessInterface;
import edu.wustl.cab2b.common.datalist.IDataRow;
import edu.wustl.cab2b.common.ejb.EjbNamesConstants;
import edu.wustl.cab2b.common.ejb.queryengine.QueryEngineBusinessInterface;
import edu.wustl.cab2b.common.ejb.queryengine.QueryEngineHome;
import edu.wustl.cab2b.common.errorcodes.ErrorCodeHandler;
import edu.wustl.cab2b.common.exception.CheckedException;
import edu.wustl.cab2b.common.exception.RuntimeException;
import edu.wustl.cab2b.common.locator.Locator;
import edu.wustl.cab2b.common.locator.LocatorException;
import edu.wustl.cab2b.common.queryengine.ICab2bQuery;
import edu.wustl.cab2b.common.queryengine.result.IQueryResult;
import edu.wustl.cab2b.common.util.Utility;
import edu.wustl.common.util.logger.Logger;
/**
* @author Chetan B H
* @author Mahesh Iyer
*/
public class CommonUtils {
// Constant storing enumerated values for DAG-Images
public static enum DagImages {
DocumentPaperIcon, PortImageIcon, ArrowSelectIcon, ArrowSelectMOIcon, SelectIcon, selectMOIcon, ParenthesisIcon, ParenthesisMOIcon
};
/**
* Method to get BusinessInterface object for given bean name and home class
* object
*
* @param beanName
* Name of the bean class
* @param homeClassForBean
* HomeClass object for this bean
* @param parentComponent
* The parent component which will be parent for displaying
* exception messages
* @return the businessInterface object for given bean name
*/
public static BusinessInterface getBusinessInterface(String beanName, Class homeClassForBean,
Component parentComponent) {
BusinessInterface businessInterface = null;
try {
businessInterface = Locator.getInstance().locate(beanName, homeClassForBean);
} catch (LocatorException e1) {
handleException(e1, parentComponent, true, true, false, false);
}
return businessInterface;
}
/**
* Method to disable all components from the specified container
* @param container
*/
public static void disableAllComponent(Container container) {
for (int i = 0; i < container.getComponentCount(); i++) {
container.getComponent(i).setEnabled(false);
if (container.getComponent(i) instanceof Container)
disableAllComponent((Container) container.getComponent(i));
}
}
/**
* Method to get BusinessInterface object for given bean name and home class
* object
*
* @param beanName
* Name of the bean class
* @param homeClassForBean
* HomeClass object for this bean
* @return the businessInterface object for given bean name
* @throws LocatorException
* Throws exception if BusinessInterface is not located for
* given bean name
*/
public static BusinessInterface getBusinessInterface(String beanName, Class homeClassForBean)
throws LocatorException {
return Locator.getInstance().locate(beanName, homeClassForBean);
}
/**
* A Utility method to handle exception, logging and showing it in a dialog.
*/
public static void handleException(Exception exception, Component parentComponent,
boolean shouldShowErrorDialog, boolean shouldLogException,
boolean shouldPrintExceptionInConsole, boolean shouldKillApp) {
String errorMessageForLog = "";
String errorMessageForDialog = "Error";
exception = getOriginalException(exception);
/*
* Cab2b application specific error code, available only with Cab2b's
* CheckedException and RuntimeException
*/
String errorCode = "";
/*
* Cab2b application specific error messages, corresponding to every
* error code.
*/
String customErrorMessage = "";
if (exception instanceof CheckedException) {
CheckedException checkedException = (CheckedException) exception;
errorCode = checkedException.getErrorCode();
customErrorMessage = ErrorCodeHandler.getErrorMessage(errorCode);
errorMessageForDialog = customErrorMessage;
errorMessageForLog = errorCode + ":" + customErrorMessage;
} else if (exception instanceof RuntimeException) {
RuntimeException runtimeException = (RuntimeException) exception;
errorCode = runtimeException.getErrorCode();
customErrorMessage = ErrorCodeHandler.getErrorMessage(errorCode);
errorMessageForDialog = customErrorMessage;
errorMessageForLog = errorCode + ":" + customErrorMessage;
} else if (exception instanceof LocatorException) {
LocatorException locatorException = (LocatorException) exception;
errorCode = locatorException.getErrorCode();
customErrorMessage = ErrorCodeHandler.getErrorMessage(errorCode);
errorMessageForDialog = customErrorMessage;
errorMessageForLog = errorCode + ":" + customErrorMessage;
} else {
errorMessageForLog = exception.getMessage();
}
if (shouldLogException) {
Logger.out.error(errorMessageForLog, exception);
}
if (shouldShowErrorDialog) {
JXErrorDialog.showDialog(parentComponent, "caB2B - Application Error", errorMessageForDialog,
exception);
}
if (shouldPrintExceptionInConsole) {
exception.printStackTrace();
}
if (shouldKillApp) {
System.exit(0);
}
}
/**
* This method traverses the whole hierarchy of the given exception to check
* whether there is any exception which is {@link CheckedException} OR {@link LocatorException} OR{@link RuntimeException}
* If yes it returns it otherwise it returns the original passed exception.
* @param cause exception to verify
* @return The root exception
*/
private static Exception getOriginalException(Exception cause) {
if(cause!=null && cause instanceof Exception ) {
if(cause instanceof CheckedException || cause instanceof LocatorException || cause instanceof RuntimeException) {
return cause;
} else {
return getOriginalException((Exception) cause.getCause());
}
}
return cause;
}
/**
* The method executes the encapsulated B2B query. For this it uses the
* Locator service to locate an instance of the QueryEngineBusinessInterface
* and uses the interace to remotely execute the query.
*/
public static IQueryResult executeQuery(ICab2bQuery query, JComponent comp) throws RemoteException {
QueryEngineBusinessInterface queryEngineBus = (QueryEngineBusinessInterface) getBusinessInterface(
EjbNamesConstants.QUERY_ENGINE_BEAN,
QueryEngineHome.class,
comp);
return executeQuery(query, queryEngineBus, comp);
}
/**
* The method executes the encapsulated B2B query. For this it uses the
* Locator service to locate an instance of the QueryEngineBusinessInterface
* and uses the interace to remotely execute the query.
*/
public static IQueryResult executeQuery(ICab2bQuery query, QueryEngineBusinessInterface queryEngineBus,
JComponent comp) throws RemoteException {
IQueryResult iQueryResult = null;
try {
iQueryResult = executeQuery(query, queryEngineBus);
} catch (RuntimeException re) {
handleException(re, comp, true, false, false, false);
} /*catch (RemoteException e1) {
//CheckedException e = new CheckedException(e1.getMessage(), e1, ErrorCodeConstants.QM_0004);
handleException(getCab2bException(e1), comp, true, false, false, false);
}*/
return iQueryResult;
}
/**
* The method executes the encapsulated B2B query. For this it uses the
* Locator service to locate an instance of the QueryEngineBusinessInterface
* and uses the interace to remotely execute the query.
*
* @param query
* @param queryEngineBus
* @throws RuntimeException
* @throws RemoteException
*/
public static IQueryResult executeQuery(ICab2bQuery query, QueryEngineBusinessInterface queryEngineBus)
throws RuntimeException, RemoteException {
return queryEngineBus.executeQuery(query, UserValidator.getProxy());
}
/**
* Method to get count of bit 1 set in given BitSet
*
* @param bitSet
* The BitSet object in which to find count
* @return The count of 1 bit in BitSet
*/
public static int getCountofOnBits(BitSet bitSet) {
int count = 0;
for (int i = 0; i < bitSet.size(); i++) {
if (bitSet.get(i))
count++;
}
return count;
}
/**
* Utility method to find the number of occurrence of a particular character
* in the String
*/
public static int countCharacterIn(String str, char character) {
int count = 0;
char[] chars = str.toCharArray();
for (char characterInStr : chars) {
if (characterInStr == character)
count++;
}
return count;
}
/**
* Utility method to capitalise first character in the String
*/
static String capitalizeFirstCharacter(String str) {
char[] chars = str.toCharArray();
char firstChar = chars[0];
chars[0] = Character.toUpperCase(firstChar);
return new String(chars);
}
static String[] splitCamelCaseString(String str, int countOfUpperCaseLetter) {
String[] splitStrings = new String[countOfUpperCaseLetter + 1];
char[] chars = str.toCharArray();
int firstIndex = 0;
int lastIndex = 0;
int splitStrCount = 0;
for (int i = 1; i < chars.length; i++) // change indexing from "chars"
// 1 to length
{
char character = chars[i];
char nextCharacter;
char previousCharacter;
if (splitStrCount != countOfUpperCaseLetter) {
if (Character.isUpperCase(character)) {
if (i == (chars.length - 1)) {
splitStrings[splitStrCount++] = str.substring(0, i);
char[] lasrCharIsUpperCase = new char[1];
lasrCharIsUpperCase[0] = character;
splitStrings[splitStrCount++] = new String(lasrCharIsUpperCase);
} else {
lastIndex = i;
previousCharacter = chars[i - 1];
nextCharacter = chars[i + 1];
if (Character.isUpperCase(previousCharacter)
&& Character.isLowerCase(nextCharacter)
|| Character.isLowerCase(previousCharacter)
&& Character.isUpperCase(nextCharacter)
|| (Character.isLowerCase(previousCharacter) && Character.isLowerCase(nextCharacter))) {
String split = str.substring(firstIndex, lastIndex);
if (splitStrCount == 0) {
split = capitalizeFirstCharacter(split);
}
splitStrings[splitStrCount] = split;
splitStrCount++;
firstIndex = lastIndex;
} else {
continue;
}
}
}
} else {
firstIndex = lastIndex;
lastIndex = str.length();
String split = str.substring(firstIndex, lastIndex);
splitStrings[splitStrCount] = split;
break;
}
}
return splitStrings;
}
/**
* Utility method to count upper case characters in the String
*/
static int countUpperCaseLetters(String str) {
/*
* This is the count of Capital letters in a string excluding first
* character, and continuos uppercase letter in the string.
*/
int countOfCapitalLetters = 0;
char[] chars = str.toCharArray();
for (int i = 1; i < chars.length; i++) {
char character = chars[i];
char nextCharacter = 'x';
char prevCharacter = chars[i - 1];
if ((i + 1) < chars.length)
nextCharacter = chars[i + 1];
if ((Character.isUpperCase(character) && Character.isUpperCase(prevCharacter)
&& Character.isLowerCase(nextCharacter) && i != chars.length - 1)
|| (Character.isUpperCase(character) && Character.isLowerCase(prevCharacter) && Character.isUpperCase(nextCharacter))
|| (Character.isUpperCase(character) && Character.isLowerCase(prevCharacter) && Character.isLowerCase(nextCharacter)))
countOfCapitalLetters++;
}
return countOfCapitalLetters;
}
public static String getFormattedString(String str) {
String returner = "";
if (str.equalsIgnoreCase("id")) {
return "Identifier";
}
String[] splitStrings = null;
int upperCaseCount = countUpperCaseLetters(str);
if (upperCaseCount > 0) {
splitStrings = splitCamelCaseString(str, upperCaseCount);
returner = getFormattedString(splitStrings);
} else {
returner = capitalizeFirstCharacter(str);
}
return returner;
}
public static String getFormattedString(String[] splitStrings) {
String returner = "";
for (int i = 0; i < splitStrings.length; i++) {
String str = splitStrings[i];
if (i == splitStrings.length - 1) {
returner += str;
} else {
returner += str + " ";
}
}
return returner;
}
/**
* Utility method to get a Dimension relative to a reference Dimension.
*
* @param referenceDimnesion
* @param percentageWidth
* @param percentageHeight
* @return a new relative dimension.
*/
public static Dimension getRelativeDimension(Dimension referenceDimnesion, float percentageWidth,
float percentageHeight) {
if (referenceDimnesion.height <= 0 || referenceDimnesion.width <= 0) {
throw new IllegalArgumentException("Reference dimension can't be (0,0) or less");
}
if ((0.0f > percentageHeight || percentageHeight > 1.0f)
|| (0.0f > percentageWidth || percentageWidth > 1.0f)) {
throw new IllegalArgumentException(
"Percentage width and height should be less than 1.0 and greater than 1.0");
}
Dimension relativeDimension = new Dimension();
relativeDimension.setSize(percentageWidth * referenceDimnesion.getWidth(), percentageHeight
* referenceDimnesion.getHeight());
return relativeDimension;
}
/**
* Splits the string with qualifier
*
* @param string
* @param textQualifier
* @param seperator
*/
public static ArrayList<String> splitStringWithTextQualifier(String string, char textQualifier, char delimeter) {
ArrayList<String> tokenList = new ArrayList<String>();
StringBuffer token = new StringBuffer();
boolean isTextQualifierStart = false;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == textQualifier) {
if (isTextQualifierStart == true) {
if (token.length() != 0) {
tokenList.add(token.toString().trim());
}
isTextQualifierStart = false;
token.setLength(0);
} else {
isTextQualifierStart = true;
}
} else if (string.charAt(i) != delimeter) {
token.append(string.charAt(i));
} else {
if (isTextQualifierStart == true) {
token.append(string.charAt(i));
} else {
if (token.length() != 0) {
tokenList.add(token.toString().trim());
}
token.setLength(0);
}
}
}
//append last string
String finalToken = token.toString().trim();
if (isTextQualifierStart == true) {
if (!finalToken.equals("")) {
tokenList.add("\"" + finalToken);
}
} else {
if (!finalToken.equals("")) {
tokenList.add(finalToken);
}
}
return tokenList;
}
/**
* Removes any continuos space chatacters(2 or more) that may appear at the
* begining, end or in between to words.
*
* @param str
* string with continuos space characters.
* @return procssed string with no continuos space characters.
*/
public static String removeContinuousSpaceCharsAndTrim(String str) {
char[] charsWithoutContinousSpaceChars = new char[str.length()];
char prevCharacter = 'a';
int index = 0;
for (char character : str.toCharArray()) {
if (!(Character.isWhitespace(character) && Character.isWhitespace(prevCharacter))) {
charsWithoutContinousSpaceChars[index++] = character;
}
prevCharacter = character;
}
String result = new String(charsWithoutContinousSpaceChars);
return result.trim();
}
/**
* This method takes the node string and traverses the tree till it finds
* the node matching the string. If the match is found the node is returned
* else null is returned
*
* @param nodeStr
* node string to search for
* @return tree node
*/
public static DefaultMutableTreeNode searchNode(DefaultMutableTreeNode rootNode, Object userObject) {
DefaultMutableTreeNode node = null;
// Get the enumeration
Enumeration benum = rootNode.breadthFirstEnumeration();
// iterate through the enumeration
while (benum.hasMoreElements()) {
// get the node
node = (DefaultMutableTreeNode) benum.nextElement();
// match the string with the user-object of the node
if (userObject.equals(node.getUserObject())) {
// tree node with string found
return node;
}
}
// tree node with string node found return null
return null;
}
/**
* Method to get identifier attribute index for given list of attibutes
*
* @param attributes
* Ordered list of attributes
* @return index of Id attribute
*/
public static int getIdAttributeIndexFromAttributes(List<AttributeInterface> attributes) {
int identifierIndex = -1;
for (int i = 0; i < attributes.size(); i++) {
AttributeInterface attribute = attributes.get(i);
if (Utility.isIdentifierAttribute(attribute)) {
identifierIndex = i;
break;
}
}
return identifierIndex;
}
/**
* check the if the specified string is a valid name for an experiment,
* category etc.
*
* @param name
* the name
* @return true if name is valid otherwise false
*/
public static boolean isNameValid(String name) {
if (name == null || name.trim().equals("")) {
return false;
}
return true;
}
/**
* This method returns the Component form the parent Container given the
* name of the Component
*
* @param parentContainer
* the parent Container
* @param panelName
* name of the Component
* @return the desired Component if present; null otherwise
*/
public static Component getComponentByName(final Container parentContainer, final String panelName) {
Component requiredComponent = null;
Component[] components = parentContainer.getComponents();
for (Component component : components) {
String componentName = component.getName();
if (componentName != null && componentName.equals(panelName)) {
requiredComponent = component;
break;
}
}
return requiredComponent;
}
/**
* This Method returns the maximum dimension required to generate the label
* for the given attributes.
*
* @param attributeList
* @return
*/
public static Dimension getMaximumLabelDimension(Collection<AttributeInterface> attributeList) {
Dimension maxLabelDimension = new Dimension(0, 0);
for (AttributeInterface attribute : attributeList) {
String formattedString = attribute.getName();
if (!Utility.isCategory(attribute.getEntity())) {
formattedString = CommonUtils.getFormattedString(formattedString);
}
Cab2bLabel tempLabel = new Cab2bLabel(formattedString + " : ");
if (maxLabelDimension.width < tempLabel.getPreferredSize().width) {
maxLabelDimension = tempLabel.getPreferredSize();
}
}
return maxLabelDimension;
}
/**
* @return Popular categories at this point
*/
public static Vector getPopularSearchCategories() {
/* TODO These default Search Categories will be removed after its support*/
Vector<String> popularSearchCategories = new Vector<String>();
popularSearchCategories.add("Gene Annotation");
popularSearchCategories.add("Genomic Identifiers");
popularSearchCategories.add("Literature-based Gene Association");
//popularSearchCategories.add("Microarray Annotation");
popularSearchCategories.add("Orthologus Gene");
return popularSearchCategories;
}
/**
* @return Recent search queries
*/
public static Vector getUserSearchQueries() {
/* TODO These default UserSearchQueries will be removed later after SAVE QUERY support*/
Vector<String> userSearchQueries = new Vector<String>();
userSearchQueries.add("Prostate Cancer Microarray Data");
userSearchQueries.add("Glioblastoma Microarray Data");
userSearchQueries.add("High Quality RNA Biospecimens");
//userSearchQueries.add("Breast Cancer Microarrays (MOE430+2.0)");
userSearchQueries.add("Adenocarcinoma Specimens");
userSearchQueries.add("Lung Primary Tumor");
return userSearchQueries;
}
/**
* @return All the experiments performed by the user.
*/
public static Vector getExperiments() {
/* TODO These default experiments will be removed later on*/
Vector<String> experiments = new Vector<String>();
experiments.add("Breast Cancer Microarrays (Hu133+2.0)");
experiments.add("Comparative study of specimens between pre and post therapy");
experiments.add("Acute Myelogenous Leukemia Microarrays");
experiments.add("Patients with newly diagnose Adenocarcinoma");
return experiments;
}
/**
* @return Popular categories at this point
*/
public static Vector getUserSearchCategories() {
/* TODO These default Search Categories will be removed after its support*/
Vector<String> userSearchCategories = new Vector<String>();
//userSearchCategories.add("Gene Annotation");
userSearchCategories.add("Microarray Annotation");
userSearchCategories.add("Tissue Biospecimens");
userSearchCategories.add("Molecular Biospecimens");
userSearchCategories.add("Participant Details");
return userSearchCategories;
}
public static Exception getCab2bException(Exception e) {
while (e.getCause() != null) {
if (e.getCause() instanceof Exception) {
Exception e1 = (Exception) e.getCause();
if (e1 instanceof CheckedException || e1 instanceof RuntimeException) {
return e1;
}
e = e1;
}
}
return e;
}
public static String escapeString(String input) {
if (input.indexOf(",") != -1) {
input = "\"" + input + "\"";
}
return input;
}
/**
* Method which will return number of elements in current datalist
* @return
*/
public static int getDataListSize() {
IDataRow rootNode = MainSearchPanel.getDataList().getRootDataRow();
// This node is hidden node in the tree view
return rootNode.getChildren().size();
}
} |
package org.vorthmann.zome.ui;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.ToolTipManager;
import org.vorthmann.j3d.J3dComponentFactory;
import org.vorthmann.j3d.Platform;
import org.vorthmann.ui.Controller;
import org.vorthmann.ui.ExclusiveAction;
import com.vzome.desktop.controller.ViewPlatformControlPanel;
public class DocumentFrame extends JFrame implements PropertyChangeListener, ControlActions
{
private static final long serialVersionUID = 1L;
protected final Controller mController, toolsController;
private final ModelPanel modelPanel;
private final JTabbedPane tabbedPane = new JTabbedPane();
private final ExclusiveAction.Excluder mExcluder = new ExclusiveAction.Excluder( this );
private boolean isEditor, fullPower, readerPreview, canSave;
private CardLayout modelArticleCardLayout;
private static final Logger logger = Logger.getLogger( "org.vorthmann.zome.ui" );
private LessonPanel lessonPanel;
private JButton snapshotButton;
private JRadioButton articleButton, modelButton;
private JPanel viewControl, modelArticleEditPanel;
private JLabel statusText;
private Controller viewPlatform;
private Controller lessonController;
private JDialog polytopesDialog;
private final boolean developerExtras;
private final ActionListener localActions;
private File mFile = null;
private final Controller.ErrorChannel errors;
private Snapshot2dFrame snapshot2dFrame;
private ControllerFileAction saveAsAction;
public ExclusiveAction.Excluder getExcluder()
{
return mExcluder;
}
public DocumentFrame( File file, final Controller controller, PropertyChangeListener app )
{
mController = controller;
this .mFile = file;
controller .addPropertyListener( this );
toolsController = mController .getSubController( "tools" );
// TODO: compute these booleans once here, and don't recompute in DocumentMenuBar
this.readerPreview = controller .propertyIsTrue( "reader.preview" );
this.isEditor = controller .userHasEntitlement( "model.edit" ) && ! readerPreview;
this.canSave = controller .userHasEntitlement( "save.files" );
this.fullPower = isEditor ;//&& controller .userHasEntitlement( "all.tools" );
this.developerExtras = fullPower && mController .userHasEntitlement( "developer.extras" );
JFrame mZomicFrame = new JFrame( "Zomic Scripting" );
mZomicFrame.setContentPane( new ZomicEditorPanel( mZomicFrame, controller ) );
mZomicFrame.pack();
JFrame mPythonFrame = new JFrame( "Python Scripting" );
mPythonFrame .setContentPane( new PythonConsolePanel( mPythonFrame, controller ) );
mPythonFrame .pack();
polytopesDialog = new PolytopesDialog( this, controller .getSubController( "polytopes" ) );
errors = new Controller.ErrorChannel()
{
@Override
public void reportError( String errorCode, Object[] arguments )
{
if ( Controller.USER_ERROR_CODE.equals( errorCode ) ) {
errorCode = ( (Exception) arguments[0] ).getMessage();
// don't want a stack trace for a user error
logger.log( Level.WARNING, errorCode );
} else if ( Controller.UNKNOWN_ERROR_CODE.equals( errorCode ) ) {
errorCode = ( (Exception) arguments[0] ).getMessage();
logger.log( Level.WARNING, "internal error: " + errorCode, ( (Exception) arguments[0] ) );
errorCode = "internal error, see vZomeLog0.log in your home directory";
} else {
logger.log( Level.WARNING, "reporting error: " + errorCode, arguments );
// TODO use resources
}
if ( statusText != null )
statusText .setText( errorCode );
else
JOptionPane .showMessageDialog( DocumentFrame.this, errorCode, "Command Failure", JOptionPane .ERROR_MESSAGE );
}
@Override
public void clearError()
{
if ( statusText != null )
statusText .setText( "" );
}
};
controller.setErrorChannel( errors );
saveAsAction = new ControllerFileAction( new FileDialog( this ), false, "save", "vZome", mController )
{
// this happens at the very end, after choose, save, set type
@Override
protected void openApplication( File file )
{
mFile = file;
String newTitle = file.getAbsolutePath();
app .propertyChange( new PropertyChangeEvent( DocumentFrame.this, "window.title", getTitle(), newTitle ) );
}
};
final String initSystem = controller .getProperty( "symmetry" );
localActions = new ActionListener()
{
private String system = initSystem;
private final Map<String, JDialog> shapesDialogs = new HashMap<>();
private final Map<String, JDialog> directionsDialogs = new HashMap<>();
@Override
public void actionPerformed( ActionEvent e )
{
Controller delegate = controller;
String cmd = e.getActionCommand();
switch ( cmd ) {
case "close":
closeWindow();
break;
case "openURL":
String url = JOptionPane .showInputDialog( DocumentFrame.this, "Enter the URL for an online .vZome file.", "Open URL",
JOptionPane.PLAIN_MESSAGE );
try {
mController .doAction( cmd, new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, url ) );
} catch ( Exception ex )
{
ex .printStackTrace();
// TODO better error report
errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ ex } );
}
break;
case "save":
if ( mFile == null )
saveAsAction .actionPerformed( e );
else {
mController .doFileAction( "save", mFile );
}
break;
case "saveDefault":
// this is basically "save a copy...", with no choosing
String fieldName = mController.getProperty( "field.name" );
File prototype = new File( Platform.getPreferencesFolder(), "Prototypes/" + fieldName + ".vZome" );
mController .doFileAction( "save", prototype );
break;
case "snapshot.2d":
if ( snapshot2dFrame == null ) {
snapshot2dFrame = new Snapshot2dFrame( mController.getSubController( "snapshot.2d" ), new FileDialog( DocumentFrame.this ) );
}
snapshot2dFrame.setPanelSize( modelPanel .getRenderedSize() );
snapshot2dFrame.pack();
if ( ! snapshot2dFrame .isVisible() )
snapshot2dFrame.repaint();
snapshot2dFrame.setVisible( true );
break;
case "redoUntilEdit":
String number = JOptionPane.showInputDialog( null, "Enter the edit number.", "Set Edit Number",
JOptionPane.PLAIN_MESSAGE );
try {
mController .doAction( "redoUntilEdit." + number, new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "redoUntilEdit." + number ) );
} catch ( Exception e1 ) {
errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ e1 } );
}
break;
case "showToolsPanel":
tabbedPane .setSelectedIndex( 1 ); // should be "tools" tab
break;
case "showPolytopesDialog":
polytopesDialog .setVisible( true );
break;
case "showPythonWindow":
mPythonFrame .setVisible( true );
break;
case "showZomicWindow":
mZomicFrame .setVisible( true );
break;
case "setItemColor":
Color color = JColorChooser.showDialog( DocumentFrame.this, "Choose Object Color", null );
if ( color == null )
return;
int rgb = color .getRGB() & 0xffffff;
int alpha = color .getAlpha() & 0xff;
String command = "setItemColor/" + Integer.toHexString( ( rgb << 8 ) | alpha );
mController .actionPerformed( new ActionEvent( e .getSource(), e.getID(), command ) );
break;
case "setBackgroundColor":
color = JColorChooser.showDialog( DocumentFrame.this, "Choose Background Color", null );
if ( color != null )
mController .setProperty( "backgroundColor", Integer.toHexString( color.getRGB() & 0xffffff ) );
break;
case "usedOrbits":
mController .actionPerformed( e ); // TO DO exclusive
break;
case "rZomeOrbits":
case "predefinedOrbits":
case "setAllDirections":
delegate = mController .getSubController( "symmetry." + system );
delegate .actionPerformed( e );
break;
case "configureShapes":
JDialog shapesDialog = (JDialog) shapesDialogs.get( system );
if ( shapesDialog == null ) {
delegate = mController .getSubController( "symmetry." + system );
shapesDialog = new ShapesDialog( DocumentFrame.this, delegate );
shapesDialogs .put( system, shapesDialog );
}
shapesDialog .setVisible( true );
break;
case "configureDirections":
JDialog symmetryDialog = (JDialog) directionsDialogs.get( system );
if ( symmetryDialog == null ) {
delegate = mController .getSubController( "symmetry." + system );
symmetryDialog = new SymmetryDialog( DocumentFrame.this, delegate );
directionsDialogs .put( system, symmetryDialog );
}
symmetryDialog .setVisible( true );
default:
if ( cmd .startsWith( "setSymmetry." ) )
{
system = cmd .substring( "setSymmetry.".length() );
mController .actionPerformed( e ); // TODO exclusive
}
else if ( cmd .startsWith( "showProperties-" ) )
{
String key = cmd .substring( "showProperties-" .length() );
Controller subc = mController .getSubController( key + "Picking" );
JOptionPane .showMessageDialog( DocumentFrame.this, subc .getProperty( "objectProperties" ), "Object Properties",
JOptionPane.PLAIN_MESSAGE );
}
break;
}
}
};
viewPlatform = controller .getSubController( "viewPlatform" );
lessonController = controller .getSubController( "lesson" );
lessonController .addPropertyListener( this );
// Now the component containment hierarchy
JPanel outerPanel = new JPanel( new BorderLayout() );
setContentPane( outerPanel );
{
JPanel leftCenterPanel = new JPanel( new BorderLayout() );
{
if ( this .isEditor )
{
JPanel modeAndStatusPanel = new JPanel( new BorderLayout() );
JPanel articleButtonsPanel = new JPanel();
modeAndStatusPanel .add( articleButtonsPanel, BorderLayout.LINE_START );
ButtonGroup group = new ButtonGroup();
modelButton = new JRadioButton( "Model" );
modelButton .setSelected( true );
articleButtonsPanel .add( modelButton );
group .add( modelButton );
modelButton .setActionCommand( "switchToModel" );
modelButton .addActionListener( mController );
snapshotButton = new JButton( "-> capture ->" );
// String imgLocation = "/icons/snapshot.png";
// URL imageURL = getClass().getResource( imgLocation );
// if ( imageURL != null ) {
// Icon icon = new ImageIcon( imageURL, "capture model snapshot" );
// snapshotButton .setIcon( icon );
// Dimension dim = new Dimension( 50, 36 );
// snapshotButton .setPreferredSize( dim );
// snapshotButton .setMaximumSize( dim );
articleButtonsPanel .add( snapshotButton );
snapshotButton .setActionCommand( "takeSnapshot" );
snapshotButton .addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mController .actionPerformed( e ); // sends thumbnailChanged propertyChange, but no listener...
articleButton .doClick(); // switch to article mode, so now there's a listener
// now trigger the propertyChange again
lessonController .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "setView" ) );
}
} );
articleButton = new JRadioButton( "Article" );
articleButton .setEnabled( lessonController .propertyIsTrue( "has.pages" ) );
articleButton .setSelected( false );
articleButtonsPanel .add( articleButton );
group .add( articleButton );
articleButton .setActionCommand( "switchToArticle" );
articleButton .addActionListener( mController );
JPanel statusPanel = new JPanel( new BorderLayout() );
statusPanel .setBorder( BorderFactory .createEmptyBorder( 4, 4, 4, 4 ) );
statusText = new JLabel( "", JLabel.CENTER );
statusText .setBorder( BorderFactory .createLineBorder( Color.LIGHT_GRAY ) );
statusText .setForeground( Color .RED );
statusPanel .add( statusText );
modeAndStatusPanel .add( statusPanel, BorderLayout.CENTER );
leftCenterPanel .add( modeAndStatusPanel, BorderLayout.PAGE_START );
}
modelPanel = new ModelPanel( controller, this, this .isEditor, fullPower );
leftCenterPanel .add( modelPanel, BorderLayout.CENTER );
}
outerPanel.add( leftCenterPanel, BorderLayout.CENTER );
// String mag = props .getProperty( "default.magnification" );
// if ( mag != null ) {
// float magnification = Float .parseFloat( mag );
// // TODO this seems to work, but ought not to!
// viewControl .zoomAdjusted( (int) magnification );
JPanel rightPanel = new JPanel( new BorderLayout() );
{
Component trackballCanvas = ( (J3dComponentFactory) controller ) .createJ3dComponent( "controlViewer" );
viewControl = new ViewPlatformControlPanel( trackballCanvas, viewPlatform );
// this is probably moot for reader mode
rightPanel .add( viewControl, BorderLayout.PAGE_START );
modelArticleEditPanel = new JPanel();
modelArticleCardLayout = new CardLayout();
modelArticleEditPanel .setLayout( modelArticleCardLayout );
if ( this .isEditor )
{
JPanel buildPanel = new StrutBuilderPanel( DocumentFrame.this, controller .getProperty( "symmetry" ), controller, this );
if ( this .fullPower )
{
tabbedPane .addTab( "build", buildPanel );
JPanel toolsPanel = new ToolsPanel( DocumentFrame.this, toolsController );
tabbedPane .addTab( "tools", toolsPanel );
JPanel bomPanel = new PartsPanel( controller .getSubController( "parts" ) );
tabbedPane .addTab( "parts", bomPanel );
modelArticleEditPanel .add( tabbedPane, "model" );
}
else
modelArticleEditPanel .add( buildPanel, "model" );
}
{
lessonPanel = new LessonPanel( lessonController );
modelArticleEditPanel .add( lessonPanel, "article" );
}
if ( this .isEditor )
{
modelArticleCardLayout .show( modelArticleEditPanel, "model" );
modelArticleEditPanel .setMinimumSize( new Dimension( 300, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( 300, 800 ) );
}
else
{
modelArticleCardLayout .show( modelArticleEditPanel, "article" );
modelArticleEditPanel .setMinimumSize( new Dimension( 400, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( 400, 800 ) );
}
rightPanel .add( modelArticleEditPanel, BorderLayout.CENTER );
}
outerPanel.add( rightPanel, BorderLayout.LINE_END );
}
JPopupMenu.setDefaultLightWeightPopupEnabled( false );
ToolTipManager ttm = ToolTipManager.sharedInstance();
ttm .setLightWeightPopupEnabled( false );
this .setJMenuBar( new DocumentMenuBar( controller, this ) );
this.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
this.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent we )
{
closeWindow();
mController .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "documentClosed" ));
}
} );
this.pack();
this.setVisible( true );
this.setFocusable( true );
}
private ExclusiveAction getExclusiveAction( final String action )
{
return new ExclusiveAction( getExcluder() )
{
@Override
protected void doAction( ActionEvent e ) throws Exception
{
mController.doAction( action, e );
}
@Override
protected void showError( Exception e )
{
JOptionPane.showMessageDialog( DocumentFrame.this, e.getMessage(), "Command failure", JOptionPane.ERROR_MESSAGE );
}
};
}
public AbstractButton setButtonAction( String command, AbstractButton control )
{
control .setActionCommand( command );
boolean enable = true;
switch ( command ) {
// TODO: find a better way to disable these... they are found in OrbitPanel.java
case "predefinedOrbits":
case "usedOrbits":
case "setAllDirections":
enable = fullPower;
break;
case "save":
case "saveAs":
case "saveDefault":
enable = this .canSave;
break;
default:
if ( command .startsWith( "export." ) ) {
enable = this .canSave;
}
}
control .setEnabled( enable );
if ( control .isEnabled() )
{
ActionListener actionListener = this .mController;
switch ( command ) {
// these can fall through to the ApplicationUI
case "quit":
case "new":
case "new-rootTwo":
case "new-rootThree":
case "new-heptagon":
case "new-snubDodec":
case "showAbout":
case "toggleWireframe":
case "toggleOrbitViews":
case "toggleStrutScales":
case "toggleFrameLabels":
case "toggleOutlines":
actionListener = this .mController;
break;
case "open":
case "newFromTemplate":
case "openDeferringRedo":
actionListener = new ControllerFileAction( new FileDialog( this ), true, command, "vZome", mController );
break;
case "import.vef":
actionListener = new ControllerFileAction( new FileDialog( this ), true, command, "vef", mController );
break;
case "saveAs":
actionListener = saveAsAction;
break;
case "save":
case "saveDefault":
case "openURL":
case "close":
case "snapshot.2d":
case "showToolsPanel":
case "setItemColor":
case "setBackgroundColor":
case "showPolytopesDialog":
case "showZomicWindow":
case "showPythonWindow":
case "rZomeOrbits":
case "predefinedOrbits":
case "usedOrbits":
case "setAllDirections":
case "configureShapes":
case "configureDirections":
case "redoUntilEdit":
actionListener = this .localActions;
break;
case "capture-animation":
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, "png", mController );
break;
default:
if ( command .startsWith( "openResource-" ) ) {
actionListener = this .mController;
}
else if ( command .startsWith( "setSymmetry." ) ) {
actionListener = this .localActions;
}
else if ( command .startsWith( "showProperties-" ) ) {
actionListener = this .localActions;
}
else if ( command .startsWith( "capture." ) ) {
String ext = command .substring( "capture." .length() );
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, ext, mController );
}
else if ( command .startsWith( "export." ) ) {
String ext = command .substring( "export." .length() );
switch ( ext ) {
case "vrml": ext = "wrl"; break;
case "size": ext = "txt"; break;
case "partslist": ext = "txt"; break;
case "partgeom": ext = "vef"; break;
default:
break;
}
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, ext, mController );
}
else {
actionListener = getExclusiveAction( command );
this .mExcluder .addExcludable( control );
}
break;
}
control .addActionListener( actionListener );
}
return control;
}
public JMenuItem setMenuAction( String command, JMenuItem menuItem )
{
return (JMenuItem) this .setButtonAction( command, menuItem );
}
@Override
public void propertyChange( PropertyChangeEvent e )
{
switch ( e .getPropertyName() ) {
case "command.status":
statusText .setText( (String) e .getNewValue() );
break;
case "current.edit.xml":
if ( this .developerExtras )
statusText .setText( (String) e .getNewValue() );
break;
case "editor.mode":
String mode = (String) e .getNewValue();
int width = 0;
if ( "article" .equals( mode ) )
{
width = 400;
if ( snapshotButton != null ) // this gets called just once for the Reader
snapshotButton .setEnabled( false );
// viewControl .setVisible( false );
mExcluder .grab();
}
else
{
width = 300;
snapshotButton .setEnabled( true );
// viewControl .setVisible( true );
mExcluder .release();
}
modelArticleCardLayout .show( modelArticleEditPanel, mode );
modelArticleEditPanel .setMinimumSize( new Dimension( width, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( width, 800 ) );
break;
case "has.pages":
if ( articleButton != null )
{
boolean enable = e .getNewValue() .toString() .equals( "true" );
articleButton .setEnabled( enable );
if ( ! enable )
modelButton .doClick();
}
break;
}
}
// called from ApplicationUI on quit
boolean closeWindow()
{
if ( "true".equals( mController.getProperty( "edited" ) ) && ( isEditor && canSave ) )
{
// TODO replace showConfirmDialog() with use of EscapeDialog, or something similar...
int response = JOptionPane.showConfirmDialog( DocumentFrame.this, "Do you want to save your changes?",
"file is changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE );
if ( response == JOptionPane.CANCEL_OPTION )
return false;
if ( response == JOptionPane.YES_OPTION )
try {
localActions .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "save" ) );
return false;
} catch ( RuntimeException re ) {
logger.log( Level.WARNING, "did not save due to error", re );
return false;
}
}
dispose();
mController .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "documentClosed" ) );
return true;
}
public void makeUnnamed()
{
this .mFile = null;
}
} |
package com.intellij.facet.impl.ui.libraries;
import com.intellij.facet.ui.libraries.LibraryDownloadInfo;
import com.intellij.facet.ui.libraries.LibraryInfo;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.io.UrlConnectionUtil;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.net.IOExceptionDialog;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* @author nik
*/
public class LibraryDownloader {
private static final int CONNECTION_TIMEOUT = 60*1000;
private static final int READ_TIMEOUT = 60*1000;
@NonNls private static final String LIB_SCHEMA = "lib:
private LibraryDownloadInfo[] myLibraryInfos;
private final LibraryDownloadingMirrorsMap myMirrorsMap;
private JComponent myParent;
private @Nullable Project myProject;
private String myDirectoryForDownloadedLibrariesPath;
private final @Nullable String myLibraryPresentableName;
public LibraryDownloader(final LibraryDownloadInfo[] libraryInfos, final @Nullable Project project, JComponent parent, @Nullable String directoryForDownloadedLibrariesPath,
@Nullable String libraryPresentableName,
final LibraryDownloadingMirrorsMap mirrorsMap) {
myProject = project;
myLibraryInfos = libraryInfos;
myParent = parent;
myDirectoryForDownloadedLibrariesPath = directoryForDownloadedLibrariesPath;
myLibraryPresentableName = libraryPresentableName;
myMirrorsMap = mirrorsMap;
}
public LibraryDownloader(final LibraryDownloadInfo[] libraryInfos, final @Nullable Project project, @NotNull JComponent parent) {
this(libraryInfos, project, parent, null, null, new LibraryDownloadingMirrorsMap());
}
public LibraryDownloader(final LibraryDownloadInfo[] libraryInfos, final @NotNull Project project) {
myLibraryInfos = libraryInfos;
myProject = project;
myLibraryPresentableName = null;
myMirrorsMap = new LibraryDownloadingMirrorsMap();
}
public VirtualFile[] download() {
VirtualFile dir = null;
if (myDirectoryForDownloadedLibrariesPath != null) {
File ioDir = new File(FileUtil.toSystemDependentName(myDirectoryForDownloadedLibrariesPath));
ioDir.mkdirs();
dir = LocalFileSystem.getInstance().refreshAndFindFileByPath(myDirectoryForDownloadedLibrariesPath);
}
if (dir == null) {
dir = chooseDirectoryForLibraries();
}
if (dir != null) {
return doDownload(dir);
}
return VirtualFile.EMPTY_ARRAY;
}
private VirtualFile[] doDownload(final VirtualFile dir) {
HttpConfigurable.getInstance().setAuthenticator();
final List<Pair<LibraryDownloadInfo, File>> downloadedFiles = new ArrayList<Pair<LibraryDownloadInfo, File>>();
final List<VirtualFile> existingFiles = new ArrayList<VirtualFile>();
final Ref<Exception> exceptionRef = Ref.create(null);
final Ref<LibraryDownloadInfo> currentLibrary = new Ref<LibraryDownloadInfo>();
String dialogTitle = IdeBundle.message("progress.download.libraries.title");
if (myLibraryPresentableName != null) {
dialogTitle = IdeBundle.message("progress.download.0.libraries.title", StringUtil.capitalize(myLibraryPresentableName));
}
ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() {
public void run() {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
try {
for (int i = 0; i < myLibraryInfos.length; i++) {
LibraryDownloadInfo info = myLibraryInfos[i];
currentLibrary.set(info);
if (indicator != null) {
indicator.checkCanceled();
indicator.setText(IdeBundle.message("progress.0.of.1.file.downloaded.text", i, myLibraryInfos.length));
}
final VirtualFile existing = dir.findChild(getExpectedFileName(info));
long size = existing != null ? existing.getLength() : -1;
if (!download(info, size, downloadedFiles)) {
existingFiles.add(existing);
}
}
}
catch (ProcessCanceledException e) {
exceptionRef.set(e);
}
catch (IOException e) {
exceptionRef.set(e);
}
}
}, dialogTitle, true, myProject);
Exception exception = exceptionRef.get();
if (exception == null) {
try {
return moveToDir(existingFiles, downloadedFiles, dir);
}
catch (IOException e) {
final String title = IdeBundle.message("progress.download.libraries.title");
if (myProject != null) {
Messages.showErrorDialog(myProject, title, e.getMessage());
}
else {
Messages.showErrorDialog(myParent, title, e.getMessage());
}
return VirtualFile.EMPTY_ARRAY;
}
}
deleteFiles(downloadedFiles);
if (exception instanceof IOException) {
String message = IdeBundle.message("error.library.download.failed", exception.getMessage());
if (currentLibrary.get() != null) {
message += ": " + myMirrorsMap.getDownloadingUrl(currentLibrary.get());
}
final boolean tryAgain = IOExceptionDialog.showErrorDialog(IdeBundle.message("progress.download.libraries.title"), message);
if (tryAgain) {
return doDownload(dir);
}
}
return VirtualFile.EMPTY_ARRAY;
}
private @Nullable VirtualFile chooseDirectoryForLibraries() {
final FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
descriptor.setTitle(IdeBundle.message("dialog.directory.for.libraries.title"));
final VirtualFile[] files;
if (myProject != null) {
files = FileChooser.chooseFiles(myProject, descriptor, myProject.getBaseDir());
}
else {
files = FileChooser.chooseFiles(myParent, descriptor);
}
return files.length > 0 ? files[0] : null;
}
private static VirtualFile[] moveToDir(final List<VirtualFile> existingFiles, final List<Pair<LibraryDownloadInfo, File>> downloadedFiles, final VirtualFile dir) throws IOException {
List<VirtualFile> files = new ArrayList<VirtualFile>();
final File ioDir = VfsUtil.virtualToIoFile(dir);
for (Pair<LibraryDownloadInfo, File> pair : downloadedFiles) {
final LibraryDownloadInfo info = pair.getFirst();
final boolean dontTouch = info.getDownloadUrl().startsWith(LIB_SCHEMA) || info.getDownloadUrl().startsWith(LocalFileSystem.PROTOCOL_PREFIX);
final File toFile = dontTouch? pair.getSecond() : generateName(info, ioDir);
if (!dontTouch) {
FileUtil.rename(pair.getSecond(), toFile);
}
VirtualFile file = new WriteAction<VirtualFile>() {
protected void run(final Result<VirtualFile> result) {
final String url = VfsUtil.getUrlForLibraryRoot(toFile);
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(toFile);
result.setResult(VirtualFileManager.getInstance().refreshAndFindFileByUrl(url));
}
}.execute().getResultObject();
if (file != null) {
files.add(file);
}
}
for (final VirtualFile file : existingFiles) {
VirtualFile libraryRootFile = new WriteAction<VirtualFile>() {
protected void run(final Result<VirtualFile> result) {
final String url = VfsUtil.getUrlForLibraryRoot(VfsUtil.virtualToIoFile(file));
result.setResult(VirtualFileManager.getInstance().refreshAndFindFileByUrl(url));
}
}.execute().getResultObject();
if (libraryRootFile != null) {
files.add(libraryRootFile);
}
}
return files.toArray(new VirtualFile[files.size()]);
}
private static String getExpectedFileName(LibraryDownloadInfo info) {
return info.getFileNamePrefix() + info.getFileNameSuffix();
}
private static File generateName(LibraryDownloadInfo info, final File dir) {
String prefix = info.getFileNamePrefix();
String suffix = info.getFileNameSuffix();
File file = new File(dir, prefix + suffix);
int count = 1;
while (file.exists()) {
file = new File(dir, prefix + "_" + count + suffix);
count++;
}
return file;
}
private static void deleteFiles(final List<Pair<LibraryDownloadInfo, File>> pairs) {
for (Pair<LibraryDownloadInfo, File> pair : pairs) {
FileUtil.delete(pair.getSecond());
}
pairs.clear();
}
private boolean download(final LibraryDownloadInfo libraryInfo, final long existingFileSize, final List<Pair<LibraryDownloadInfo, File>> downloadedFiles) throws IOException {
final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
final String presentableUrl = myMirrorsMap.getPresentableUrl(libraryInfo);
final String url = myMirrorsMap.getDownloadingUrl(libraryInfo);
if (url.startsWith(LIB_SCHEMA)) {
indicator.setText2(IdeBundle.message("progress.locate.jar.text", getExpectedFileName(libraryInfo)));
final String path = url.substring(LIB_SCHEMA.length()).replace('/', File.separatorChar);
final String fullPath = PathManager.getLibPath() + File.separatorChar + path;
final File file = new File(fullPath);
downloadedFiles.add(Pair.create(libraryInfo, file));
} else if (url.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) {
String path = url.substring(LocalFileSystem.PROTOCOL_PREFIX.length()).replace('/', File.separatorChar).replace('\\', File.separatorChar);
File file = new File(path);
if (file.exists()) downloadedFiles.add(Pair.create(libraryInfo, file));
} else {
indicator.setText2(IdeBundle.message("progress.connecting.to.dowload.jar.text", presentableUrl));
indicator.setIndeterminate(true);
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
InputStream input = null;
BufferedOutputStream output = null;
boolean deleteFile = true;
File tempFile = null;
try {
final int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException(IdeBundle.message("error.connection.failed.with.http.code.N", responseCode));
}
final int size = connection.getContentLength();
if (size != -1 && size == existingFileSize) {
return false;
}
tempFile = FileUtil.createTempFile("downloaded", "jar");
input = UrlConnectionUtil.getConnectionInputStreamWithException(connection, indicator);
output = new BufferedOutputStream(new FileOutputStream(tempFile));
indicator.setText2(IdeBundle.message("progress.download.jar.text", getExpectedFileName(libraryInfo), presentableUrl));
indicator.setIndeterminate(size == -1);
int len;
final byte[] buf = new byte[1024];
int count = 0;
while ((len = input.read(buf)) > 0) {
indicator.checkCanceled();
count += len;
if (size > 0) {
indicator.setFraction((double)count / size);
}
output.write(buf, 0, len);
}
deleteFile = false;
downloadedFiles.add(Pair.create(libraryInfo, tempFile));
}
finally {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
if (deleteFile && tempFile != null) {
FileUtil.delete(tempFile);
}
connection.disconnect();
}
}
return true;
}
public static LibraryDownloadInfo[] getDownloadingInfos(final LibraryInfo[] libraries) {
List<LibraryDownloadInfo> downloadInfos = new ArrayList<LibraryDownloadInfo>();
for (LibraryInfo library : libraries) {
LibraryDownloadInfo downloadInfo = library.getDownloadingInfo();
if (downloadInfo != null) {
downloadInfos.add(downloadInfo);
}
}
return downloadInfos.toArray(new LibraryDownloadInfo[downloadInfos.size()]);
}
} |
package org.wildfly.swarm.plugin;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.inject.Inject;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.ProjectBuildingResult;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.impl.ArtifactResolver;
/**
* @author Bob McWhirter
* @author Ken Finnigan
*/
@Mojo(
name = "create",
defaultPhase = LifecyclePhase.PACKAGE,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME,
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME
)
public class CreateMojo extends AbstractSwarmMojo {
private static final String MAIN_SLOT = "main";
private static final Pattern MODULE_ARTIFACT_EXPRESSION_PATTERN = Pattern.compile(
// artifact tag
"(<artifact\\s+?name=\")(?:\\$\\{)" +
// possible GAV
"+([A-Za-z0-9_\\-.]+:[A-Za-z0-9_\\-.]+)(?:(?::)([A-Za-z0-9_\\-.]+))?" +
// end tag
"+(?:})(\"/>)"
);
private static final Pattern MODULE_ARTIFACT_GAV_PATTERN = Pattern.compile(
// artifact tag
"(<artifact\\s+?name=\")" +
// possible GAV
"+([A-Za-z0-9_\\-.]+:[A-Za-z0-9_\\-.]+:[A-Za-z0-9_\\-.]+)" +
// end tag
"+(\"/>)"
);
@Inject
private ArtifactResolver resolver;
private Map<String, List<String>> modules = new HashMap<>();
private List<String> fractionModules = new ArrayList<>();
/**
* Keyed on {@code groupId:artifactId}
*/
private final Map<String, String> featurePackDepVersions = new HashMap<>();
@Parameter(alias = "modules")
private String[] additionalModules;
@Parameter(alias = "bundle-dependencies", defaultValue = "true")
private boolean bundleDependencies;
private Path dir;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
setupFeaturePacks(this.resolver);
setupFeaturePackArtifacts();
setupDirectory();
addBootstrap();
processFractions(this.resolver, new FractionExpander());
addAdditionalModules();
addMavenRepository();
addProjectArtifact();
addProjectDependenciesToRepository();
createManifest();
createJar();
}
private void setupFeaturePackArtifacts() throws MojoFailureException {
for (Artifact pack : this.featurePacks) {
Artifact packPom = new DefaultArtifact(pack.getGroupId(),
pack.getArtifactId(),
pack.getVersion(),
"",
"pom",
pack.getClassifier(),
new DefaultArtifactHandler("pom"));
try {
ProjectBuildingResult buildingResult = buildProject(packPom);
DependencyResolutionResult resolutionResult = resolveProjectDependencies(buildingResult.getProject(), null);
if (resolutionResult.getDependencies() != null && resolutionResult.getDependencies().size() > 0) {
for (Dependency dep : resolutionResult.getDependencies()) {
// Add the dependency version
featurePackDepVersions.put(dep.getArtifact().getGroupId() + ":" + dep.getArtifact().getArtifactId(), dep.getArtifact().getVersion());
this.featurePackArtifacts.add(convertAetherToMavenArtifact(dep.getArtifact(), "compile", "jar"));
}
}
} catch (Exception e) {
// skip
}
}
}
private void addMavenRepository() throws MojoFailureException {
if ( ! this.bundleDependencies ) {
return;
}
Path modulesDir = this.dir.resolve("modules");
analyzeModuleXmls(modulesDir);
collectArtifacts();
}
private void collectArtifacts() throws MojoFailureException {
for (ArtifactSpec each : this.gavs) {
if (!collectArtifact(each)) {
getLog().error("unable to locate artifact: " + each);
}
}
}
private boolean collectArtifact(ArtifactSpec spec) throws MojoFailureException {
Artifact artifact = locateArtifact(spec);
if (artifact == null) {
return false;
}
addArtifact(artifact);
return true;
}
private void addArtifact(Artifact artifact) throws MojoFailureException {
Path m2repo = this.dir.resolve("m2repo");
Path dest = m2repo.resolve(ArtifactUtils.toPath(artifact));
try {
Files.createDirectories(dest.getParent());
Files.copy(artifact.getFile().toPath(), dest, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new MojoFailureException("unable to add artifact: " + dest, e);
}
}
private Artifact locateArtifact(ArtifactSpec spec) {
for (Artifact each : this.featurePackArtifacts) {
if (spec.matches(each)) {
return each;
}
}
for (Artifact each : this.pluginArtifacts) {
if (spec.matches(each)) {
return each;
}
}
for (Artifact each : this.project.getArtifacts()) {
if (spec.matches(each)) {
return each;
}
}
return null;
}
private void analyzeModuleXmls(final Path path) throws MojoFailureException {
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if ("module.xml".equals(file.getFileName().toString())) {
analyzeModuleXml(file);
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new MojoFailureException("Failed to analyze module XML for " + path, e);
}
}
private void analyzeModuleXml(final Path path) throws IOException {
final List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
for (String line : lines) {
final Matcher matcher = MODULE_ARTIFACT_GAV_PATTERN.matcher(line);
if (matcher.find()) {
this.gavs.add(new ArtifactSpec(matcher.group(2)));
}
}
}
private void addTransitiveModules(Path moduleXml) {
try (BufferedReader in = Files.newBufferedReader(moduleXml, StandardCharsets.UTF_8)) {
String line = null;
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.startsWith("<module-alias")) {
int start = line.indexOf(TARGET_NAME_PREFIX);
if (start > 0) {
int end = line.indexOf("\"", start + TARGET_NAME_PREFIX.length());
if (end >= 0) {
String moduleName = line.substring(start + TARGET_NAME_PREFIX.length(), end);
addTransitiveModule(moduleName);
break;
}
}
}
if (line.startsWith("<module name=")) {
int start = line.indexOf("\"");
if (start > 0) {
int end = line.indexOf("\"", start + 1);
if (end > 0) {
String moduleName = line.substring(start + 1, end);
if (!line.contains("optional=\"true\"")) {
int slotStart = line.indexOf("slot=\"");
if (slotStart > 0) {
slotStart += 6;
int slotEnd = line.indexOf("\"", slotStart + 1);
String slotName = line.substring(slotStart, slotEnd);
addTransitiveModule(moduleName, slotName);
} else {
addTransitiveModule(moduleName);
}
}
}
}
}
}
} catch (IOException e) {
getLog().error(e);
}
}
private void addTransitiveModule(String moduleName) {
addTransitiveModule(moduleName, MAIN_SLOT);
}
private void addTransitiveModule(String moduleName, String slot) {
if (this.modules.containsKey(moduleName) && this.modules.get(moduleName).contains(slot)) {
return;
}
String search = "modules/system/layers/base/" + moduleName.replace('.', '/') + "/" + slot + "/module.xml";
for (Artifact pack : this.featurePacks) {
try {
ZipFile zip = new ZipFile(pack.getFile());
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry each = entries.nextElement();
if (each.getName().equals(search)) {
Path outFile = this.dir.resolve(search);
Files.createDirectories(outFile.getParent());
copyFileFromZip(zip, each, outFile);
List<String> slots = new ArrayList<>();
slots.add(slot);
this.modules.put(moduleName, slots);
addTransitiveModules(outFile);
return;
}
}
} catch (IOException e) {
getLog().error(e);
}
}
}
private void addAdditionalModules() {
if (this.additionalModules == null) {
return;
}
for (int i = 0; i < this.additionalModules.length; ++i) {
addTransitiveModule(this.additionalModules[i]);
}
}
private void setupDirectory() throws MojoFailureException {
this.dir = Paths.get(this.projectBuildDir, "wildfly-swarm-archive");
try {
if (Files.notExists(dir)) {
Files.createDirectories(dir);
} else {
emptyDir(dir);
}
} catch (IOException e) {
throw new MojoFailureException("Failed to setup wildfly-swarm-archive directory", e);
}
}
private void emptyDir(Path dir) throws IOException {
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
private void expandArtifact(Artifact artifact) throws IOException {
Path destination = this.dir;
File artifactFile = artifact.getFile();
if (artifact.getType().equals("jar")) {
JarFile jarFile = new JarFile(artifactFile);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry each = entries.nextElement();
if (each.getName().startsWith("META-INF")) {
continue;
}
Path fsEach = destination.resolve(each.getName());
if (each.isDirectory()) {
Files.createDirectories(fsEach);
} else {
copyFileFromZip(jarFile, each, fsEach);
}
}
}
}
private Artifact findArtifact(String groupId, String artifactId, String type) {
Set<Artifact> artifacts = this.project.getArtifacts();
for (Artifact each : artifacts) {
if (each.getGroupId().equals(groupId) && each.getArtifactId().equals(artifactId) && each.getType().equals(type)) {
return each;
}
}
return null;
}
private void addBootstrap() throws MojoFailureException {
Artifact artifact = findArtifact("org.wildfly.swarm", "wildfly-swarm-bootstrap", "jar");
try {
expandArtifact(artifact);
} catch (IOException e) {
throw new MojoFailureException("Unable to add bootstrap", e);
}
}
private void addProjectArtifact() throws MojoFailureException {
Artifact artifact = this.project.getArtifact();
Path appDir = this.dir.resolve("app");
Path appFile = appDir.resolve(artifact.getFile().getName());
try {
Files.createDirectories(appDir);
Files.copy(artifact.getFile().toPath(), appFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new MojoFailureException("Error copying project artifact", e);
}
}
private void addProjectDependenciesToRepository() throws MojoFailureException {
if ( ! this.bundleDependencies ) {
return;
}
if (!this.project.getPackaging().equals("jar")) {
return;
}
Path depsTxt = this.dir.resolve("dependencies.txt");
try (final BufferedWriter out = Files.newBufferedWriter(depsTxt, StandardCharsets.UTF_8)) {
Set<Artifact> dependencies = this.project.getArtifacts();
for (Artifact each : dependencies) {
String scope = each.getScope();
if (scope.equals("compile") || scope.equals("runtime")) {
addArtifact(each);
out.write(each.getGroupId() + ":" + each.getArtifactId() + ":" + each.getVersion() + "\n");
}
}
} catch (IOException e) {
throw new MojoFailureException("Unable to create dependencies.txt", e);
}
}
private void createJar() throws MojoFailureException {
Artifact primaryArtifact = this.project.getArtifact();
ArtifactHandler handler = new DefaultArtifactHandler("jar");
Artifact artifact = new DefaultArtifact(
primaryArtifact.getGroupId(),
primaryArtifact.getArtifactId(),
primaryArtifact.getVersion(),
primaryArtifact.getScope(),
"jar",
"swarm",
handler
);
String name = artifact.getArtifactId() + "-" + artifact.getVersion() + "-swarm.jar";
File file = new File(this.projectBuildDir, name);
try (
FileOutputStream fileOut = new FileOutputStream(file);
JarOutputStream out = new JarOutputStream(fileOut)
) {
writeToJar(out, this.dir);
} catch (IOException e) {
throw new MojoFailureException("Unable to create jar", e);
}
artifact.setFile(file);
this.project.addAttachedArtifact(artifact);
}
private void writeToJar(final JarOutputStream out, final Path entry) throws IOException {
String rootPath = this.dir.toAbsolutePath().toString();
String entryPath = entry.toAbsolutePath().toString();
if (!rootPath.equals(entryPath)) {
String jarPath = entryPath.substring(rootPath.length() + 1);
if (Files.isDirectory(entry)) {
jarPath = jarPath + "/";
}
out.putNextEntry(new ZipEntry(jarPath.replace(File.separatorChar, '/')));
}
if (Files.isDirectory(entry)) {
Files.walkFileTree(entry, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
writeToJar(out, file);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.copy(entry, out);
}
}
private void createManifest() throws MojoFailureException {
Manifest manifest = new Manifest();
Attributes attrs = manifest.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attrs.put(Attributes.Name.MAIN_CLASS, "org.wildfly.swarm.bootstrap.Main");
attrs.putValue("Application-Artifact", this.project.getArtifact().getFile().getName());
StringBuilder modules = new StringBuilder();
boolean first = true;
for (String each : this.fractionModules) {
if (!first) {
modules.append(",");
}
modules.append(each);
first = false;
}
attrs.putValue("Feature-Pack-Modules", modules.toString());
// Write the manifest to the dir
final Path manifestPath = dir.resolve("META-INF").resolve("MANIFEST.MF");
// Ensure the directories have been created
try {
Files.createDirectories(manifestPath.getParent());
try (final OutputStream out = Files.newOutputStream(manifestPath, StandardOpenOption.CREATE)) {
manifest.write(out);
}
} catch (IOException e) {
throw new MojoFailureException("Could not create manifest file: " + manifestPath.toString(), e);
}
}
private void copyFileFromZip(final ZipFile resource, final ZipEntry entry, final Path outFile) throws IOException {
if (entry.getName().endsWith("module.xml")) {
try (
final BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(entry), StandardCharsets.UTF_8));
final BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8)
) {
String line;
while ((line = reader.readLine()) != null) {
// Attempt to find a version if required
final Matcher matcher = MODULE_ARTIFACT_EXPRESSION_PATTERN.matcher(line);
while (matcher.find()) {
String version = matcher.group(3);
if (version == null) {
// No version found attempt to resolve it
version = findVersion(matcher.group(2));
if (version != null) {
line = matcher.replaceAll("$1$2:" + version + "$4");
} else {
getLog().debug("No version found for " + line);
}
}
}
writer.write(line);
writer.write(System.lineSeparator());
}
}
} else {
try (InputStream in = resource.getInputStream(entry)) {
Files.copy(in, outFile, StandardCopyOption.REPLACE_EXISTING);
}
}
}
private String findVersion(final String ga) {
String version = featurePackDepVersions.get(ga);
// Check the project dependencies if not found in the feature pack
if (version == null) {
final String[] gaParts = ga.split(":");
if (gaParts.length == 2) {
final Set<Artifact> artifacts = project.getArtifacts();
for (Artifact artifact : artifacts) {
if (artifact.getGroupId().endsWith(gaParts[0]) && artifact.getArtifactId().equals(gaParts[1])) {
version = artifact.getVersion();
break;
}
}
}
}
return version;
}
final class FractionExpander implements ExceptionConsumer<org.eclipse.aether.artifact.Artifact> {
@Override
public void accept(org.eclipse.aether.artifact.Artifact artifact) throws Exception {
ZipFile zipFile = new ZipFile(artifact.getFile());
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry each = entries.nextElement();
Path fsEach = dir.resolve(each.getName());
if (each.isDirectory()) {
Files.createDirectories(fsEach);
continue;
}
String normalizedName = normalizeZipEntryName(each);
if (normalizedName.startsWith(MODULE_PREFIX) && normalizedName.endsWith(MODULE_SUFFIX)) {
String moduleName = normalizedName.substring(MODULE_PREFIX.length(), normalizedName.length() - MODULE_SUFFIX.length());
moduleName = moduleName.replace('/', '.') + ":main";
fractionModules.add(moduleName);
}
copyFileFromZip(zipFile, each, fsEach);
if ("module.xml".equals(fsEach.getFileName().toString())) {
addTransitiveModules(fsEach);
}
}
}
}
private String normalizeZipEntryName(ZipEntry entry) {
return entry.getName().replace(File.separatorChar, '/');
}
} |
package com.intellij.psi.impl.source.tree;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.impl.source.SrcRepositoryPsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.editor.impl.DocumentRange;
import com.intellij.openapi.editor.impl.VirtualFileDelegate;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl;
import com.intellij.lang.Language;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.PsiParser;
import com.intellij.lang.ASTNode;
import com.intellij.lang.impl.PsiBuilderImpl;
/**
* @author cdr
*/
public class InjectedLanguageUtil {
public static Pair<PsiElement, TextRange> createInjectedPsiFile(final PsiLanguageInjectionHost host, final String text, final TextRange range) {
final Language language = host.getManager().getInjectedLanguage(host);
if (language == null) return null;
final Project project = host.getProject();
final ParserDefinition parserDefinition = language.getParserDefinition();
if (parserDefinition == null) return null;
final PsiParser parser = parserDefinition.createParser(project);
final IElementType root = parserDefinition.getFileNodeType();
final PsiBuilderImpl builder = new PsiBuilderImpl(language, project, null, text);
final ASTNode parsedNode = parser.parse(root, builder);
if (parsedNode instanceof FileElement) {
parsedNode.putUserData(TreeElement.MANAGER_KEY, host.getManager());
TextRange documentWindow = host.getTextRange().cutOut(range);
DocumentEx document = (DocumentEx)PsiDocumentManager.getInstance(project).getDocument(host.getContainingFile());
DocumentRange documentRange = new DocumentRange(document, documentWindow);
final VirtualFile virtualFile = new VirtualFileDelegate(host.getContainingFile().getVirtualFile(), documentWindow, language, text);
PsiFile psiFile = parserDefinition.createFile(new SingleRootFileViewProvider(host.getManager(), virtualFile));
psiFile.putUserData(ResolveUtil.INJECTED_IN_ELEMENT, host);
FileDocumentManagerImpl.registerDocument(documentRange, virtualFile);
SrcRepositoryPsiElement repositoryPsiElement = (SrcRepositoryPsiElement)psiFile;
((FileElement)parsedNode).setPsiElement(repositoryPsiElement);
repositoryPsiElement.setTreeElement(parsedNode);
}
return Pair.create(parsedNode.getPsi(), range);
}
} |
package permafrost.tundra.server;
import com.wm.app.b2b.server.ServiceException;
import com.wm.data.IData;
import com.wm.util.coder.IDataCodable;
import permafrost.tundra.data.IDataMap;
import permafrost.tundra.lang.ExceptionHelper;
import java.net.InetAddress;
import java.net.UnknownHostException;
public final class NameHelper {
/**
* Disallow instantiation of this class.
*/
private NameHelper() {}
/**
* Resolves the given domain name or internet address, returning an IData representation.
*
* @param name The domain name or internet address to be resolved.
* @return An IData representation of the resolved address, containing the following keys: $domain, $host, $ip.
* @throws ServiceException If the address could not be resolved.
*/
public static IData resolve(String name) throws ServiceException {
IData output = null;
try {
output = InternetAddress.resolve(name).getIData();
} catch (UnknownHostException ex) {
ExceptionHelper.raise(ex);
}
return output;
}
/**
* Returns an IData representation of the localhost internet domain name and address.
*
* @return An IData representation of the localhost address, containing the following keys: $domain, $host, $ip.
* @throws ServiceException If the localhost address could not be resolved.
*/
public static IData localhost() throws ServiceException {
IData output = null;
try {
output = InternetAddress.localhost().getIData();
} catch (UnknownHostException ex) {
ExceptionHelper.raise(ex);
}
return output;
}
/**
* Convenience class for resolving domain names and converting to IData representations.
*/
static class InternetAddress implements IDataCodable {
/**
* Cache localhost in volatile class member to optimize performance by avoiding the thread synchronization in
* the java.net.InetAddress class.
*/
protected static final long LOCALHOST_EXPIRE_DURATION = 5 * 60 * 1000; // 5 minutes
protected static volatile long localhostExpireTime = 0;
protected static volatile InternetAddress localhost;
protected String domain, host, ip;
/**
* Create a new InternetAddress from the given InetAddress object.
*
* @param address The address to use to create this object.
*/
public InternetAddress(InetAddress address) {
if (address == null) throw new NullPointerException("address must not be null");
this.domain = address.getCanonicalHostName().toLowerCase();
this.host = address.getHostName().toLowerCase();
this.ip = address.getHostAddress().toLowerCase();
}
/**
* Returns the domain name associated with this internet address.
*
* @return The domain name associated with this internet address.
*/
public String getDomain() {
return domain;
}
/**
* Returns the host name associated with this internet address.
*
* @return The host name associated with this internet address.
*/
public String getHost() {
return host;
}
/**
* Returns the IP address associated with this internet address.
*
* @return The IP address associated with this internet address.
*/
public String getIPAddress() {
return ip;
}
/**
* Returns an IData representation of this internet address.
*
* @return An IData representation of this internet address, containing the following keys: $domain, $host, $ip.
*/
public IData getIData() {
IDataMap output = new IDataMap();
output.put("$domain", domain);
output.put("$host", host);
output.put("$ip", ip);
return output;
}
/**
* This method is not implemented by this class.
*
* @param input An IData to use to set the member variables of this class.
* @throws UnsupportedOperationException Because this method is not implemented by this class.
*/
public void setIData(IData input) {
throw new UnsupportedOperationException("setIData is not supported by this class");
}
/**
* Returns the localhost address.
*
* @return The localhost address.
* @throws UnknownHostException If the localhost cannot be resolved.
*/
public static InternetAddress localhost() throws UnknownHostException {
// thread synchronization is not required because we don't care if we miss an update
if (localhost == null || localhostExpireTime <= System.currentTimeMillis()) {
localhost = new InternetAddress(InetAddress.getLocalHost());
localhostExpireTime = System.currentTimeMillis() + LOCALHOST_EXPIRE_DURATION;
}
return localhost;
}
/**
* Returns the internet address that the given name resolves to.
*
* @param name The name to be resolved.
* @return The internet address which resolves to the given name.
* @throws UnknownHostException If the name cannot be resolved.
*/
public static InternetAddress resolve(String name) throws UnknownHostException {
return new InternetAddress(InetAddress.getByName(name));
}
}
} |
package permafrost.tundra.tn.route;
import com.wm.app.b2b.server.InvokeState;
import com.wm.app.b2b.server.Server;
import com.wm.app.b2b.server.ServerAPI;
import com.wm.app.b2b.server.ServiceException;
import com.wm.app.tn.db.Datastore;
import com.wm.app.tn.db.SQLStatements;
import com.wm.app.tn.db.SQLWrappers;
import com.wm.app.tn.doc.BizDocEnvelope;
import com.wm.app.tn.profile.ProfileSummary;
import com.wm.app.tn.route.RoutingRule;
import com.wm.data.IData;
import com.wm.data.IDataFactory;
import permafrost.tundra.io.InputOutputHelper;
import permafrost.tundra.lang.Startable;
import permafrost.tundra.server.SchedulerHelper;
import permafrost.tundra.server.SchedulerStatus;
import permafrost.tundra.server.ServerThreadFactory;
import permafrost.tundra.time.DateTimeHelper;
import permafrost.tundra.tn.document.BizDocEnvelopeHelper;
import permafrost.tundra.tn.profile.ProfileHelper;
import permafrost.tundra.util.concurrent.BoundedPriorityBlockingQueue;
import permafrost.tundra.util.concurrent.PrioritizedThreadPoolExecutor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Used to defer processing of bizdocs to a dedicated thread pool.
*/
public class Deferrer implements Startable {
/**
* Bizdoc user status used to defer routing.
*/
public static final String BIZDOC_USER_STATUS_DEFERRED = "DEFERRED";
/**
* Bizdoc user status used to begin routing after it was previously deferred.
*/
public static final String BIZDOC_USER_STATUS_ROUTING = "ROUTING";
/**
* SQL statement for seeding deferred work queue.
*/
protected final static String SELECT_BIZDOCS_FOR_USERSTATUS = "SELECT DocID FROM BizDoc WHERE UserStatus = ? ORDER BY DocTimestamp ASC";
/**
* The default timeout for database queries.
*/
protected static final int DEFAULT_SQL_STATEMENT_QUERY_TIMEOUT_SECONDS = 30;
/**
* How long to keep threads alive in the pool when idle.
*/
protected static final long DEFAULT_THREAD_KEEP_ALIVE_MILLISECONDS = 60 * 60 * 1000L;
/**
* How often to seed deferred bizdocs from the database.
*/
protected static final long DEFAULT_SEED_SCHEDULE_MILLISECONDS = 60 * 1000L;
/**
* How often to clean up completed deferred routes from the cache.
*/
protected static final long DEFAULT_CLEAN_SCHEDULE_MILLISECONDS = 60 * 1000L;
/**
* How often to clean up completed deferred routes from the cache.
*/
protected static final long DEFAULT_RESTART_SCHEDULE_MILLISECONDS = 60 * 60 * 1000L;
/**
* The default number of threads to use for executing deferred routes.
*/
protected static final int DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
/**
* Maximum time to wait to shutdown the executor in milliseconds.
*/
protected static final long DEFAULT_SHUTDOWN_TIMEOUT_MILLISECONDS = 5 * 60 * 1000L;
/**
* The maximum number of routes to cache in memory or to queue in the executor.
*/
protected static final int DEFAULT_WORK_QUEUE_CAPACITY = DEFAULT_THREAD_POOL_SIZE * 2048;
/**
* Is this object started or stopped?
*/
protected volatile boolean started;
/**
* The executors used to run deferred jobs by thread priority.
*/
protected volatile ThreadPoolExecutor executor;
/**
* The scheduler used to self-heal and load balance by seeding deferred documents from database regularly.
*/
protected volatile ScheduledExecutorService scheduler;
/**
* The level of concurrency to use, equal to the number of threads in the pool used for processing.
*/
protected volatile int concurrency;
/**
* The maximum capacity of the work queue.
*/
protected volatile int capacity;
/**
* An in-memory cache of pending routes.
*/
protected ConcurrentMap<String, Future<IData>> pendingRoutes;
/**
* Initialization on demand holder idiom.
*/
private static class Holder {
/**
* The singleton instance of the class.
*/
private static final Deferrer DEFERRER = new Deferrer();
}
/**
* Creates a new Deferrer.
*/
public Deferrer() {
this(DEFAULT_THREAD_POOL_SIZE);
}
/**
* Creates a new Deferrer.
*
* @param concurrency The level of concurrency to use.
*/
public Deferrer(int concurrency) {
this(concurrency, DEFAULT_WORK_QUEUE_CAPACITY);
}
/**
* Creates a new Deferrer.
*
* @param concurrency The level of concurrency to use.
* @param capacity The maximum capacity of the work queue.
*/
public Deferrer(int concurrency, int capacity) {
setConcurrency(concurrency);
setCapacity(capacity);
}
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static Deferrer getInstance() {
return Holder.DEFERRER;
}
/**
* Defers the given bizdoc to be routed by a dedicated thread pool.
*
* @param bizdoc The bizdoc to be deferred.
* @throws ServiceException If an error occurs.
*/
public Future<IData> defer(BizDocEnvelope bizdoc, RoutingRule rule, IData parameters) throws ServiceException {
return defer(new CallableDeferredRoute(bizdoc, rule, parameters));
}
/**
* Defers the given route to be executed by a dedicated thread pool.
*
* @param route The route to be deferred.
*/
public Future<IData> defer(CallableDeferredRoute route) {
Future<IData> result = null;
try {
result = executor.submit(route);
} catch(Throwable ex) {
// if we failed to submit route to executor for any reason, then run it directly on the current thread
FutureTask<IData> task = new FutureTask<IData>(route);
result = task;
task.run();
} finally {
pendingRoutes.putIfAbsent(route.getIdentity(), result);
}
return result;
}
/**
* Returns the current level of concurrency used.
*
* @return the current level of concurrency used.
*/
public int getConcurrency() {
return concurrency;
}
/**
* Sets the size of the thread pool.
*
* @param concurrency The level of concurrency to use.
*/
public synchronized void setConcurrency(int concurrency) {
if (concurrency < 1) throw new IllegalArgumentException("concurrency must be >= 1");
this.concurrency = concurrency;
}
/**
* Returns the current capacity of the work queue.
*
* @return the current capacity of the work queue.
*/
public int getCapacity() {
return capacity;
}
/**
* Sets the maximum capacity of the work queue.
*
* @param capacity The maximum capacity of the work queue.
*/
public synchronized void setCapacity(int capacity) {
if (capacity < 1) throw new IllegalArgumentException("capacity must be >= 1");
this.capacity = capacity;
}
/**
* Returns true if there are less threads busy than are in the pool.
*
* @return true if there are less threads busy than are in the pool.
*/
public boolean isIdle() {
return executor.getActiveCount() < executor.getMaximumPoolSize();
}
/**
* Returns true if the work queue is full.
*
* @return true if the work queue is full.
*/
public boolean isSaturated() {
return executor.getQueue().size() >= capacity;
}
/**
* Returns the number of routes pending execution.
*
* @return the number of routes pending execution.
*/
public int size() {
return executor.getQueue().size();
}
/**
* Seeds the work queue with any bizdocs in the database with user status "DEFERRED".
*/
protected void seed() {
if (shouldSeed()) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = Datastore.getConnection();
statement = connection.prepareStatement(SELECT_BIZDOCS_FOR_USERSTATUS);
statement.setQueryTimeout(DEFAULT_SQL_STATEMENT_QUERY_TIMEOUT_SECONDS);
statement.clearParameters();
SQLWrappers.setString(statement, 1, BIZDOC_USER_STATUS_DEFERRED);
statement.setFetchSize(InputOutputHelper.DEFAULT_BUFFER_SIZE);
boolean shouldContinue = true;
while (shouldSeed() && shouldContinue) {
shouldContinue = false;
try {
resultSet = statement.executeQuery();
while (shouldSeed() && resultSet.next()) {
String id = resultSet.getString(1);
try {
if (!pendingRoutes.containsKey(id)) {
pendingRoutes.putIfAbsent(id, executor.submit(new CallableDeferredRoute(id)));
shouldContinue = true;
}
} catch (RejectedExecutionException ex) {
// executor must be saturated or shut down, so stop seeding
shouldContinue = false;
break;
}
}
} finally {
SQLWrappers.close(resultSet);
connection.commit();
}
}
} catch (SQLException ex) {
connection = Datastore.handleSQLException(connection, ex);
ServerAPI.logError(ex);
} finally {
SQLStatements.releaseStatement(statement);
Datastore.releaseConnection(connection);
}
}
}
/**
* Returns true if seeding can occur on this server.
*
* @return true if seeding can occur on this server.
*/
protected boolean shouldSeed() {
return isStarted() && Server.isRunning() && SchedulerHelper.status() == SchedulerStatus.STARTED && !isSaturated();
}
/**
* Cleans up the deferred route cache by removing bizdocs that are no longer deferred.
*/
protected void clean() {
for (Map.Entry<String, Future<IData>> pendingRoute : pendingRoutes.entrySet()) {
String id = pendingRoute.getKey();
Future<IData> result = pendingRoute.getValue();
if (result.isDone()) {
pendingRoutes.remove(id, result);
}
}
}
/**
* Starts this object.
*/
@Override
public synchronized void start() {
start(null);
}
/**
* Starts this object.
*
* @param pendingTasks A list of tasks that were previously pending execution that will be resubmitted.
*/
protected synchronized void start(List<Runnable> pendingTasks) {
if (!started) {
ConcurrentMap<String, Future<IData>> drainedRoutes = pendingRoutes;
pendingRoutes = new ConcurrentHashMap<String, Future<IData>>(capacity);
if (drainedRoutes != null) {
pendingRoutes.putAll(drainedRoutes);
}
ThreadFactory threadFactory = new ServerThreadFactory("TundraTN/Route Worker", null, InvokeState.getCurrentState(), Thread.NORM_PRIORITY, false);
executor = new PrioritizedThreadPoolExecutor(concurrency, concurrency, DEFAULT_THREAD_KEEP_ALIVE_MILLISECONDS, TimeUnit.MILLISECONDS, new BoundedPriorityBlockingQueue<Runnable>(capacity), threadFactory, new ThreadPoolExecutor.AbortPolicy());
executor.allowCoreThreadTimeOut(true);
scheduler = Executors.newScheduledThreadPool(1, new ServerThreadFactory("TundraTN/Route Manager", InvokeState.getCurrentState()));
// schedule seeding
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
seed();
} catch(Throwable ex) {
ServerAPI.logError(ex);
}
}
}, DEFAULT_SEED_SCHEDULE_MILLISECONDS, DEFAULT_SEED_SCHEDULE_MILLISECONDS, TimeUnit.MILLISECONDS);
// schedule cleaning
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
clean();
} catch(Throwable ex) {
ServerAPI.logError(ex);
}
}
}, DEFAULT_CLEAN_SCHEDULE_MILLISECONDS, DEFAULT_CLEAN_SCHEDULE_MILLISECONDS, TimeUnit.MILLISECONDS);
// schedule restart
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
restart();
} catch(Throwable ex) {
ServerAPI.logError(ex);
}
}
}, DEFAULT_RESTART_SCHEDULE_MILLISECONDS, DEFAULT_RESTART_SCHEDULE_MILLISECONDS, TimeUnit.MILLISECONDS);
if (pendingTasks != null) {
for (Runnable pendingTask : pendingTasks) {
try {
executor.submit(pendingTask);
} catch(RejectedExecutionException ex) {
// do nothing
}
}
}
clean();
started = true;
}
}
/**
* Stops this object.
*/
@Override
public synchronized void stop() {
stop(DEFAULT_SHUTDOWN_TIMEOUT_MILLISECONDS, true);
}
/**
* Stops this object.
*
* @param timeout How long in milliseconds to wait for the executor to shutdown.
* @param interrupt Whether to interrupt tasks that are in-flight.
* @return List of submitted tasks not yet started.
*/
protected synchronized List<Runnable> stop(long timeout, boolean interrupt) {
List<Runnable> pendingTasks = Collections.emptyList();
if (started) {
started = false;
try {
scheduler.shutdown();
executor.shutdown();
if (timeout > 0) {
executor.awaitTermination(timeout, TimeUnit.MILLISECONDS);
}
} catch(InterruptedException ex) {
// ignore interruption to this thread
} finally {
if (interrupt) {
scheduler.shutdownNow();
pendingTasks = executor.shutdownNow();
} else {
pendingTasks = drain();
}
}
}
return pendingTasks;
}
/**
* Drains the executor work queue of tasks not yet started.
*
* @return List of submitted tasks not yet started.
*/
protected List<Runnable> drain() {
BlockingQueue<Runnable> queue = executor.getQueue();
ArrayList<Runnable> list = new ArrayList<Runnable>(queue.size());
queue.drainTo(list);
if (!queue.isEmpty()) {
for (Runnable runnable : queue.toArray(new Runnable[0])) {
if (queue.remove(runnable)) {
list.add(runnable);
}
}
}
return list;
}
/**
* Restarts this object.
*/
@Override
public synchronized void restart() {
start(stop(0, false));
}
/**
* Returns true if the object is started.
*
* @return true if the object is started.
*/
@Override
public boolean isStarted() {
return started;
}
/**
* A callable deferred route with optimistic concurrency via user status.
*/
protected static class CallableDeferredRoute extends CallableRoute {
/**
* An in-memory cache of routes currently executing.
*/
protected static final ConcurrentMap<String, CallableDeferredRoute> EXECUTING_ROUTES = new ConcurrentHashMap<String, CallableDeferredRoute>();
/**
* Constructs a new CallableDeferredRoute object.
*
* @param id The internal ID of the bizdoc to be routed.
*/
public CallableDeferredRoute(String id) {
super(id);
}
/**
* Constructs a new CallableRoute.
*
* @param bizdoc The bizdoc to be routed.
* @param rule The rule to use when routing.
* @param parameters The optional TN_parms to use when routing.
* @throws ServiceException If an error occurs.
*/
public CallableDeferredRoute(BizDocEnvelope bizdoc, RoutingRule rule, IData parameters) throws ServiceException {
super(bizdoc, rule, parameters);
if (!BIZDOC_USER_STATUS_DEFERRED.equals(bizdoc.getUserStatus())) {
BizDocEnvelopeHelper.setStatus(bizdoc, null, BIZDOC_USER_STATUS_DEFERRED);
}
}
/**
* Routes the bizdoc.
*/
@Override
public IData call() throws ServiceException {
IData output;
Thread currentThread = Thread.currentThread();
if (EXECUTING_ROUTES.putIfAbsent(id, this) == null) {
String currentThreadName = currentThread.getName();
try {
initialize();
if (BizDocEnvelopeHelper.setUserStatusForPrevious(bizdoc, BIZDOC_USER_STATUS_ROUTING, BIZDOC_USER_STATUS_DEFERRED)) {
// status was able to be changed, so we have a "lock" on the bizdoc and can now route it
currentThread.setName(MessageFormat.format("{0}: {1}, Started={2} PROCESSING", currentThreadName, toThreadSuffix(bizdoc), DateTimeHelper.now("datetime")));
output = super.call();
} else {
// status was not able to be changed, therefore another server or process has already processed this bizdoc
output = IDataFactory.create();
}
} finally {
EXECUTING_ROUTES.remove(id, this);
currentThread.setName(currentThreadName);
}
} else {
output = IDataFactory.create();
}
return output;
}
/**
* Returns a string that can be used for logging the given bizdoc.
*
* @param bizdoc The bizdoc to be logged.
* @return A string representing the given bizdoc.
*/
private static String toThreadSuffix(BizDocEnvelope bizdoc) {
String output = "";
if (bizdoc != null) {
try {
ProfileSummary sender = ProfileHelper.getProfileSummary(bizdoc.getSenderId());
ProfileSummary receiver = ProfileHelper.getProfileSummary(bizdoc.getReceiverId());
output = MessageFormat.format("BizDoc/InternalID={0}, BizDoc/DocumentID={1}, BizDoc/DocTimestamp={2}, BizDoc/DocType/TypeName={3}, BizDoc/Sender={4}, BizDoc/Receiver={5}", bizdoc.getInternalId(), bizdoc.getDocumentId(), DateTimeHelper.emit(bizdoc.getTimestamp(), "datetime"), bizdoc.getDocType().getName(), sender.getDisplayName(), receiver.getDisplayName());
} catch (ServiceException ex) {
// do nothing
}
}
return output;
}
}
} |
package picard.fingerprint;
import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.variant.utils.SAMSequenceDictionaryExtractor;
import htsjdk.variant.vcf.VCFFileReader;
import htsjdk.variant.vcf.VCFHeader;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import picard.PicardException;
import picard.analysis.FingerprintingDetailMetrics;
import picard.analysis.FingerprintingSummaryMetrics;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.DiagnosticsAndQCProgramGroup;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
/**
* Checks the sample identity of the sequence/genotype data in the provided file (SAM/BAM or VCF)
* against a set of known genotypes in the supplied genotype file (in VCF format).
* <p>
* <h3> Summary </h3>
* Computes a fingerprint (essentially, genotype information from different parts of the genome)
* from the supplied input file (SAM/BAM or VCF) file and
* compares it to the expected fingerprint genotypes provided. The key output is a LOD score
* which represents the relative likelihood of the sequence data originating from the same
* sample as the genotypes vs. from a random sample.
* <br/>
* Two outputs are produced:
* <ol>
* <li>A summary metrics file that gives metrics of the fingerprint matches when comparing the input to a set of
* genotypes for the expected sample. At the single sample level (if the input was a VCF) or at the read
* level (lane or index within a lane) (if the input was a SAM/BAM) </li>
* <li>A detail metrics file that contains an individual SNP/Haplotype comparison within a fingerprint comparison.
* </li>
* </ol>
* The metrics files fill the fields of the classes {@link FingerprintingSummaryMetrics} and
* {@link FingerprintingDetailMetrics}.
* The output files may be specified individually using the SUMMARY_OUTPUT and DETAIL_OUTPUT options.
* Alternatively the OUTPUT option may be used instead to give the base of the two output
* files, with the summary metrics having a file extension {@value #FINGERPRINT_SUMMARY_FILE_SUFFIX},
* and the detail metrics having a file extension {@value #FINGERPRINT_DETAIL_FILE_SUFFIX}.
* <br/>
* <h3>Example comparing a bam against known genotypes:</h3>
* <pre>
* java -jar picard.jar CheckFingerprint \
* INPUT=sample.bam \
* GENOTYPES=sample_genotypes.vcf \
* HAPLOTYPE_MAP=fingerprinting_haplotype_database.txt \
* OUTPUT=sample_fingerprinting
* </pre>
* <br/>
* <h3>Detailed Explanation</h3>
* <p>
* This tool calculates a single number that reports the LOD score for identity check between the {@link #INPUT}
* and the {@link #GENOTYPES}. A positive value indicates that the data seems to have come from the same individual
* or, in other words the identity checks out. The scale is logarithmic (base 10), so a LOD of 6 indicates
* that it is 1,000,000 more likely that the data matches the genotypes than not. A negative value indicates
* that the data do not match. A score that is near zero is inconclusive and can result from low coverage
* or non-informative genotypes.
* <p>
* The identity check makes use of haplotype blocks defined in the {@link #HAPLOTYPE_MAP} file to enable it to have higher
* statistical power for detecting identity or swap by aggregating data from several SNPs in the haplotype block. This
* enables an identity check of samples with very low coverage (e.g. ~1x mean coverage).
* <p>
* When provided a VCF, the identity check looks at the PL, GL and GT fields (in that order) and uses the first one that
* it finds.
*
* @author Tim Fennell
*/
@CommandLineProgramProperties(
summary = CheckFingerprint.USAGE_DETAILS,
oneLineSummary = "Computes a fingerprint from the supplied input (SAM/BAM or VCF) file and compares it to the provided genotypes",
programGroup = DiagnosticsAndQCProgramGroup.class
)
@DocumentedFeature
public class CheckFingerprint extends CommandLineProgram {
static final String USAGE_DETAILS =
"Checks the sample identity of the sequence/genotype data in the provided file (SAM/BAM or VCF) " +
"against a set of known genotypes in the supplied genotype file (in VCF format).\n " +
"\n " +
"<h3>Summary</h3> " +
"Computes a fingerprint (essentially, genotype information from different parts of the genome) " +
"from the supplied input file (SAM/BAM or VCF) file and " +
"compares it to the expected fingerprint genotypes provided. " +
"The key output is a LOD score which represents the relative likelihood of " +
"the sequence data originating from the same sample as the genotypes vs. from a random sample. " +
"<br/> " +
"Two outputs are produced: " +
"<ol> " +
"<li>" +
"A summary metrics file that gives metrics of the fingerprint matches when comparing the input to a set of " +
"genotypes for the expected sample. " +
"At the single sample level (if the input was a VCF) or at the read level (lane or index within a lane) " +
"(if the input was a SAM/BAM) " +
"</li> " +
"<li>" +
"A detail metrics file that contains an individual SNP/Haplotype comparison within a fingerprint comparison." +
"</li> " +
"</ol> " +
"The metrics files fill the fields of the classes FingerprintingSummaryMetrics and FingerprintingDetailMetrics. " +
"The output files may be specified individually using the SUMMARY_OUTPUT and DETAIL_OUTPUT options. " +
"Alternatively the OUTPUT option may be used instead to give the base of the two output files, " +
"with the summary metrics having a file extension \".fingerprinting_summary_metrics\", " +
"and the detail metrics having a file extension \".fingerprinting_detail_metrics\". " +
"<br/> " +
"<h3>Example comparing a bam against known genotypes:</h3> " +
"<pre> " +
" java -jar picard.jar CheckFingerprint \\\n " +
" INPUT=sample.bam \\\n " +
" GENOTYPES=sample_genotypes.vcf \\\n " +
" HAPLOTYPE_MAP=fingerprinting_haplotype_database.txt \\\n " +
" OUTPUT=sample_fingerprinting " +
"</pre> " +
"<br/> " +
"<h3>Detailed Explanation</h3>" +
"This tool calculates a single number that reports the LOD score for identity check between the INPUT and the GENOTYPES. " +
"A positive value indicates that the data seems to have come from the same individual or, " +
"in other words the identity checks out. " +
"The scale is logarithmic (base 10), " +
"so a LOD of 6 indicates that it is 1,000,000 more likely that the data matches the genotypes than not. " +
"A negative value indicates that the data do not match. " +
"A score that is near zero is inconclusive and can result from low coverage or non-informative genotypes. " +
"\n\n " +
"The identity check makes use of haplotype blocks defined in the HAPLOTYPE_MAP file to enable it to have higher " +
"statistical power for detecting identity or swap by aggregating data from several SNPs in the haplotype block. " +
"This enables an identity check of samples with very low coverage (e.g. ~1x mean coverage). " +
"\n\n " +
"When provided a VCF, the identity check looks at the PL, GL and GT fields (in that order) " +
"and uses the first one that it finds. ";
@Argument(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "Input file SAM/BAM or VCF. If a VCF is used, " +
"it must have at least one sample. If there are more than one samples in the VCF, the parameter OBSERVED_SAMPLE_ALIAS must " +
"be provided in order to indicate which sample's data to use. If there are no samples in the VCF, an exception will be thrown.")
public String INPUT;
@Argument(optional = true, doc = "If the input is a VCF, this parameters used to select which sample's data in the VCF to use.")
public String OBSERVED_SAMPLE_ALIAS;
@Argument(shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "The base prefix of output files to write. The summary metrics " +
"will have the file extension '" + CheckFingerprint.FINGERPRINT_SUMMARY_FILE_SUFFIX + "' and the detail metrics will have " +
"the extension '" + CheckFingerprint.FINGERPRINT_DETAIL_FILE_SUFFIX + "'.", mutex = {"SUMMARY_OUTPUT", "DETAIL_OUTPUT"})
public String OUTPUT;
@Argument(shortName = "S", doc = "The text file to which to write summary metrics.", mutex = {"OUTPUT"})
public File SUMMARY_OUTPUT;
@Argument(shortName = "D", doc = "The text file to which to write detail metrics.", mutex = {"OUTPUT"})
public File DETAIL_OUTPUT;
@Argument(shortName = "G", doc = "File of genotypes (VCF) to be used in comparison. May contain " +
"any number of genotypes; CheckFingerprint will use only those that are usable for fingerprinting.")
public String GENOTYPES;
@Argument(shortName = "SAMPLE_ALIAS", optional = true, doc = "This parameter can be used to specify which sample's genotypes to use from the " +
"expected VCF file (the GENOTYPES file). If it is not supplied, the sample name from the input " +
"(VCF or BAM read group header) will be used.")
public String EXPECTED_SAMPLE_ALIAS;
@Argument(shortName = "H", doc = "The file lists a set of SNPs, optionally arranged in high-LD blocks, to be used for fingerprinting. See " +
"https://software.broadinstitute.org/gatk/documentation/article?id=9526 for details.")
public File HAPLOTYPE_MAP;
@Argument(shortName = "LOD", doc = "When counting haplotypes checked and matching, count only haplotypes " +
"where the most likely haplotype achieves at least this LOD.")
public double GENOTYPE_LOD_THRESHOLD = 5;
@Argument(optional = true, shortName = "IGNORE_RG", doc = "If the input is a SAM/BAM, and this parameter is true, treat the " +
"entire input BAM as one single read group in the calculation, " +
"ignoring RG annotations, and producing a single fingerprint metric for the entire BAM.")
public boolean IGNORE_READ_GROUPS = false;
private final Log log = Log.getInstance(CheckFingerprint.class);
public static final String FINGERPRINT_SUMMARY_FILE_SUFFIX = "fingerprinting_summary_metrics";
public static final String FINGERPRINT_DETAIL_FILE_SUFFIX = "fingerprinting_detail_metrics";
private Path inputPath;
private Path genotypesPath;
@Override
protected int doWork() {
final File outputDetailMetricsFile, outputSummaryMetricsFile;
if (OUTPUT == null) {
outputDetailMetricsFile = DETAIL_OUTPUT;
outputSummaryMetricsFile = SUMMARY_OUTPUT;
} else {
OUTPUT += ".";
outputDetailMetricsFile = new File(OUTPUT + FINGERPRINT_DETAIL_FILE_SUFFIX);
outputSummaryMetricsFile = new File(OUTPUT + FINGERPRINT_SUMMARY_FILE_SUFFIX);
}
try {
inputPath = IOUtil.getPath(INPUT);
genotypesPath = IOUtil.getPath(GENOTYPES);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
IOUtil.assertFileIsReadable(inputPath);
IOUtil.assertFileIsReadable(HAPLOTYPE_MAP);
IOUtil.assertFileIsReadable(genotypesPath);
IOUtil.assertFileIsWritable(outputDetailMetricsFile);
IOUtil.assertFileIsWritable(outputSummaryMetricsFile);
final FingerprintChecker checker = new FingerprintChecker(HAPLOTYPE_MAP);
checker.setReferenceFasta(REFERENCE_SEQUENCE);
List<FingerprintResults> results;
String observedSampleAlias = null;
if (fileContainsReads(inputPath)) {
SequenceUtil.assertSequenceDictionariesEqual(SAMSequenceDictionaryExtractor.extractDictionary(inputPath), SAMSequenceDictionaryExtractor.extractDictionary(genotypesPath), true);
SequenceUtil.assertSequenceDictionariesEqual(SAMSequenceDictionaryExtractor.extractDictionary(inputPath), checker.getHeader().getSequenceDictionary(), true);
// Verify that there's only one sample in the SAM/BAM.
final SamReader in = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).open(inputPath);
for (final SAMReadGroupRecord rec : in.getFileHeader().getReadGroups()) {
if (observedSampleAlias == null) {
observedSampleAlias = rec.getSample();
} else if (!observedSampleAlias.equals(rec.getSample())) {
throw new PicardException("inputPath SAM/BAM file must not contain data from multiple samples.");
}
}
CloserUtil.close(in);
// If expected sample alias isn't supplied, assume it's the one from the INPUT file's RGs
if (EXPECTED_SAMPLE_ALIAS == null) {
EXPECTED_SAMPLE_ALIAS = observedSampleAlias;
}
results = checker.checkFingerprints(
Collections.singletonList(inputPath),
Collections.singletonList(genotypesPath),
EXPECTED_SAMPLE_ALIAS,
IGNORE_READ_GROUPS);
} else { // Input is a VCF
// Note that FingerprintChecker.loadFingerprints() verifies that the VCF's Sequence Dictionaries agree with that of the Haplotye Map File
// Verify that there is only one sample in the VCF
final VCFFileReader fileReader = new VCFFileReader(inputPath, false);
final VCFHeader fileHeader = fileReader.getFileHeader();
if (fileHeader.getNGenotypeSamples() < 1) {
throw new PicardException("inputPath VCF file must contain at least one sample.");
}
if ((fileHeader.getNGenotypeSamples() > 1) && (OBSERVED_SAMPLE_ALIAS == null)) {
throw new PicardException("inputPath VCF file contains multiple samples and yet the OBSERVED_SAMPLE_ALIAS parameter is not set.");
}
// set observedSampleAlias to the parameter, if set. Otherwise, if here, this must be a single sample VCF, get it's sample
observedSampleAlias = (OBSERVED_SAMPLE_ALIAS != null) ? OBSERVED_SAMPLE_ALIAS : fileHeader.getGenotypeSamples().get(0);
// Now verify that observedSampleAlias is, in fact, in the VCF
if (!fileHeader.getGenotypeSamples().contains(observedSampleAlias)) {
throw new PicardException("inputPath VCF file does not contain OBSERVED_SAMPLE_ALIAS: " + observedSampleAlias);
}
if (OBSERVED_SAMPLE_ALIAS == null) {
observedSampleAlias = fileHeader.getGenotypeSamples().get(0);
}
fileReader.close();
// If expected sample alias isn't supplied, assume it's the one from the INPUT file
if (EXPECTED_SAMPLE_ALIAS == null) {
EXPECTED_SAMPLE_ALIAS = observedSampleAlias;
}
results = checker.checkFingerprintsFromPaths(
Collections.singletonList(inputPath),
Collections.singletonList(genotypesPath),
observedSampleAlias,
EXPECTED_SAMPLE_ALIAS);
}
final MetricsFile<FingerprintingSummaryMetrics, ?> summaryFile = getMetricsFile();
final MetricsFile<FingerprintingDetailMetrics, ?> detailsFile = getMetricsFile();
boolean allZeroLod = true;
for (final FingerprintResults fpr : results) {
final MatchResults mr = fpr.getMatchResults().first();
final FingerprintingSummaryMetrics metrics = new FingerprintingSummaryMetrics();
metrics.READ_GROUP = fpr.getReadGroup();
metrics.SAMPLE = EXPECTED_SAMPLE_ALIAS;
metrics.LL_EXPECTED_SAMPLE = mr.getSampleLikelihood();
metrics.LL_RANDOM_SAMPLE = mr.getPopulationLikelihood();
metrics.LOD_EXPECTED_SAMPLE = mr.getLOD();
for (final LocusResult lr : mr.getLocusResults()) {
final DiploidGenotype expectedGenotype = lr.getExpectedGenotype();
final DiploidGenotype observedGenotype = lr.getMostLikelyGenotype();
// Update the summary metrics
metrics.HAPLOTYPES_WITH_GENOTYPES++;
if (lr.getLodGenotype() >= GENOTYPE_LOD_THRESHOLD) {
metrics.HAPLOTYPES_CONFIDENTLY_CHECKED++;
if (lr.getExpectedGenotype() == lr.getMostLikelyGenotype()) {
metrics.HAPLOTYPES_CONFIDENTLY_MATCHING++;
}
if (expectedGenotype.isHeterozygous() && observedGenotype.isHomomozygous()) {
metrics.HET_AS_HOM++;
}
if (expectedGenotype.isHomomozygous() && observedGenotype.isHeterozygous()) {
metrics.HOM_AS_HET++;
}
if (expectedGenotype.isHomomozygous() && observedGenotype.isHomomozygous()
&& expectedGenotype.compareTo(observedGenotype) != 0) {
metrics.HOM_AS_OTHER_HOM++;
}
}
// Build the detail metrics
final FingerprintingDetailMetrics details = new FingerprintingDetailMetrics();
details.READ_GROUP = fpr.getReadGroup();
details.SAMPLE = EXPECTED_SAMPLE_ALIAS;
details.SNP = lr.getSnp().getName();
details.SNP_ALLELES = lr.getSnp().getAlleleString();
details.CHROM = lr.getSnp().getChrom();
details.POSITION = lr.getSnp().getPos();
details.EXPECTED_GENOTYPE = expectedGenotype.toString();
details.OBSERVED_GENOTYPE = observedGenotype.toString();
details.LOD = lr.getLodGenotype();
details.OBS_A = lr.getAllele1Count();
details.OBS_B = lr.getAllele2Count();
detailsFile.addMetric(details);
}
summaryFile.addMetric(metrics);
log.info("Read Group: " + metrics.READ_GROUP + " / " + observedSampleAlias + " vs. " + metrics.SAMPLE + ": LOD = " + metrics.LOD_EXPECTED_SAMPLE);
allZeroLod &= metrics.LOD_EXPECTED_SAMPLE == 0;
}
summaryFile.write(outputSummaryMetricsFile);
detailsFile.write(outputDetailMetricsFile);
if (allZeroLod) {
log.error("No non-zero results found. This is likely an error. " +
"Probable cause: EXPECTED_SAMPLE (if provided) or the sample name from INPUT (if EXPECTED_SAMPLE isn't provided)" +
"isn't a sample in GENOTYPES file.");
return 1;
}
return 0;
}
protected String[] customCommandLineValidation() {
try {
final boolean fileContainsReads = fileContainsReads(IOUtil.getPath(INPUT));
if (!fileContainsReads && IGNORE_READ_GROUPS) {
return new String[]{"The parameter IGNORE_READ_GROUPS can only be used with BAM/SAM/CRAM inputs."};
}
if (fileContainsReads && OBSERVED_SAMPLE_ALIAS != null) {
return new String[]{"The parameter OBSERVED_SAMPLE_ALIAS can only be used with a VCF input."};
}
} catch (IOException e) {
e.printStackTrace();
}
if (REFERENCE_SEQUENCE == null && INPUT.endsWith(SamReader.Type.CRAM_TYPE.fileExtension())) {
return new String[]{"REFERENCE must be provided when using CRAM as input."};
}
return super.customCommandLineValidation();
}
static boolean fileContainsReads(final Path p) {
return (p.toUri().getRawPath().endsWith(SamReader.Type.BAM_TYPE.fileExtension()) ||
p.toUri().getRawPath().endsWith(SamReader.Type.SAM_TYPE.fileExtension()) ||
p.toUri().getRawPath().endsWith(SamReader.Type.CRAM_TYPE.fileExtension()));
}
} |
package com.splicemachine.test;
import com.splicemachine.derby.test.framework.SpliceNetConnection;
import org.apache.log4j.Logger;
import org.junit.Assert;
import java.sql.*;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
public class Benchmark {
public static final Logger LOG = Logger.getLogger(Benchmark.class);
/*
* Statistics
*/
static final int MAXSTATS = 1024;
static final boolean cumulative = true; // false - reset stats on every report
static AtomicLongArray statsCnt;
static AtomicLongArray statsSum;
static AtomicLongArray statsMin;
static AtomicLongArray statsMax;
static final AtomicLong nextReport = new AtomicLong(0);
static long deadLine = Long.MAX_VALUE;
static ConcurrentHashMap<String, Integer> indexMap = new ConcurrentHashMap<>(MAXSTATS);
static final AtomicInteger lastIdx = new AtomicInteger(0);
static {
resetStats();
}
public static void updateStats(String stat) {
updateStats(stat, 1, 0);
}
public static void updateStats(String stat, long delta) {
updateStats(stat, 1, delta);
}
public static void updateStats(String stat, long increment, long delta) {
int idx = indexMap.computeIfAbsent(stat, key -> lastIdx.getAndIncrement());
if (idx >= MAXSTATS) {
throw new RuntimeException("ERROR: Too many statistics: " + idx);
}
statsCnt.addAndGet(idx, increment);
statsSum.addAndGet(idx, delta);
statsMin.accumulateAndGet(idx, delta / increment, Math::min);
statsMax.accumulateAndGet(idx, (delta + increment - 1) / increment, Math::max);
long curTime = System.currentTimeMillis();
long t = nextReport.get();
if (curTime > t && nextReport.compareAndSet(t, (t == 0 ? curTime : t) + 60000) && t > 0) {
reportStats();
if (curTime > deadLine) {
throw new RuntimeException("Deadline has been reached");
}
}
}
public static void reportStats() {
if (indexMap.isEmpty()) {
return;
}
StringBuilder sb = new StringBuilder().append("Statistics:");
for (Map.Entry<String, Integer> entry : indexMap.entrySet()) {
int idx = entry.getValue();
long count = cumulative ? statsCnt.get(idx) : statsCnt.getAndSet(idx, 0);
long time = cumulative ? statsSum.get(idx) : statsSum.getAndSet(idx, 0);
long min = cumulative ? statsMin.get(idx) : statsMin.getAndSet(idx, Long.MAX_VALUE);
long max = cumulative ? statsMax.get(idx) : statsMax.getAndSet(idx, 0);
if (count != 0) {
long avg = (time + count / 2) / count;
sb.append("\n\t").append(entry.getKey());
sb.append("\tops: ").append(count);
sb.append("\ttime(s): ").append(time / 1000);
sb.append("\tmin/avg/max(ms): [").append(min).append(" .. ").append(avg).append(" .. ").append(max).append("]");
}
}
LOG.info(sb.toString());
}
public static void resetStats() {
reportStats();
nextReport.set(0);
statsCnt = new AtomicLongArray(MAXSTATS);
statsSum = new AtomicLongArray(MAXSTATS);
statsMin = new AtomicLongArray(MAXSTATS);
statsMax = new AtomicLongArray(MAXSTATS);
for (int i = 0; i < statsMin.length(); ++i) {
statsMin.set(i, Long.MAX_VALUE);
}
}
/*
* Setup
*/
public static class RegionServerInfo {
public String hostName;
public String release;
public String buildHash;
RegionServerInfo(String hostName, String release, String buildHash) {
this.hostName = hostName;
this.release = release;
this.buildHash = buildHash;
}
}
public static RegionServerInfo[] getRegionServerInfo() throws Exception {
try (Connection connection = SpliceNetConnection.getDefaultConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("CALL SYSCS_UTIL.SYSCS_GET_VERSION_INFO()");
try (ResultSet rs = statement.getResultSet()) {
ArrayList<RegionServerInfo> info = new ArrayList<>();
while (rs.next()) {
info.add(new RegionServerInfo(rs.getString(1), rs.getString(2), rs.getString(3)));
}
return info.toArray(new RegionServerInfo[info.size()]);
}
}
finally {
connection.rollback();
}
}
}
public static void getInfo() throws Exception {
try (Connection connection = SpliceNetConnection.getDefaultConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("CALL SYSCS_UTIL.SYSCS_GET_VERSION_INFO()");
try (ResultSet rs = statement.getResultSet()) {
while (rs.next()) {
String host = rs.getString(1);
String release = rs.getString(2);
LOG.info("HOST: " + host + " SPLICE: " + release);
}
}
}
finally {
connection.rollback();
}
}
}
/*
* Parallel execution
*/
public static void runBenchmark(int numThreads, Runnable runnable) {
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < threads.length; ++i) {
Thread thread = new Thread(runnable);
threads[i] = thread;
}
for (Thread t : threads) {
t.start();
}
try {
for (Thread thread : threads) {
thread.join();
}
}
catch (InterruptedException ie) {
LOG.error("Interrupted while waiting for threads to finish", ie);
}
resetStats();
}
/***
* Executes `query` using `conn` and verifies `matchLines` against the query's result set.
*
* @param matchLines a map of the expected String occurrence (s) in each
* line of the result set, e.g. { {1,['abc','def']}, {10, 'ghi'}} expects line 1
* contains 'abc' and 'def', and line 10 contains 'ghi'.
*/
public static void executeQueryAndMatchLines(Connection conn,
String query,
Map<Integer,String[]> matchLines) throws Exception {
try (PreparedStatement ps = conn.prepareStatement(query)) {
try (ResultSet resultSet = ps.executeQuery()) {
int i = 0;
int k = 0;
while (resultSet.next()) {
i++;
for (Map.Entry<Integer, String[]> entry : matchLines.entrySet()) {
int level = entry.getKey();
if (level == i) {
String resultString = resultSet.getString(1);
for (String phrase : entry.getValue()) {
Assert.assertTrue("failed query at level (" + level + "): \n" + query + "\nExpected: " + phrase + "\nWas: "
+ resultString, resultString.contains(phrase));
}
k++;
}
}
}
if (k < matchLines.size()) {
Assert.fail("fail to match the given strings");
}
}
}
}
} |
package py.una.med.base.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlOutcomeTargetLink;
import javax.faces.component.html.HtmlOutputLink;
import javax.faces.context.FacesContext;
import org.richfaces.component.UIPanelMenu;
import org.richfaces.component.UIPanelMenuGroup;
import org.richfaces.component.UIPanelMenuItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;
import py.una.med.base.breadcrumb.BreadcrumbController;
import py.una.med.base.configuration.PropertiesUtil;
import py.una.med.base.domain.Menu;
import py.una.med.base.domain.Menu.Menus;
import py.una.med.base.dynamic.forms.SIGHComponentFactory;
import py.una.med.base.util.HostResolver;
import py.una.med.base.util.I18nHelper;
/**
* Clase que implementa la creacion del menu de la aplicacion.
*
* @author Arturo Volpe Torres
* @since 1.0
* @version 1.0 Feb 20, 2013
*
*/
@SessionScoped
@Controller
@ManagedBean
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class MenuBean {
private UIPanelMenu menupanel;
// private final Logger logger = LoggerFactory.getLogger(MenuBean.class);
@Autowired
private Menus menus;
@Autowired
private I18nHelper helper;
private HashMap<String, Boolean> expanded;
@Autowired
private PropertiesUtil properties;
@Autowired
private HostResolver hostResolver;
/**
* Configura y retorna un menu
*
* @return Menu entero de la aplicacion
*/
public UIPanelMenu getMenu() {
// XXX Ver como generar el menupanel UNA sola vez.
menupanel = SIGHComponentFactory.getMenu();
menupanel.setGroupExpandedLeftIcon("triangleUp");
menupanel.setGroupCollapsedLeftIcon("triangleDown");
menupanel.setTopGroupExpandedRightIcon("chevronUp");
menupanel.setTopGroupCollapsedRightIcon("chevronDown");
menupanel.setItemLeftIcon("disc");
menupanel.setStyleClass("menu");
menupanel.getChildren().clear();
menupanel.getChildren().addAll(buildMenu());
return menupanel;
}
/**
* Si se llama a esta funcion algo esta mal, se utiliza solamente para que
* "menu" sea una atributo de menuBean
*
* @param obj
*/
public void setMenu(UIPanelMenu menupanel) {
this.menupanel = menupanel;
}
private List<UIComponent> buildMenu() {
List<UIComponent> menuGroups = new ArrayList<UIComponent>(
menus.menus.size());
for (Menu menu : menus.menus) {
UIComponent component = getComponent(menu);
if (component != null) {
menuGroups.add(component);
}
}
return menuGroups;
}
private UIComponent getComponent(Menu menu) {
if (!isVisible(menu)) {
return null;
}
if ((menu.getChildrens() == null) || (menu.getChildrens().size() == 0)) {
return getSingleMenu(menu);
} else {
return getMultipleMenu(menu);
}
}
private UIComponent getMultipleMenu(Menu menu) {
UIPanelMenuGroup menuGroup = SIGHComponentFactory.getMenuGroup();
menuGroup.setId(menu.getIdFather() + menu.getId());
menuGroup.setLabel(helper.getString(menu.getName()));
menuGroup.setExpanded(false);
for (Menu children : menu.getChildrens()) {
UIComponent component = getComponent(children);
if (component != null) {
menuGroup.getChildren().add(component);
}
}
if (menuGroup.getChildren().isEmpty()) {
return null;
}
return menuGroup;
}
private UIComponent getSingleMenu(Menu menu) {
UIPanelMenuItem item = SIGHComponentFactory.getMenuItem();
item.setId(menu.getIdFather() + menu.getId());
item.setLabel(helper.getString(menu.getName()));
UIComponent link;
if (menu.getUrl() != null) {
String menuUrl = menu.getUrl().trim();
String appPlaceHolder = properties
.getProperty("application.appUrlPlaceHolder");
if (menuUrl.startsWith(appPlaceHolder)
|| menuUrl.startsWith("/view")) {
// link correspondiente a este sistema
menuUrl = menuUrl.replace(appPlaceHolder, "");
link = SIGHComponentFactory.getLink();
((HtmlOutcomeTargetLink) link).setOutcome(menuUrl
+ BreadcrumbController.BREADCRUM_URL);
menu.setUrl(menuUrl);
} else {
// link a otro sistema
String urlPlaceHolder = menuUrl.substring(0,
menuUrl.indexOf("/"));
menuUrl = menuUrl.replace(urlPlaceHolder,
hostResolver.getSystemURL(urlPlaceHolder));
link = FacesContext
.getCurrentInstance()
.getApplication()
.createComponent(FacesContext.getCurrentInstance(),
HtmlOutputLink.COMPONENT_TYPE,
"javax.faces.Link");
((HtmlOutputLink) link).setValue(menuUrl
+ BreadcrumbController.BREADCRUM_URL);
menu.setUrl(menuUrl);
}
} else {
link = SIGHComponentFactory.getLink();
}
link.getChildren().add(item);
return link;
}
private boolean isVisible(Menu menu) {
if (menu == null) {
return false;
}
if (menu.getPermissions() == null) {
return true;
}
for (String permission : menu.getPermissions()) {
if (AuthorityController.hasRoleStatic(permission)) {
return true;
}
}
return false;
}
/**
* Retorna si un menu dado debe estar expandido
*
* @return lista de menus, con su corresopndiente debe estar o no expandido
*/
public HashMap<String, Boolean> getExpanded() {
return expanded;
}
/**
*
* @param expanded
*/
public void setExpanded(HashMap<String, Boolean> expanded) {
this.expanded = expanded;
}
} |
package edu.umd.cs.findbugs.sarif; |
package se.lth.cs.connect.routes;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import iot.jcypher.graph.GrNode;
import iot.jcypher.query.JcQueryResult;
import iot.jcypher.query.api.IClause;
import iot.jcypher.query.factories.clause.CASE;
import iot.jcypher.query.factories.clause.CREATE;
import iot.jcypher.query.factories.clause.DO;
import iot.jcypher.query.factories.clause.MATCH;
import iot.jcypher.query.factories.clause.MERGE;
import iot.jcypher.query.factories.clause.NATIVE;
import iot.jcypher.query.factories.clause.OPTIONAL_MATCH;
import iot.jcypher.query.factories.clause.RETURN;
import iot.jcypher.query.factories.clause.WHERE;
import iot.jcypher.query.factories.xpression.X;
import iot.jcypher.query.values.JcBoolean;
import iot.jcypher.query.values.JcNode;
import iot.jcypher.query.values.JcNumber;
import iot.jcypher.query.values.JcRelation;
import ro.pippo.core.Messages;
import ro.pippo.core.PippoSettings;
import ro.pippo.core.route.RouteContext;
import se.lth.cs.connect.Connect;
import se.lth.cs.connect.Graph;
import se.lth.cs.connect.RequestException;
import se.lth.cs.connect.TrustLevel;
import se.lth.cs.connect.modules.AccountSystem;
import se.lth.cs.connect.modules.Database;
/**
* Handles account related actions.
*/
public class Collection extends BackendRouter {
public String getPrefix() { return "/v1/collection"; }
private String inviteTemplate;
private String inviteNewUserTemplate;
private String inviteActionTemplate;
private String frontend;
public Collection(Connect app) {
super(app);
Messages msg = app.getMessages();
inviteTemplate = msg.get("pippo.collectioninvite", "en");
inviteNewUserTemplate = msg.get("pippo.collectioninvitenewuser", "en");
inviteActionTemplate = msg.get("pippo.collectioninviteaction", "en");
frontend = app.getPippoSettings().getString("frontend", "http://localhost:8181");
}
protected void setup(PippoSettings conf) {
// POST api.serpconnect.cs.lth.se/v1/collection HTTP/1.1
// name=blabla
POST("/", (rc) -> {
String email = rc.getSession("email");
if (email == null)
throw new RequestException(401, "Must be logged in.");
String name = rc.getParameter("name").toString();
if (name == null || name.isEmpty())
throw new RequestException("No name parameter");
JcNode coll = new JcNode("c");
JcNode usr = new JcNode("u");
JcNumber id = new JcNumber("x");
//usr-(member_of)->coll-(owner)->user
JcQueryResult res = Database.query(Database.access(), new IClause[]{
MATCH.node(usr).label("user").property("email").value(email),
CREATE.node(usr).relation().type("MEMBER_OF").out()
.node(coll).label("collection")
.property("name").value(name).relation().type("OWNER").out().node(usr),
RETURN.value(coll.id()).AS(id)
});
rc.json().send(
"{ \"id\": " + res.resultOf(id).get(0) + " }");
});
//id must be a string and the id must exist in the database.
ALL("/{id}/.*", (rc) -> {
String ids = rc.getParameter("id").toString();
if (!StringUtils.isNumeric(ids)){
throw new RequestException("Invalid id");
}
int id = Integer.parseInt(ids);
JcNode coll = new JcNode("coll");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
NATIVE.cypher("RETURN true AS ok")
});
if (res.resultOf(new JcBoolean("ok")).size() == 0)
throw new RequestException("id does not exist in database");
rc.next();
});
GET("/{id}/graph", (rc) -> {
int id = rc.getParameter("id").toInt();
JcNode coll = new JcNode("coll");
JcNode node = new JcNode("entry");
JcRelation rel = new JcRelation("rel");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection")
.relation().type("CONTAINS")
.node(node).label("entry"),
WHERE.valueOf(coll.id()).EQUALS(id),
OPTIONAL_MATCH.node(node).relation(rel).out().node().label("facet"),
RETURN.value(node),
RETURN.value(rel)
});
rc.json().send(new Graph(res.resultOf(node), res.resultOf(rel)));
});
// GET api.serpconnect.cs.lth.se/{id}/stats HTTP/1.1
// --> { members: int, entries: int }
GET("/{id}/stats", (rc) -> {
int id = rc.getParameter("id").toInt();
JcNode coll = new JcNode("coll");
JcRelation u = new JcRelation("u");
JcRelation e = new JcRelation("e");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node().label("user")
.relation(u).type("MEMBER_OF")
.node(coll).label("collection")
.relation(e).type("CONTAINS")
.node().label("entry"),
WHERE.valueOf(coll.id()).EQUALS(id),
NATIVE.cypher("RETURN COUNT(DISTINCT u) AS users, COUNT(DISTINCT e) AS entries")
});
final java.math.BigDecimal users = res.resultOf(new JcNumber("users")).get(0);
final java.math.BigDecimal entries = res.resultOf(new JcNumber("entries")).get(0);
class RetVal {
public int members, entries;
public RetVal(int mem, int ent) {
members = mem;
entries = ent;
}
}
rc.json().send(new RetVal(users.intValue(), entries.intValue()));
});
// GET api.serpconnect.cs.lth.se/{id}/entries HTTP/1.1
// --> [entries in collection]
GET("/{id}/entries", (rc) -> {
int id = rc.getParameter("id").toInt();
final JcNode entry = new JcNode("e");
final JcNode coll = new JcNode("c");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection")
.relation().type("CONTAINS")
.node(entry).label("entry"),
WHERE.valueOf(coll.id()).EQUALS(id),
RETURN.value(entry)
});
final List<GrNode> entries = res.resultOf(entry);
rc.status(200).json().send(Graph.Node.fromList(entries));
});
// Must be logged in to accept
ALL("/{id}/.*", (rc) -> {
if (rc.getParameter("id").isEmpty())
throw new RequestException("Invalid collection id");
if (rc.getSession("email") == null)
throw new RequestException(401, "Must be logged in.");
rc.next();
});
POST("/{id}/reject", (rc) -> {
String email = rc.getSession("email");
int id = rc.getParameter("id").toInt();
JcNode user = new JcNode("user");
JcNode coll = new JcNode("coll");
JcRelation rel = new JcRelation("rel");
handleInvitation(rc, "rejected");
// Delete invitation
JcQueryResult res = Database.query(Database.access(), new IClause[] {
MATCH.node(user).label("user").property("email").value(email)
.relation(rel).type("INVITE")
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
DO.DELETE(rel),
NATIVE.cypher("RETURN TRUE AS ok")
});
if (res.resultOf(new JcBoolean("ok")).size() > 0)
rc.getResponse().ok();
else
throw new RequestException("Not invited to that collection.");
});
// POST api.serpconnect.cs.lth.se/{id}/accept HTTP/1.1
POST("/{id}/accept", (rc) -> {
String email = rc.getSession("email");
int id = rc.getParameter("id").toInt();
JcNode user = new JcNode("user");
JcNode coll = new JcNode("coll");
JcRelation rel = new JcRelation("rel");
handleInvitation(rc, "accepted");
// Replace an INVITE type relation with a MEMBER_OF relation
JcQueryResult res = Database.query(Database.access(), new IClause[]{
MATCH.node(user).label("user").property("email").value(email)
.relation(rel).type("INVITE")
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
MERGE.node(user).relation().out().type("MEMBER_OF").node(coll),
DO.DELETE(rel),
NATIVE.cypher("RETURN TRUE AS ok")
});
if (res.resultOf(new JcBoolean("ok")).size() > 0)
rc.getResponse().ok();
else
throw new RequestException("Not invited to that collection.");
});
// Must be logged in AND member of collection to proceed
ALL("/{id}/.*", (rc) -> {
String email = rc.getSession("email");
int id = rc.getParameter("id").toInt();
JcNode coll = new JcNode("coll");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node().label("user").property("email").value(email)
.relation().out().type("MEMBER_OF")
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
NATIVE.cypher("RETURN TRUE AS ok")
});
if (res.resultOf(new JcBoolean("ok")).size() == 0)
throw new RequestException(403, "You are not a member of that collection");
rc.next();
});
// POST api.serpconnect.cs.lth.se/{id}/leave HTTP/1.1
POST("/{id}/leave", (rc) -> {
String email = rc.getSession("email");
int id = rc.getParameter("id").toInt();
JcNode user = new JcNode("user");
JcNode coll = new JcNode("coll");
JcRelation rel = new JcRelation("connection");
//if the leaver is the owner of the collection delete the entire collection.
if(isOwner(rc)){
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(user).label("user").property("email").value(email)
.relation(rel)
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
DO.DETACH_DELETE(coll)
});
}
else{
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(user).label("user").property("email").value(email)
.relation(rel)
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
DO.DELETE(rel)
});
//Delete collections that have no members (or invites)
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id).
AND().NOT().existsPattern(
X.node().label("user")
.relation()
.node(coll)),
DO.DETACH_DELETE(coll)
});
}
removeEntriesWithNoCollection(rc);
rc.getResponse().ok();
});
// POST api.serpconnect.cs.lth.se/{id}/removeEntry HTTP/1.1
// entryId=...
POST("/{id}/removeEntry", (rc) -> {
int id = rc.getParameter("id").toInt();
int entryId = rc.getParameter("entryId").toInt();
final JcNode entry = new JcNode("e");
final JcNode coll = new JcNode("c");
final JcRelation rel = new JcRelation("r");
// First, remove the relation to the current collection
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection")
.relation(rel).type("CONTAINS")
.node(entry).label("entry"),
WHERE.valueOf(coll.id()).EQUALS(id).AND().valueOf(entry.id()).EQUALS(entryId),
DO.DELETE(rel)
});
//TODO: Optimize: Only remove the entry that was supposed to be delted.
removeEntriesWithNoCollection(rc);
rc.getResponse().ok();
});
// POST api.serpconnect.cs.lth.se/{id}/kick HTTP/1.1
// entryId=...
POST("/{id}/addEntry", (rc) -> {
int id = rc.getParameter("id").toInt();
int entryId = rc.getParameter("entryId").toInt();
final JcNode entry = new JcNode("e");
final JcNode coll = new JcNode("c");
// Connect entry and collection
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
MATCH.node(entry).label("entry"),
WHERE.valueOf(entry.id()).EQUALS(entryId),
MERGE.node(coll).relation().out().type("CONTAINS").node(entry)
});
rc.getResponse().ok();
});
// GET api.serpconnect.cs.lth.se/{id}/members HTTP/1.1
// --> [members in collection]
GET("/{id}/members", (rc) -> {
int id = rc.getParameter("id").toInt();
final JcNode user = new JcNode("u");
final JcNode coll = new JcNode("c");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(coll).label("collection")
.relation().in().type("MEMBER_OF")
.node(user).label("user"),
WHERE.valueOf(coll.id()).EQUALS(id),
RETURN.value(user)
});
Graph.User[] members = Graph.User.fromList(res.resultOf(user));
rc.status(200).json().send(members);
});
//return true if current logged in user is owner of the given collection
GET("/{id}/is-owner", (rc)->{
rc.status(200).json().send(isOwner(rc));
});
//must be logged in AND be member AND be owner of collection AND provide an email to proceed
ALL("/{id}/.*", (rc) -> {
if(!isOwner(rc))
throw new RequestException(401, "You must be an owner of the collection");
if (rc.getParameter("email").isEmpty())
throw new RequestException("Invalid email");
rc.next();
});
// POST api.serpconnect.cs.lth.se/{id}/kick HTTP/1.1
// email=...
POST("/{id}/kick", (rc) -> {
String email = rc.getParameter("email").toString();
//don't allow the user to kick himself
if(rc.getSession("email").toString().equals(rc.getParameter("email").toString()))
throw new RequestException(400, "Can't kick yourself, please use leave collection if you want to leave the collection");
int id = rc.getParameter("id").toInt();
JcNode user = new JcNode("user");
JcNode coll = new JcNode("coll");
JcRelation rel = new JcRelation("connection");
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(user).label("user").property("email").value(email)
.relation(rel)
.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
DO.DELETE(rel),
RETURN.value(user)
});
if(res.resultOf(user).isEmpty())
throw new RequestException(404, email + " is not a member of collection " + id);
rc.getResponse().ok();
});
// POST api.serpconnect.cs.lth.se/{id}/invite HTTP/1.1
// email[0]=...&email[1]=
POST("/{id}/invite", (rc) -> {
int id = rc.getParameter("id").toInt();
List<String> emails = rc.getParameter("email").toList(String.class);
String inviter = rc.getSession("email");
for (String email : emails) {
JcNode user = new JcNode("user");
JcNode inviterNode = new JcNode("inviter");
JcNode coll = new JcNode("coll");
JcQueryResult res2 = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node().label("user").property("email").value(email).
relation().out().type("MEMBER_OF").
node(coll),
WHERE.valueOf(coll.id()).EQUALS(id),
NATIVE.cypher("RETURN TRUE AS ok")
});
if(res2.resultOf(new JcBoolean("ok")).size()==0){
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(user).label("user").property("email").value(email),
RETURN.value(user)
});
boolean emptyUser = res.resultOf(user).isEmpty();
//create temporary unregistered user if non existent
if (emptyUser) {
AccountSystem.createAccount(email, "", TrustLevel.UNREGISTERED);
} else if(res.resultOf(user).get(0).getProperty("trust").getValue().equals(TrustLevel.UNREGISTERED)){
emptyUser = true;
}
// Use MERGE so we don't end up with multiple invites per user
// keep track of who invited the user and to which collection
Database.query(rc.getLocal("db"), new IClause[] {
MATCH.node(user).label("user").property("email").value(email),
MATCH.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
MATCH.node(inviterNode).label("user").property("email").value(inviter),
MERGE.node(user).relation().out().type("INVITE").node(coll),
MERGE.node(user).relation().out().type("INVITER")
.property("parentnode").value(id).node(inviterNode)
});
String template = emptyUser ? inviteNewUserTemplate
: inviteTemplate;
template = template.replace("{frontend}", frontend);
app.getMailClient().sendEmail(email, "SERP Connect - Collection Invite", template);
}
}
rc.getResponse().ok();
});
}
private boolean isOwner(RouteContext rc){
final int id = rc.getParameter("id").toInt();
final String email = rc.getSession("email");
final JcNode usr = new JcNode("u");
final JcNode coll = new JcNode("c");
//return true as ok if the logged in user is owner of the collection
JcQueryResult res = Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(usr).label("user").
property("email").value(email).
relation().type("OWNER").in().
node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
NATIVE.cypher("RETURN true AS ok")
});
return res.resultOf(new JcBoolean("ok")).size()>0;
}
private void removeEntriesWithNoCollection(RouteContext rc){
final JcNode entry = new JcNode("e");
Database.query(rc.getLocal("db"), new IClause[]{
MATCH.node(entry).label("entry"),
WHERE.NOT().existsPattern(
X.node().label("collection")
.relation().type("CONTAINS")
.node(entry)),
DO.DETACH_DELETE(entry)
});
}
//will reply an email to all users that invited this user which informs them
//of what action was taken.
private void handleInvitation(RouteContext rc, String action) {
final String email = rc.getSession("email");
final int id = rc.getParameter("id").toInt();
// 1 invitee -- Many inviters: Must destroy all relations
// TODO: Only return data we want (emails)
final JcNode user = new JcNode("user");
final JcNode inviter = new JcNode("inviter");
final JcRelation rel = new JcRelation("rel");
JcQueryResult inviters = Database.query(rc.getLocal("db"), new IClause[] {
MATCH.node(user).label("user").property("email").value(email)
.relation(rel).type("INVITER").node(inviter),
WHERE.valueOf(rel.property("parentnode").toInt()).EQUALS(id),
DO.DELETE(rel),
RETURN.value(inviter)
});
// Get the name of the collection.
// TODO: Only return data we want (collection name)
final JcNode coll = new JcNode("coll2");
final JcQueryResult collQuery = Database.query(Database.access(), new IClause[] {
MATCH.node(coll).label("collection"),
WHERE.valueOf(coll.id()).EQUALS(id),
RETURN.value(coll)
});
final Graph.Collection collection = new Graph.Collection(collQuery.resultOf(coll).get(0));
final String template = inviteActionTemplate
.replace("{user}", email)
.replace("{action}", action)
.replace("{collection}", collection.name);
// Maybe only send email to person whose invite user accepted?
final Graph.User[] invitors = Graph.User.fromList(inviters.resultOf(inviter));
for (Graph.User invitor : invitors) {
app.getMailClient().sendEmail(invitor.email, "SERP Connect - Collection Invite Response", template);
}
}
} |
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Objects;
import java.util.Optional;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
import javax.swing.plaf.synth.Region;
import javax.swing.plaf.synth.SynthConstants;
import javax.swing.plaf.synth.SynthContext;
import javax.swing.plaf.synth.SynthLookAndFeel;
import javax.swing.plaf.synth.SynthStyle;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ClippedTitleTabbedPane tabs = new ClippedTitleTabbedPane(SwingConstants.LEFT);
tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabs.addTab("1111111111111111111", new ColorIcon(Color.RED), new JScrollPane(new JTree()));
tabs.addTab("2", new ColorIcon(Color.GREEN), new JScrollPane(new JTable(5, 3)));
tabs.addTab("33333333333333", new ColorIcon(Color.BLUE), new JLabel("666666666"));
tabs.addTab("444444444444444444444444", new ColorIcon(Color.ORANGE), new JSplitPane());
add(new JLayer<>(tabs, new TabAreaResizeLayer()));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setMinimumSize(new Dimension(256, 200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ClippedTitleTabbedPane extends JTabbedPane {
private static final int MIN_WIDTH = 24;
private int tabAreaWidth = 32;
// protected ClippedTitleTabbedPane() {
// super();
protected ClippedTitleTabbedPane(int tabPlacement) {
super(tabPlacement);
}
private Insets getSynthInsets(Region region) {
SynthStyle style = SynthLookAndFeel.getStyle(this, region);
SynthContext context = new SynthContext(this, region, style, SynthConstants.ENABLED);
return style.getInsets(context, null);
}
private Insets getTabInsets() {
return Optional.ofNullable(UIManager.getInsets("TabbedPane.tabInsets"))
.orElseGet(() -> getSynthInsets(Region.TABBED_PANE_TAB));
}
private Insets getTabAreaInsets() {
return Optional.ofNullable(UIManager.getInsets("TabbedPane.tabAreaInsets"))
.orElseGet(() -> getSynthInsets(Region.TABBED_PANE_TAB_AREA));
}
public int getTabAreaWidth() {
return tabAreaWidth;
}
public void setTabAreaWidth(int width) {
int w = Math.max(MIN_WIDTH, Math.min(width, getWidth() - MIN_WIDTH));
if (tabAreaWidth != w) {
tabAreaWidth = w;
revalidate(); // doLayout();
}
}
@Override public void doLayout() {
int tabCount = getTabCount();
if (tabCount == 0 || !isVisible()) {
super.doLayout();
return;
}
Insets tabAreaInsets = getTabAreaInsets();
Insets insets = getInsets();
int areaWidth = getWidth() - tabAreaInsets.left - tabAreaInsets.right - insets.left - insets.right;
int tabWidth; // = tabInsets.left + tabInsets.right + 3;
int gap;
int tabPlacement = getTabPlacement();
if (tabPlacement == LEFT || tabPlacement == RIGHT) {
tabWidth = getTabAreaWidth();
gap = 0;
} else { // TOP || BOTTOM
tabWidth = areaWidth / tabCount;
gap = areaWidth - tabWidth * tabCount;
}
// "3" is magic number @see BasicTabbedPaneUI#calculateTabWidth
Insets tabInsets = getTabInsets();
tabWidth -= tabInsets.left + tabInsets.right + 3;
updateAllTabWidth(tabWidth, gap);
super.doLayout();
}
@Override public void insertTab(String title, Icon icon, Component component, String tip, int index) {
super.insertTab(title, icon, component, Objects.toString(tip, title), index);
setTabComponentAt(index, new JLabel(title, icon, SwingConstants.LEADING));
}
private void updateAllTabWidth(int tabWidth, int gap) {
Dimension dim = new Dimension();
int rest = gap;
for (int i = 0; i < getTabCount(); i++) {
Component c = getTabComponentAt(i);
if (c instanceof JComponent) {
JComponent tab = (JComponent) c;
int a = (i == getTabCount() - 1) ? rest : 1;
int w = rest > 0 ? tabWidth + a : tabWidth;
dim.setSize(w, tab.getPreferredSize().height);
tab.setPreferredSize(dim);
rest -= a;
}
}
}
}
class TabAreaResizeLayer extends LayerUI<ClippedTitleTabbedPane> {
private int offset;
private boolean resizing;
@Override public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer<?>) c).setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
}
@Override public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer<?>) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
@Override protected void processMouseEvent(MouseEvent e, JLayer<? extends ClippedTitleTabbedPane> l) {
ClippedTitleTabbedPane tabbedPane = l.getView();
if (e.getID() == MouseEvent.MOUSE_PRESSED) {
Rectangle rect = getDividerBounds(tabbedPane);
Point pt = e.getPoint();
SwingUtilities.convertPoint(e.getComponent(), pt, tabbedPane);
if (rect.contains(pt)) {
offset = pt.x - tabbedPane.getTabAreaWidth();
tabbedPane.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
resizing = true;
e.consume();
}
} else if (e.getID() == MouseEvent.MOUSE_RELEASED) {
tabbedPane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
resizing = false;
}
}
@Override protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends ClippedTitleTabbedPane> l) {
ClippedTitleTabbedPane tabbedPane = l.getView();
Point pt = e.getPoint();
SwingUtilities.convertPoint(e.getComponent(), pt, tabbedPane);
if (e.getID() == MouseEvent.MOUSE_MOVED) {
Rectangle r = getDividerBounds(tabbedPane);
Cursor c = Cursor.getPredefinedCursor(r.contains(pt) ? Cursor.W_RESIZE_CURSOR : Cursor.DEFAULT_CURSOR);
tabbedPane.setCursor(c);
} else if (e.getID() == MouseEvent.MOUSE_DRAGGED && resizing) {
tabbedPane.setTabAreaWidth(pt.x - offset);
e.consume();
}
}
private static Rectangle getDividerBounds(ClippedTitleTabbedPane tabbedPane) {
Dimension dividerSize = new Dimension(4, 4);
Rectangle bounds = tabbedPane.getBounds();
Rectangle compRect = Optional.ofNullable(tabbedPane.getSelectedComponent())
.map(Component::getBounds).orElseGet(Rectangle::new);
switch (tabbedPane.getTabPlacement()) {
case SwingConstants.LEFT:
bounds.x = compRect.x - dividerSize.width;
bounds.width = dividerSize.width * 2;
break;
case SwingConstants.RIGHT:
bounds.x += compRect.x + compRect.width - dividerSize.width;
bounds.width = dividerSize.width * 2;
break;
case SwingConstants.BOTTOM:
bounds.y += compRect.y + compRect.height - dividerSize.height;
bounds.height = dividerSize.height * 2;
break;
default: // case SwingConstants.TOP:
bounds.y = compRect.y - dividerSize.height;
bounds.height = dividerSize.height * 2;
break;
}
return bounds;
}
}
class ColorIcon implements Icon {
private final Color color;
protected ColorIcon(Color color) {
this.color = color;
}
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
g2.translate(x, y);
g2.setPaint(color);
g2.fillRect(1, 1, getIconWidth() - 3, getIconHeight() - 3);
g2.dispose();
}
@Override public int getIconWidth() {
return 16;
}
@Override public int getIconHeight() {
return 16;
}
} |
package seedu.address.commons.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import seedu.address.commons.exceptions.IllegalValueException;
public class DateUtil {
private static List<SimpleDateFormat> DATE_FORMATS; //validate date format if both time and date are present
private static List<SimpleDateFormat> DATE_FORMATS1; //validate date format if only date is present
private static List<SimpleDateFormat> DATE_FORMATS2; //convert DATE_FORMATS1 date to date and time
private static List<SimpleDateFormat> TIME_FORMATS; //convert DATE_FORMATS1 date to date and time
public static final String INVALID_FORMAT = "Invalid Format";
public static final String INVALID_TIME = "Time Input is missing";
public DateUtil() {
DATE_FORMATS = new ArrayList<>();
DATE_FORMATS1 = new ArrayList<>();
DATE_FORMATS2 = new ArrayList<>();
TIME_FORMATS = new ArrayList<>();
TIME_FORMATS.add(new SimpleDateFormat("h:mm a"));
TIME_FORMATS.add(new SimpleDateFormat("HHmm"));
TIME_FORMATS.add(new SimpleDateFormat("HH:mm"));
TIME_FORMATS.add(new SimpleDateFormat("H:mm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy h:mm a"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy h:mm a"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy h.mm a"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy h.mm a"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy HHmm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy HHmm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy Hmm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy Hmm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy HH:mm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy HH:mm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy H:mm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy H:mm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy HH.mm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy HH.mm"));
DATE_FORMATS.add(new SimpleDateFormat("d-MM-yyyy H.mm"));
DATE_FORMATS.add(new SimpleDateFormat("d.MM.yyyy H.mm"));
DATE_FORMATS.add(new SimpleDateFormat("EEE, MMM d, yyyy h:mm a"));
DATE_FORMATS1.add(new SimpleDateFormat("d-MM-yyyy"));
DATE_FORMATS1.add(new SimpleDateFormat("d.MM.yyyy"));
DATE_FORMATS1.add(new SimpleDateFormat("EEE, MMM d, yyyy"));
DATE_FORMATS2.add(new SimpleDateFormat("d-MM-yyyy HH:mm"));
DATE_FORMATS2.add(new SimpleDateFormat("d.MM.yyyy HH:mm"));
DATE_FORMATS2.add(new SimpleDateFormat("d-MM-yyyy H:mm"));
DATE_FORMATS2.add(new SimpleDateFormat("d.MM.yyyy H:mm"));
}
//@@author A0125680H
/**
* Validate date format with regular expression
*
* @param date
* @return true valid date format, false invalid date format
*
*/
public static boolean validate(String date) {
Date validDate;
for (SimpleDateFormat sdf : DATE_FORMATS) {
try {
validDate = sdf.parse(date);
if (date.equals(sdf.format(validDate))) {
return true;
}
} catch (ParseException e) {
continue;
}
}
for (SimpleDateFormat sdf : DATE_FORMATS1) {
try {
validDate = sdf.parse(date);
if (date.equals(sdf.format(validDate))) {
return true;
}
} catch (ParseException e) {
continue;
}
}
return false;
}
//@@author A0131813R
public static Date parseDateTime(String date) throws IllegalValueException {
Date validDate;
for (SimpleDateFormat sdf : DATE_FORMATS) {
try {
validDate = sdf.parse(date);
if (date.equals(sdf.format(validDate))) {
return validDate;
}
} catch (ParseException e) {
continue;
}
}
throw new IllegalValueException(INVALID_FORMAT);
}
public static boolean hasPassed(Date date) {
Date today = Calendar.getInstance().getTime();
if (date.before(today)) {
return true;
} else {
return false;
}
}
public static boolean isValidDate(String test) {
if (validate(test) || test == "")
return true;
else
return false;
}
/**
* Convert today's date into date format Must contain time of the day in
* hour and mins
*
* @param string
* "tomorrow"
* @return tomorrow in valid date format
*/
public static String FixedTime(String date) throws IllegalValueException {
String[] timeparts = date.split(" ");
Date today = new Date();
String strDate;
int dayIndex;
if(date.contains("today"))
strDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
else if(date.contains("tomorrow")){
new Date(today.getTime() + TimeUnit.DAYS.toMillis(1));
strDate = new SimpleDateFormat("dd-MM-yyyy").format(today.getTime() + TimeUnit.DAYS.toMillis(1));
}
else if (date.contains("mon")||date.contains("tue")||date.contains("wed")||date.contains("thu")||date.contains("fri")||date.contains("sat")||date.contains("sun")){
dayIndex = DayOfTheWeek(date);
strDate = new SimpleDateFormat("dd-MM-yyyy").format(today.getTime() + TimeUnit.DAYS.toMillis(dayIndex));
}
else throw new IllegalValueException(INVALID_FORMAT);
return ConcatDateTime(strDate,date);
}
private static String ConcatDateTime(String strDate, String date) throws IllegalValueException {
String[] timeparts = date.split(" ");
String part1 = strDate;
String part2 = strDate;
if (timeparts.length != 1) {
part2 = timeparts[1];
if(timeparts.length== 3){
String part3 = timeparts [2];
part2 = part2.concat(" " + part3);}
part2 = strDate.concat(" " + part2);}
else throw new IllegalValueException(INVALID_TIME);
return part2;
}
public static int DayOfTheWeek(String date){
int dayindex = 0;
int diff = 0;
int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
if(date.contains("mon"))
dayindex = Calendar.MONDAY;
else if(date.contains("tue"))
dayindex = Calendar.TUESDAY;
else if(date.contains("wed"))
dayindex = Calendar.WEDNESDAY;
else if(date.contains("thu"))
dayindex = Calendar.THURSDAY;
else if(date.contains("fri"))
dayindex = Calendar.FRIDAY;
else if(date.contains("sat"))
dayindex = Calendar.SATURDAY;
else if(date.contains("sun"))
dayindex = Calendar.SUNDAY;
return diff = (today > dayindex) ? (7 - (today - dayindex)) : (dayindex - today);
}
public static Date DueDateConvert(String date) throws IllegalValueException {
if (date.contains("today")||date.contains("tomorrow")||date.contains("mon")||date.contains("tue")||date.contains("wed")||date.contains("thu")||date.contains("fri")||date.contains("sat")||date.contains("sun")) { // allow user to key in "today" instead of today's date
if(date.split(" ").length ==1){
date=date.concat(" 2359");}
date = FixedTime(date);
}
Date taskDate = parseDateTime(date);
return taskDate;
}
public static Date FixedDateConvert(String date) throws IllegalValueException {
if (date.contains("today")||date.contains("tomorrow")||date.contains("mon")||date.contains("tue")||date.contains("wed")||date.contains("thu")||date.contains("fri")||date.contains("sat")||date.contains("sun")) { // allow user to key in "today" instead of today's date
date = FixedTime(date);
}
Date taskDate = parseDateTime(date);
return taskDate;
}
public static Calendar EndDateTime(Date date) throws IllegalValueException {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 1);
return cal;
}
//these following methods used only for testing purposes only.
/**
* Convert a given calendar object into a string format
*
* @param string
* ""
* @return tomorrow in valid date format
*/
public String outputDateTimeAsString (Calendar dateTime, String format) {
assert (isValidFormat(format));
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(dateTime.getTime());
}
//@@author A0125680H
/**
* Checks whether the format entered will be accepted by LifeKeeper
* @param format
* @return boolean indicating whether format is accepted.
*/
public boolean isValidFormat (String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
for (SimpleDateFormat a : DATE_FORMATS) {
if (a.equals(formatter)) {
return true;
}
} return false;
}
public static boolean recurValidDate(String date) {
Date validDate;
for (SimpleDateFormat sdf : TIME_FORMATS) {
try {
validDate = sdf.parse(date);
if (date.equals(sdf.format(validDate))) {
return true;
}
} catch (ParseException e) {
continue;
}
}
return false;
}
} |
package wasdev.sample.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import com.ibm.watson.developer_cloud.language_translation.v2.model.*;
import com.ibm.watson.developer_cloud.language_translation.v2.*;
import com.ibm.watson.developer_cloud.conversation.v1.*;
import com.ibm.watson.developer_cloud.conversation.v1.model.*;
import com.ibm.watson.developer_cloud.conversation.v1_experimental.model.*;
import com.ibm.watson.developer_cloud.conversation.v1.ConversationService;
/**
* Servlet implementation class SimpleServlet
*/
@WebServlet("/SimpleServlet")
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getTranslatedResult();
//response.setContentType("text/html");
//response.getWriter().print("result is " + result.toString());
//System.out.println("result is " + result);
response.setContentType("application/json");
response.getWriter().print("V17 Dian Dian " + result.toString());
}
private static LanguageTranslation service = new LanguageTranslation();
private static TranslationResult result;
public static void getTranslatedResult() {
//System.getenv("VCAP_SERVICES");
//service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz");
service.setEndPoint("https://gateway.watsonplatform.net/language-translator/api");
service.setUsernameAndPassword("d02a80d2-fb2a-4941-9d74-7ed0e72541c4", "i6YdoXRKCWEz");
result = service.translate("This is English good morning!", Language.ENGLISH, Language.SPANISH).execute();
}
/*private static ConversationService service = new ConversationService("2016-09-30");
public static void main(String[] args) {
service
}*/
} |
package fr.lip6.jkernelmachines.example;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import fr.lip6.jkernelmachines.classifier.DoubleSAG;
import fr.lip6.jkernelmachines.evaluation.ApEvaluator;
import fr.lip6.jkernelmachines.io.FvecImporter;
import fr.lip6.jkernelmachines.type.TrainingSample;
/**
* @author picard
*
*/
public class VOCExample {
/**
* @param args
*/
public static void main(String[] args) {
if(args.length < 4) {
System.out.println("usage: VOCExample trainfile.voc trainfile.fvec testfile.voc testfile.fvec");
return;
}
FvecImporter fvecimp = new FvecImporter();
// read train features
List<double[]> feat = null;
try {
feat = fvecimp.readFile(args[1]);
} catch (IOException e1) {
System.out.println("Unable to read train features: "+args[1]);
return;
}
// read voc train file
List<TrainingSample<double[]>> train = new ArrayList<TrainingSample<double[]>>();
try {
LineNumberReader lin = new LineNumberReader(new FileReader(args[0]));
String line;
int i = 0;
while((line = lin.readLine()) != null) {
//get label from second field. ex: "000012 -1"
int label = Integer.parseInt(line.split("[ ]+")[1]);
train.add(new TrainingSample<double[]>(feat.get(i), label));
i++;
}
lin.close();
} catch (FileNotFoundException e) {
System.out.println("trainfile.voc : "+args[0]+" was not found.");
return;
} catch (IOException e) {
System.out.println("Error while parsing trainfile.voc : "+args[0]);
return;
}
System.out.println("Train features loaded.");
// load test features
try {
feat = fvecimp.readFile(args[3]);
} catch (IOException e1) {
System.out.println("Unable to read test features: "+args[3]);
return;
}
// read voc test file
List<TrainingSample<double[]>> test = new ArrayList<TrainingSample<double[]>>();
try {
LineNumberReader lin = new LineNumberReader(new FileReader(args[2]));
String line;
int i = 0;
while((line = lin.readLine()) != null) {
//get label from second field. ex: "000012 -1"
int label = Integer.parseInt(line.split("[ ]+")[1]);
test.add(new TrainingSample<double[]>(feat.get(i), label));
i++;
}
lin.close();
} catch (FileNotFoundException e) {
System.out.println("trainfile.voc : "+args[2]+" was not found.");
return;
} catch (IOException e) {
System.out.println("Error while parsing trainfile.voc : "+args[2]);
return;
}
System.out.println("Test features loaded.");
//classifier
DoubleSAG svm = new DoubleSAG();
svm.setE(10);
// AP evaluation
ApEvaluator<double[]> ape = new ApEvaluator<double[]>(svm, train, test);
System.out.println("training...");
ape.evaluate();
System.out.println("AP: "+ape.getScore());
}
} |
package org.voltdb;
import org.voltdb.catalog.Procedure;
import com.google.common.collect.ImmutableMap;
/**
* Lists built-in system stored procedures with metadata
*/
public class SystemProcedureCatalog {
// Historical note:
// We used to list syprocs in the catalog (inserting them in
// VoltCompiler). That adds unnecessary content to catalogs,
// couples catalogs to versions (an old catalog wouldn't be able
// to invoke a new sysprocs), and complicates the idea of
// commercial-only sysprocs.
// Now we maintain this list here in code. This is also not
// roses - as ProcedureWrapper really wants catalog.Procedures
// and ClientInterface has to check two lists at dispatch
// time.
/* Data about each registered procedure */
public static class Config {
public final String className;
public final boolean readOnly;
public final boolean singlePartition;
public final boolean everySite;
public final boolean commercial;
// whether this procedure will terminate replication
public final boolean terminatesReplication;
// whether this procedure should be skipped in replication
public final boolean skipReplication;
// whether normal clients can call this sysproc in secondary
public final boolean allowedInReplica;
public Config(String className,
boolean singlePartition,
boolean readOnly,
boolean everySite,
boolean commercial,
boolean terminatesReplication,
boolean skipReplication,
boolean allowedInReplica)
{
this.className = className;
this.singlePartition = singlePartition;
this.readOnly = readOnly;
this.everySite = everySite;
this.commercial = commercial;
this.terminatesReplication = terminatesReplication;
this.skipReplication = skipReplication;
this.allowedInReplica = allowedInReplica;
}
public boolean getEverysite() {
return everySite;
}
public boolean getReadonly() {
return readOnly;
}
public boolean getSinglepartition() {
return singlePartition;
}
public String getClassname() {
return className;
}
Procedure asCatalogProcedure() {
Procedure p = new Procedure();
p.setClassname(className);
p.setSinglepartition(singlePartition);
p.setReadonly(readOnly);
p.setEverysite(everySite);
p.setSystemproc(true);
p.setDefaultproc(false);
p.setHasjava(true);
p.setPartitiontable(null);
p.setPartitioncolumn(null);
p.setPartitionparameter(0);
return p;
}
}
public static final ImmutableMap<String, Config> listing;
static { // SP RO Every Pro (DR: kill, skip, replica-ok)
ImmutableMap.Builder<String, Config> builder = ImmutableMap.builder();
builder.put("@AdHoc_RW_MP", new Config("org.voltdb.sysprocs.AdHoc_RW_MP", false, false, false, false, false, false, true));
builder.put("@AdHoc_RW_SP", new Config("org.voltdb.sysprocs.AdHoc_RW_SP", true, false, false, false, false, false, true));
builder.put("@AdHoc_RO_MP", new Config("org.voltdb.sysprocs.AdHoc_RO_MP", false, true, false, false, false, false, true));
builder.put("@AdHoc_RO_SP", new Config("org.voltdb.sysprocs.AdHoc_RO_SP", true, true, false, false, false, false, true));
builder.put("@Pause", new Config("org.voltdb.sysprocs.Pause", false, false, true, false, false, true, true));
builder.put("@Resume", new Config("org.voltdb.sysprocs.Resume", false, false, true, false, false, true, true));
builder.put("@Quiesce", new Config("org.voltdb.sysprocs.Quiesce", false, false, false, false, false, true, true));
builder.put("@SnapshotSave", new Config("org.voltdb.sysprocs.SnapshotSave", false, false, false, false, false, true, true));
builder.put("@SnapshotRestore", new Config("org.voltdb.sysprocs.SnapshotRestore", false, false, false, false, true, true, false));
builder.put("@SnapshotStatus", new Config("org.voltdb.sysprocs.SnapshotStatus", false, false, false, false, false, true, true));
builder.put("@SnapshotScan", new Config("org.voltdb.sysprocs.SnapshotScan", false, false, false, false, false, true, true));
builder.put("@SnapshotDelete", new Config("org.voltdb.sysprocs.SnapshotDelete", false, false, false, false, false, true, true));
builder.put("@Shutdown", new Config("org.voltdb.sysprocs.Shutdown", false, false, false, false, false, true, true));
builder.put("@ProfCtl", new Config("org.voltdb.sysprocs.ProfCtl", false, false, true, false, false, true, true));
builder.put("@Statistics", new Config("org.voltdb.sysprocs.Statistics", false, true, false, false, false, true, true));
builder.put("@SystemCatalog", new Config("org.voltdb.sysprocs.SystemCatalog", true, true, false, false, false, true, true));
builder.put("@SystemInformation", new Config("org.voltdb.sysprocs.SystemInformation", false, true, false, false, false, true, true));
builder.put("@UpdateLogging", new Config("org.voltdb.sysprocs.UpdateLogging", false, false, true, false, false, true, true));
builder.put("@BalancePartitions", new Config("org.voltdb.sysprocs.BalancePartitions", false, false, false, true, true, true, false));
builder.put("@UpdateApplicationCatalog",new Config("org.voltdb.sysprocs.UpdateApplicationCatalog", false, false, false, false, false, false, false));
builder.put("@LoadMultipartitionTable", new Config("org.voltdb.sysprocs.LoadMultipartitionTable", false, false, false, false, false, false, false));
builder.put("@LoadSinglepartitionTable",new Config("org.voltdb.sysprocs.LoadSinglepartitionTable", true, false, false, false, false, false, false));
builder.put("@Promote", new Config("org.voltdb.sysprocs.Promote", false, false, true, false, false, true, true));
listing = builder.build();
}
} |
package henfredemars;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Calendar;
import java.util.List;
import java.util.zip.GZIPOutputStream;
//Parse and compile data samples into a single file
//Input files must be in text form (i.e. not compressed)
public class DataCompiler {
public static void main(String[] args) {
File directory = new File(args[0]);
File outputFile = new File(args[1]);
File[] files = directory.listFiles();
long numberOfGoodRecords = 0;
long numberOfBadRecords = 0;
long totalNumberOfRecords = 0;
long filesProcessed = 0;
//Prepare output file
FileOutputStream fOutStream = null;
GZIPOutputStream goos = null;
ObjectOutputStream oos = null;
try {
fOutStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
System.out.println("DataCompiler - error writing file");
e1.printStackTrace();
}
try {
goos = new GZIPOutputStream(fOutStream);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
oos = new ObjectOutputStream(goos);
} catch (IOException e1) {
System.out.println("DataCompiler - error writing file");
e1.printStackTrace();
}
//Process files
for (File file: files) {
filesProcessed++;
System.out.println("Processing file: " + file.getName());
List<String> lines = null;
try {
lines = Files.readAllLines(file.toPath(),StandardCharsets.UTF_8);
} catch (IOException e) {
System.out.println("DataCompiler - failed to read file lines");
e.printStackTrace();
}
for (String line: lines) {
if (line.contains("WBAN")) {
continue;
}
totalNumberOfRecords++;
DataSample ds = new DataSample();
String[] elements = line.split(" +");
ds.setStationId(elements[0]);
Calendar date = Calendar.getInstance();
String dateStr = elements[2];
date.set(Calendar.YEAR, Integer.valueOf(dateStr.substring(0,4)));
date.set(Calendar.MONTH, Integer.valueOf(dateStr.substring(4,6))-1);
date.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dateStr.substring(6,8)));
date.set(Calendar.HOUR_OF_DAY, Integer.valueOf(dateStr.substring(8,10)));
date.set(Calendar.MINUTE, Integer.valueOf(dateStr.substring(10,12)));
ds.setDate(date);
try {
ds.setRainfall(Float.valueOf(elements[28]));
} catch (NumberFormatException e) {
ds.setRainfall(0f);
}
try {
ds.setTemperature(Float.valueOf(elements[21]));
ds.setHumidity(Float.valueOf(elements[22]));
ds.setPressure(Float.valueOf(elements[24]));
} catch (NumberFormatException e) {
numberOfBadRecords++;
if (totalNumberOfRecords % 100000!=0) continue;
System.out.println("Line missing required data.");
System.out.println(line);
continue; //Bad measurement
}
if (ds.checkSample()==DataStatus.ALL_GOOD) {
try {
numberOfGoodRecords++;
oos.writeObject(ds);
} catch (IOException e) {
System.out.println("DataCompiler - error writing object");
e.printStackTrace();
}
} else {
numberOfBadRecords++;
if (totalNumberOfRecords % 100000!=0) continue;
System.out.println("Bad measurement discarded DS: " + ds.checkSample());
}
}
if (filesProcessed%100==0) {
System.out.println("GoodRecords: " + numberOfGoodRecords);
System.out.println("BadRecords: " + numberOfBadRecords);
System.out.println("TotalRecords: " + totalNumberOfRecords);
System.out.println("FilesProcessed: " + filesProcessed);
}
}
System.out.println("GoodRecords: " + numberOfGoodRecords);
System.out.println("BadRecords: " + numberOfBadRecords);
System.out.println("TotalRecords: " + totalNumberOfRecords);
System.out.println("FilesProcessed: " + filesProcessed);
try {
oos.close();
} catch (IOException e) {
//Do nothing
}
}
} |
package org.voltdb.iv2;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import jsr166y.LinkedTransferQueue;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.VoltMessage;
import com.google.common.base.Throwables;
/**
* InitiatorMailbox accepts initiator work and proxies it to the
* configured InitiationRole.
*/
public class MpInitiatorMailbox extends InitiatorMailbox
{
VoltLogger hostLog = new VoltLogger("HOST");
VoltLogger tmLog = new VoltLogger("TM");
private final LinkedTransferQueue<Runnable> m_taskQueue = new LinkedTransferQueue<Runnable>();
@SuppressWarnings("serial")
private static class TerminateThreadException extends RuntimeException {};
private final Thread m_taskThread = new Thread(null,
new Runnable() {
@Override
public void run() {
while (true) {
try {
m_taskQueue.take().run();
} catch (TerminateThreadException e) {
break;
} catch (Exception e) {
tmLog.error("Unexpected exception in MpInitiator deliver thread", e);
}
}
}
},
"MpInitiator deliver", 1024 * 128);
@Override
public void setRepairAlgo(final RepairAlgo algo)
{
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
setRepairAlgoInternal(algo);
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
@Override
public void setLeaderState(final long maxSeenTxnId)
{
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
setLeaderStateInternal(maxSeenTxnId);
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
@Override
public void setMaxLastSeenMultipartTxnId(final long txnId) {
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
setMaxLastSeenMultipartTxnIdInternal(txnId);
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
@Override
public void setMaxLastSeenTxnId(final long txnId) {
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
setMaxLastSeenTxnIdInternal(txnId);
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
@Override
public void enableWritingIv2FaultLog() {
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
enableWritingIv2FaultLogInternal();
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
public MpInitiatorMailbox(int partitionId,
Scheduler scheduler,
HostMessenger messenger, RepairLog repairLog,
RejoinProducer rejoinProducer)
{
super(partitionId, scheduler, messenger, repairLog, rejoinProducer);
m_taskThread.start();
}
@Override
public void shutdown() throws InterruptedException {
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
shutdownInternal();
} catch (InterruptedException e) {
tmLog.info("Interrupted during shutdown", e);
}
}
});
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
throw new TerminateThreadException();
}
});
m_taskThread.join();
}
@Override
public void updateReplicas(final List<Long> replicas) {
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
updateReplicasInternal(replicas);
}
});
}
@Override
public void deliver(final VoltMessage message) {
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
deliverInternal(message);
}
});
}
@Override
void repairReplicasWith(final List<Long> needsRepair, final VoltMessage repairWork)
{
final CountDownLatch cdl = new CountDownLatch(1);
m_taskQueue.offer(new Runnable() {
@Override
public void run() {
try {
repairReplicasWithInternal( needsRepair, repairWork);
} finally {
cdl.countDown();
}
}
});
try {
cdl.await();
} catch (InterruptedException e) {
Throwables.propagate(e);
}
}
} |
package org.voltdb.iv2;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.messaging.TransactionInfoBaseMessage;
import org.voltcore.utils.CoreUtils;
import org.voltdb.messaging.DumpMessage;
import org.voltdb.SiteProcedureConnection;
import org.voltdb.StoredProcedureInvocation;
import org.voltdb.VoltTable;
import org.voltdb.client.ProcedureInvocationType;
import org.voltdb.dtxn.TransactionState;
import org.voltdb.messaging.BorrowTaskMessage;
import org.voltdb.messaging.FragmentResponseMessage;
import org.voltdb.messaging.FragmentTaskMessage;
import org.voltdb.messaging.Iv2InitiateTaskMessage;
import org.voltdb.utils.VoltTableUtil;
public class MpTransactionState extends TransactionState
{
static VoltLogger tmLog = new VoltLogger("TM");
/**
* This is thrown by the TransactionState instance when something
* goes wrong mid-fragment, and execution needs to back all the way
* out to the stored procedure call.
*/
// IZZY Consolidate me with MultiPartitionParticipantTransactionState
// and perhaps make me more descriptive
public static class FragmentFailureException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
final Iv2InitiateTaskMessage m_task;
LinkedBlockingDeque<FragmentResponseMessage> m_newDeps =
new LinkedBlockingDeque<FragmentResponseMessage>();
Map<Integer, Set<Long>> m_remoteDeps;
Map<Integer, List<VoltTable>> m_remoteDepTables =
new HashMap<Integer, List<VoltTable>>();
final List<Long> m_useHSIds = new ArrayList<Long>();
long m_buddyHSId;
FragmentTaskMessage m_remoteWork = null;
FragmentTaskMessage m_localWork = null;
boolean m_haveDistributedInitTask = false;
boolean m_isRestart = false;
MpTransactionState(Mailbox mailbox,
TransactionInfoBaseMessage notice,
List<Long> useHSIds, long buddyHSId, boolean isRestart)
{
super(mailbox, notice);
m_task = (Iv2InitiateTaskMessage)notice;
m_useHSIds.addAll(useHSIds);
m_buddyHSId = buddyHSId;
m_isRestart = isRestart;
}
public void updateMasters(List<Long> masters)
{
m_useHSIds.clear();
m_useHSIds.addAll(masters);
}
/**
* Used to reset the internal state of this transaction so it can be successfully restarted
*/
void restart()
{
// The poisoning path will, unfortunately, set this to true. Need to undo that.
m_needsRollback = false;
// Also need to make sure that we get the original invocation in the first fragment
// since some masters may not have seen it.
m_haveDistributedInitTask = false;
m_isRestart = true;
}
@Override
public boolean isSinglePartition()
{
return false;
}
@Override
public boolean isCoordinator()
{
return true;
}
@Override
public boolean isBlocked()
{
// Not clear this method is useful in the new world?
return false;
}
@Override
public boolean hasTransactionalWork()
{
return false;
}
@Override
public boolean doWork(boolean recovering)
{
return false;
}
@Override
public StoredProcedureInvocation getInvocation()
{
return m_task.getStoredProcedureInvocation();
}
@Override
public void handleSiteFaults(HashSet<Long> failedSites)
{
}
// Overrides needed by MpProcedureRunner
@Override
public void setupProcedureResume(boolean isFinal, int[] dependencies)
{
// Reset state so we can run this batch cleanly
m_localWork = null;
m_remoteWork = null;
m_remoteDeps = null;
m_remoteDepTables.clear();
}
// I met this List at bandcamp...
public void setupProcedureResume(boolean isFinal, List<Integer> deps)
{
setupProcedureResume(isFinal,
com.google.common.primitives.Ints.toArray(deps));
}
@Override
public void createLocalFragmentWork(FragmentTaskMessage task, boolean nonTransactional)
{
m_localWork = task;
m_localWork.setTruncationHandle(m_task.getTruncationHandle());
}
@Override
public void createAllParticipatingFragmentWork(FragmentTaskMessage task)
{
// Don't generate remote work or dependency tracking or anything if
// there are no fragments to be done in this message
// At some point maybe ProcedureRunner.slowPath() can get smarter
if (task.getFragmentCount() > 0) {
// Distribute the initiate task for command log replay.
// Command log must log the initiate task;
// Only send the fragment once.
if (!m_haveDistributedInitTask && !isForReplay() && !isReadOnly()) {
m_haveDistributedInitTask = true;
task.setInitiateTask((Iv2InitiateTaskMessage)getNotice());
}
if (m_task.getStoredProcedureInvocation().getType() == ProcedureInvocationType.REPLICATED) {
task.setOriginalTxnId(m_task.getStoredProcedureInvocation().getOriginalTxnId());
}
m_remoteWork = task;
m_remoteWork.setTruncationHandle(m_task.getTruncationHandle());
// Distribute fragments to remote destinations.
long[] non_local_hsids = new long[m_useHSIds.size()];
for (int i = 0; i < m_useHSIds.size(); i++) {
non_local_hsids[i] = m_useHSIds.get(i);
}
// send to all non-local sites
if (non_local_hsids.length > 0) {
m_mbox.send(non_local_hsids, m_remoteWork);
}
}
else {
m_remoteWork = null;
}
}
private Map<Integer, Set<Long>>
createTrackedDependenciesFromTask(FragmentTaskMessage task,
List<Long> expectedHSIds)
{
Map<Integer, Set<Long>> depMap = new HashMap<Integer, Set<Long>>();
for (int i = 0; i < task.getFragmentCount(); i++) {
int dep = task.getOutputDepId(i);
Set<Long> scoreboard = new HashSet<Long>();
depMap.put(dep, scoreboard);
for (long hsid : expectedHSIds) {
scoreboard.add(hsid);
}
}
return depMap;
}
@Override
public Map<Integer, List<VoltTable>> recursableRun(SiteProcedureConnection siteConnection)
{
// if we're restarting this transaction, and we only have local work, add some dummy
// remote work so that we can avoid injecting a borrow task into the local buddy site
// before the CompleteTransactionMessage with the restart flag reaches it.
// Right now, any read on a replicated table which has no distributed work will
// generate these null fragments in the restarted transaction.
boolean usedNullFragment = false;
if (m_isRestart && m_remoteWork == null) {
usedNullFragment = true;
m_remoteWork = new FragmentTaskMessage(m_localWork.getInitiatorHSId(),
m_localWork.getCoordinatorHSId(),
m_localWork.getTxnId(),
m_localWork.getUniqueId(),
m_localWork.isReadOnly(),
false,
false);
m_remoteWork.setEmptyForRestart(getNextDependencyId());
if (!m_haveDistributedInitTask && !isForReplay() && !isReadOnly()) {
m_haveDistributedInitTask = true;
m_remoteWork.setInitiateTask((Iv2InitiateTaskMessage)getNotice());
}
// Distribute fragments to remote destinations.
long[] non_local_hsids = new long[m_useHSIds.size()];
for (int i = 0; i < m_useHSIds.size(); i++) {
non_local_hsids[i] = m_useHSIds.get(i);
}
// send to all non-local sites
if (non_local_hsids.length > 0) {
m_mbox.send(non_local_hsids, m_remoteWork);
}
}
// Do distributed fragments, if any
if (m_remoteWork != null) {
// Create some record of expected dependencies for tracking
m_remoteDeps = createTrackedDependenciesFromTask(m_remoteWork,
m_useHSIds);
// if there are remote deps, block on them
// FragmentResponses indicating failure will throw an exception
// which will propagate out of handleReceivedFragResponse and
// cause ProcedureRunner to do the right thing and cause rollback.
while (!checkDoneReceivingFragResponses()) {
FragmentResponseMessage msg = pollForResponses();
handleReceivedFragResponse(msg);
}
}
// satisified. Clear this defensively. Procedure runner is sloppy with
// cleaning up if it decides new work is necessary that is local-only.
m_remoteWork = null;
BorrowTaskMessage borrowmsg = new BorrowTaskMessage(m_localWork);
m_localWork.m_sourceHSId = m_mbox.getHSId();
// if we created a bogus fragment to distribute to serialize restart and borrow tasks,
// don't include the empty dependencies we got back in the borrow fragment.
if (!usedNullFragment) {
borrowmsg.addInputDepMap(m_remoteDepTables);
}
m_mbox.send(m_buddyHSId, borrowmsg);
FragmentResponseMessage msg = pollForResponses();
m_localWork = null;
// Build results from the FragmentResponseMessage
// This is similar to dependency tracking...maybe some
// sane way to merge it
Map<Integer, List<VoltTable>> results =
new HashMap<Integer, List<VoltTable>>();
for (int i = 0; i < msg.getTableCount(); i++) {
int this_depId = msg.getTableDependencyIdAtIndex(i);
VoltTable this_dep = msg.getTableAtIndex(i);
List<VoltTable> tables = results.get(this_depId);
if (tables == null) {
tables = new ArrayList<VoltTable>();
results.put(this_depId, tables);
}
tables.add(this_dep);
}
// Need some sanity check that we got all of the expected output dependencies?
return results;
}
private FragmentResponseMessage pollForResponses()
{
FragmentResponseMessage msg = null;
try {
while (msg == null) {
msg = m_newDeps.poll(60L * 5, TimeUnit.SECONDS);
if (msg == null) {
tmLog.warn("Possible multipartition transaction deadlock detected for: " + m_task);
if (m_remoteWork == null) {
tmLog.warn("Waiting on local BorrowTask response from site: " +
CoreUtils.hsIdToString(m_buddyHSId));
}
else {
tmLog.warn("Waiting on remote dependencies: ");
for (Entry<Integer, Set<Long>> e : m_remoteDeps.entrySet()) {
tmLog.warn("Dep ID: " + e.getKey() + " waiting on: " +
CoreUtils.hsIdCollectionToString(e.getValue()));
}
}
m_mbox.send(com.google.common.primitives.Longs.toArray(m_useHSIds), new DumpMessage());
}
}
}
catch (InterruptedException e) {
// can't leave yet - the transaction is inconsistent.
// could retry; but this is unexpected. Crash.
throw new RuntimeException(e);
}
if (msg.getStatusCode() != FragmentResponseMessage.SUCCESS) {
m_needsRollback = true;
if (msg.getException() != null) {
throw msg.getException();
} else {
throw new FragmentFailureException();
}
}
return msg;
}
private void trackDependency(long hsid, int depId, VoltTable table)
{
// Remove the distributed fragment for this site from remoteDeps
// for the dependency Id depId.
Set<Long> localRemotes = m_remoteDeps.get(depId);
if (localRemotes == null && m_isRestart) {
// Tolerate weird deps showing up on restart
// After Ariel separates unique ID from transaction ID, rewrite restart to restart with
// a new transaction ID and make this and the fake distributed fragment stuff go away.
return;
}
Object needed = localRemotes.remove(hsid);
if (needed != null) {
// add table to storage
List<VoltTable> tables = m_remoteDepTables.get(depId);
if (tables == null) {
tables = new ArrayList<VoltTable>();
m_remoteDepTables.put(depId, tables);
}
// null dependency table is from a joining node, has no content, drop it
if (table.getStatusCode() != VoltTableUtil.NULL_DEPENDENCY_STATUS) {
tables.add(table);
}
}
else {
System.out.println("No remote dep for local site: " + hsid);
}
}
private void handleReceivedFragResponse(FragmentResponseMessage msg)
{
for (int i = 0; i < msg.getTableCount(); i++)
{
int this_depId = msg.getTableDependencyIdAtIndex(i);
VoltTable this_dep = msg.getTableAtIndex(i);
long src_hsid = msg.getExecutorSiteId();
trackDependency(src_hsid, this_depId, this_dep);
}
}
private boolean checkDoneReceivingFragResponses()
{
boolean done = true;
for (Set<Long> depid : m_remoteDeps.values()) {
if (depid.size() != 0) {
done = false;
}
}
return done;
}
// Runs from Mailbox's network thread
public void offerReceivedFragmentResponse(FragmentResponseMessage message)
{
// push into threadsafe queue
m_newDeps.offer(message);
}
/**
* Kill a transaction - maybe shutdown mid-transaction? Or a timeout
* collecting fragments? This is a don't-know-what-to-do-yet
* stub.
* TODO: fix this.
*/
void terminateTransaction()
{
throw new RuntimeException("terminateTransaction is not yet implemented.");
}
} |
package org.bimserver.shared.json;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.activation.DataHandler;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.bimserver.plugins.serializers.CacheStoringEmfSerializerDataSource;
import org.bimserver.plugins.serializers.SerializerException;
import org.bimserver.shared.meta.SBase;
import org.bimserver.shared.meta.SClass;
import org.bimserver.shared.meta.SField;
import org.bimserver.shared.meta.SServicesMap;
import org.bimserver.utils.ByteArrayDataSource;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.DoubleNode;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import com.google.common.base.Charsets;
public class JsonConverter {
private final SServicesMap servicesMap;
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public JsonConverter(SServicesMap servicesMap) {
this.servicesMap = servicesMap;
}
// public void toJson(Object object, ObjectMapper objectMapper) throws IOException, SerializerException {
// if (object instanceof SBase) {
// SBase base = (SBase) object;
// out.beginObject();
// out.name("__type");
// out.value(base.getSClass().getSimpleName());
// for (SField field : base.getSClass().getAllFields()) {
// out.name(field.getName());
// toJson(base.sGet(field), out);
// out.endObject();
// } else if (object instanceof Collection) {
// Collection<?> collection = (Collection<?>) object;
// out.beginArray();
// for (Object value : collection) {
// toJson(value, out);
// out.endArray();
// } else if (object instanceof Date) {
// out.value(((Date) object).getTime());
// } else if (object instanceof DataHandler) {
// DataHandler dataHandler = (DataHandler) object;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// if (dataHandler.getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
// CacheStoringEmfSerializerDataSource cacheStoringEmfSerializerDataSource = (CacheStoringEmfSerializerDataSource) dataHandler.getDataSource();
// cacheStoringEmfSerializerDataSource.writeToOutputStream(baos, null);
// out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
// } else {
// InputStream inputStream = dataHandler.getInputStream();
// IOUtils.copy(inputStream, baos);
// out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
// } else if (object instanceof byte[]) {
// byte[] data = (byte[]) object;
// out.value(new String(Base64.encodeBase64(data), Charsets.UTF_8));
// } else if (object instanceof String) {
// out.value((String) object);
// } else if (object instanceof Number) {
// out.value((Number) object);
// } else if (object instanceof Enum) {
// out.value(object.toString());
// } else if (object instanceof Boolean) {
// out.value((Boolean) object);
// } else if (object == null) {
// out.nullValue();
// } else {
// throw new UnsupportedOperationException(object.toString());
public JsonNode toJson(Object object) throws IOException {
if (object instanceof SBase) {
SBase base = (SBase) object;
ObjectNode jsonObject = OBJECT_MAPPER.createObjectNode();
jsonObject.put("__type", base.getSClass().getSimpleName());
for (SField field : base.getSClass().getOwnFields()) {
jsonObject.set(field.getName(), toJson(base.sGet(field)));
}
return jsonObject;
} else if (object instanceof Collection) {
Collection<?> collection = (Collection<?>) object;
ArrayNode jsonArray = OBJECT_MAPPER.createArrayNode();
for (Object value : collection) {
jsonArray.add(toJson(value));
}
return jsonArray;
} else if (object instanceof Date) {
return new LongNode(((Date) object).getTime());
} else if (object instanceof DataHandler) {
DataHandler dataHandler = (DataHandler) object;
InputStream inputStream = dataHandler.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(inputStream, out);
return new TextNode(new String(Base64.encodeBase64(out.toByteArray()), Charsets.UTF_8));
} else if (object instanceof Boolean) {
return BooleanNode.valueOf((Boolean) object);
} else if (object instanceof String) {
return new TextNode((String) object);
} else if (object instanceof Long) {
return new LongNode((Long) object);
} else if (object instanceof Integer) {
return new IntNode((Integer) object);
} else if (object instanceof Double) {
return new DoubleNode((Double) object);
} else if (object instanceof Enum) {
return new TextNode(object.toString());
} else if (object == null) {
return NullNode.getInstance();
} else if (object instanceof byte[]) {
byte[] data = (byte[]) object;
return new TextNode(new String(Base64.encodeBase64(data), Charsets.UTF_8));
}
throw new UnsupportedOperationException(object.getClass().getName());
}
public Object fromJson(SClass definedType, SClass genericType, Object object) throws ConvertException, IOException {
try {
if (object instanceof ObjectNode) {
ObjectNode jsonObject = (ObjectNode) object;
if (jsonObject.has("__type")) {
String type = jsonObject.get("__type").asText();
SClass sClass = servicesMap.getType(type);
if (sClass == null) {
throw new ConvertException("Unknown type: " + type);
}
SBase newObject = sClass.newInstance();
for (SField field : newObject.getSClass().getAllFields()) {
if (jsonObject.has(field.getName())) {
newObject.sSet(field, fromJson(field.getType(), field.getGenericType(), jsonObject.get(field.getName())));
}
}
return newObject;
} else {
Iterator<String> fieldNames = jsonObject.fieldNames();
int nrFields = 0;
while (fieldNames.hasNext()) {
nrFields++;
fieldNames.next();
}
if (nrFields != 0) {
throw new ConvertException("Missing __type field in " + jsonObject.toString());
} else {
return null;
}
}
} else if (object instanceof ArrayNode) {
ArrayNode array = (ArrayNode) object;
if (definedType.isList()) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.size(); i++) {
list.add(fromJson(definedType, genericType, array.get(i)));
}
return list;
} else if (definedType.isSet()) {
Set<Object> set = new HashSet<Object>();
for (int i = 0; i < array.size(); i++) {
set.add(fromJson(definedType, genericType, array.get(i)));
}
return set;
}
} else if (object instanceof NullNode) {
return null;
} else if (definedType.isByteArray()) {
if (object instanceof ValueNode) {
ValueNode jsonPrimitive = (ValueNode) object;
return Base64.decodeBase64(jsonPrimitive.asText().getBytes(Charsets.UTF_8));
}
} else if (definedType.isDataHandler()) {
if (object instanceof ValueNode) {
ValueNode jsonPrimitive = (ValueNode) object;
byte[] data = Base64.decodeBase64(jsonPrimitive.asText().getBytes(Charsets.UTF_8));
return new DataHandler(new ByteArrayDataSource(null, data));
}
} else if (definedType.isInteger()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asInt();
}
} else if (definedType.isLong()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asLong();
}
} else if (definedType.isShort()) {
if (object instanceof ValueNode) {
return (short)((ValueNode) object).asInt();
}
} else if (definedType.isEnum()) {
ValueNode primitive = (ValueNode) object;
for (Object enumConstantObject : definedType.getInstanceClass().getEnumConstants()) {
Enum<?> enumConstant = (Enum<?>) enumConstantObject;
if (enumConstant.name().equals(primitive.asText())) {
return enumConstant;
}
}
} else if (definedType.isDate()) {
if (object instanceof ValueNode) {
return new Date(((ValueNode) object).asLong());
}
} else if (definedType.isString()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asText();
} else if (object instanceof NullNode) {
return null;
}
} else if (definedType.isBoolean()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asBoolean();
}
} else if (definedType.isList()) {
if (genericType.isLong()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asLong();
}
} else if (genericType.isInteger()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asInt();
}
} else if (genericType.isString()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asText();
}
} else if (genericType.isDouble()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asDouble();
}
}
} else if (definedType.isSet()) {
if (genericType.isLong()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asLong();
}
} else if (genericType.isInteger()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asInt();
}
} else if (genericType.isString()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asText();
}
}
} else if (definedType.isDouble()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asDouble();
}
} else if (definedType.isFloat()) {
if (object instanceof ValueNode) {
return ((ValueNode) object).asDouble();
}
} else if (definedType.isVoid()) {
return null;
}
} catch (NumberFormatException e) {
throw new ConvertException(e);
}
throw new UnsupportedOperationException(object.toString());
}
} |
package com.kii.thingif;
public class SDKVersion {
public static final String versionString = "1.0.0";
} |
package gov.nih.nci.rembrandt.web.inbox;
import gov.nih.nci.rembrandt.cache.BusinessTierCache;
import gov.nih.nci.rembrandt.cache.ConvenientCache;
import gov.nih.nci.rembrandt.cache.PresentationTierCache;
import gov.nih.nci.rembrandt.dto.query.CompoundQuery;
import gov.nih.nci.rembrandt.web.factory.ApplicationFactory;
import java.util.Random;
import javax.servlet.http.HttpSession;
import uk.ltd.getahead.dwr.ExecutionContext;
public class QueryInbox {
private HttpSession session;
private BusinessTierCache btc;
private PresentationTierCache ptc;
public QueryInbox() {
//get some common stuff
session = ExecutionContext.get().getSession(false);
btc = ApplicationFactory.getBusinessTierCache();
ptc = ApplicationFactory.getPresentationTierCache();
}
public String checkStatus() {
//simulate that the query is still running, assuming we have only 1 query for testing
//HttpSession session = ExecutionContext.get().getSession(false);
Random r = new Random();
int randInt = Math.abs(r.nextInt()) % 11;
if(randInt % 2 == 0)
return "false";
else
return "true";
}
public String getQueryName() {
String st = "nothing";
try {
st = String.valueOf(ptc.getSessionQueryBag(session.getId()).getQueries().size());
}
catch(Exception e){
st = "no worky";
}
return st;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hatsunearu.physicssim.simulator;
import hatsunearu.physicssim.objectmodels.DraggyBall;
import hatsunearu.physicssim.objectmodels.PhysicalObject;
import java.util.Scanner;
/**
*
* @author hatsunearu
*/
public class PhysicsSim {
static double timeToRun = 10;
static double tickTime = 0.000005;
static double samplingInterval = 0.1;
static double vx,vy,rx,ry,m;
private static Scanner s;
public static void main(String[] args) {
s = new Scanner(System.in);
System.out.println("PhysicsSim, Rev 4.0, written by hatsunearu (www.github.com/hatsunearu)\n");
System.out.println("Input mass of object");
m = s.nextDouble();
System.out.println("Input Horizontal Velocity followed by Vertical Velocity");
vx = s.nextDouble();
vy = s.nextDouble();
System.out.println("Input Horizontal Position followed by Vertical Position");
rx = s.nextDouble();
ry = s.nextDouble();
s.nextLine();
System.out.println("Do you want to define simulation parameters? y/[N]");
if (s.nextLine().equalsIgnoreCase("y")) {
System.out.println("Input time to simulate, tick interval (determines accuracy), and sampling interval (how often you want to take measurements)");
timeToRun = s.nextDouble();
tickTime = s.nextDouble();
samplingInterval = s.nextDouble();
}
PhysicalObject obj = new DraggyBall(m, new Vector(vx, vy), new Vector(rx,ry), tickTime); //define your object here
System.out.println("\nPhysical Parameters: m = " + m+ " v = <"+vx+", "+vy+">" + " r = <"+rx+", "+ry+">");
System.out.println("\nRun Parameters: total time = "+timeToRun+" tick interval = "+tickTime+" sampling interval = "+samplingInterval);
System.out.println("Simulation Object: "+obj.getModelName()+"\n");
System.out.println("Press enter to continue...");
s.nextLine();
System.out.println("Time\tX\tY");
for(long i = 0; i <= (long)(timeToRun / tickTime); i++) {
if(i % (samplingInterval / tickTime) == 0) {
System.out.println(obj.getTime() + "\t" + obj.getPos().getX() + "\t" + obj.getPos().getY());
}
obj.tick();
}
}
} |
package de.lmu.ifi.dbs.elki.workflow;
import java.util.List;
import de.lmu.ifi.dbs.elki.algorithm.Algorithm;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.index.Index;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.logging.LoggingConfiguration;
import de.lmu.ifi.dbs.elki.logging.statistics.Duration;
import de.lmu.ifi.dbs.elki.result.BasicResult;
import de.lmu.ifi.dbs.elki.result.HierarchicalResult;
import de.lmu.ifi.dbs.elki.result.Result;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.Flag;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.ObjectListParameter;
/**
* The "algorithms" step, where data is analyzed.
*
* @author Erich Schubert
*
* @apiviz.has Algorithm
* @apiviz.has Result
* @apiviz.uses Database
*/
public class AlgorithmStep implements WorkflowStep {
/**
* Logger
*/
private static final Logging LOG = Logging.getLogger(AlgorithmStep.class);
/**
* Holds the algorithm to run.
*/
private List<Algorithm> algorithms;
/**
* The algorithm output
*/
private BasicResult result = null;
/**
* Constructor.
*
* @param algorithms
*/
public AlgorithmStep(List<Algorithm> algorithms) {
super();
this.algorithms = algorithms;
}
/**
* Run algorithms.
*
* @param database Database
* @return Algorithm result
*/
public HierarchicalResult runAlgorithms(Database database) {
result = new BasicResult("Algorithm Step", "main");
result.addChildResult(database);
if (LOG.isStatistics() && database.getIndexes().size() > 0) {
LOG.statistics("Index statistics before running algorithms:");
for (Index idx : database.getIndexes()) {
idx.logStatistics();
}
}
for (Algorithm algorithm : algorithms) {
Duration duration = LOG.isStatistics() ? LOG.newDuration(algorithm.getClass().getName()+".runtime") : null;
if (duration != null) {
duration.begin();
}
Result res = algorithm.run(database);
if (duration != null) {
duration.end();
LOG.statistics(duration);
}
if (LOG.isStatistics() && database.getIndexes().size() > 0) {
LOG.statistics("Index statistics after running algorithms:");
for (Index idx : database.getIndexes()) {
idx.logStatistics();
}
}
if (res != null) {
result.addChildResult(res);
}
}
return result;
}
/**
* Get the algorithm result.
*
* @return Algorithm result.
*/
public HierarchicalResult getResult() {
return result;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractParameterizer {
/**
* Enable logging of performance data
*/
protected boolean time = false;
/**
* Holds the algorithm to run.
*/
protected List<Algorithm> algorithms;
/**
* Flag to allow verbose messages while running the application.
* <p>
* Key: {@code -time}
* </p>
*/
public static final OptionID TIME_ID = new OptionID("time", "Enable logging of runtime data. Do not combine with more verbose logging, since verbose logging can significantly impact performance.");
/**
* Parameter to specify the algorithm to run.
* <p>
* Key: {@code -algorithm}
* </p>
*/
public static final OptionID ALGORITHM_ID = new OptionID("algorithm", "Algorithm to run.");
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
// Time parameter
final Flag timeF = new Flag(TIME_ID);
if (config.grab(timeF)) {
time = timeF.getValue();
}
// parameter algorithm
final ObjectListParameter<Algorithm> ALGORITHM_PARAM = new ObjectListParameter<>(ALGORITHM_ID, Algorithm.class);
if (config.grab(ALGORITHM_PARAM)) {
algorithms = ALGORITHM_PARAM.instantiateClasses(config);
}
}
@Override
protected AlgorithmStep makeInstance() {
if (time) {
LoggingConfiguration.setStatistics();
}
return new AlgorithmStep(algorithms);
}
}
} |
package info.guardianproject.otr;
import info.guardianproject.otr.app.im.ImService;
import info.guardianproject.otr.app.im.app.SmpResponseActivity;
import info.guardianproject.otr.app.im.engine.Address;
import info.guardianproject.otr.app.im.engine.Message;
import info.guardianproject.otr.app.im.plugin.xmpp.XmppAddress;
import info.guardianproject.otr.app.im.service.ChatSessionAdapter;
import info.guardianproject.otr.app.im.service.ChatSessionManagerAdapter;
import info.guardianproject.otr.app.im.service.ImConnectionAdapter;
import info.guardianproject.otr.app.im.service.RemoteImService;
import java.io.IOException;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.Date;
import java.util.Hashtable;
import net.java.otr4j.OtrEngineHost;
import net.java.otr4j.OtrKeyManager;
import net.java.otr4j.OtrPolicy;
import net.java.otr4j.session.SessionID;
import android.content.Intent;
import android.widget.Toast;
public class OtrEngineHostImpl implements OtrEngineHost {
private OtrPolicy mPolicy;
private OtrKeyManager mOtrKeyManager;
private ImService mContext;
private Hashtable<SessionID, String> mSessionResources;
private RemoteImService mImService;
public OtrEngineHostImpl(OtrPolicy policy, ImService context, OtrKeyManager otrKeyManager, RemoteImService imService) throws IOException {
mPolicy = policy;
mContext = context;
mSessionResources = new Hashtable<SessionID, String>();
mOtrKeyManager = otrKeyManager;
mImService = imService;
}
public void putSessionResource(SessionID session, String resource) {
mSessionResources.put(session, resource);
}
public void removeSessionResource(SessionID session) {
mSessionResources.remove(session);
}
public Address appendSessionResource(SessionID session, Address to) {
String resource = mSessionResources.get(session);
if (resource != null)
return new XmppAddress(to.getBareAddress() + '/' + resource);
else
return to;
}
public ImConnectionAdapter findConnection(SessionID session) {
return mImService.getConnection(Address.stripResource(session.getLocalUserId()));
}
public OtrKeyManager getKeyManager() {
return mOtrKeyManager;
}
public void storeRemoteKey(SessionID sessionID, PublicKey remoteKey) {
mOtrKeyManager.savePublicKey(sessionID, remoteKey);
}
public boolean isRemoteKeyVerified(SessionID sessionID) {
return mOtrKeyManager.isVerified(sessionID);
}
public String getLocalKeyFingerprint(SessionID sessionID) {
return mOtrKeyManager.getLocalFingerprint(sessionID);
}
public String getRemoteKeyFingerprint(SessionID sessionID) {
return mOtrKeyManager.getRemoteFingerprint(sessionID);
}
public KeyPair getKeyPair(SessionID sessionID) {
KeyPair kp = null;
kp = mOtrKeyManager.loadLocalKeyPair(sessionID);
if (kp == null) {
mOtrKeyManager.generateLocalKeyPair(sessionID);
kp = mOtrKeyManager.loadLocalKeyPair(sessionID);
}
return kp;
}
public OtrPolicy getSessionPolicy(SessionID sessionID) {
return mPolicy;
}
public void setSessionPolicy(OtrPolicy policy) {
mPolicy = policy;
}
private void sendMessage(SessionID sessionID, String body) {
ImConnectionAdapter connection = findConnection(sessionID);
if (connection != null)
{
ChatSessionManagerAdapter chatSessionManagerAdapter = (ChatSessionManagerAdapter) connection
.getChatSessionManager();
ChatSessionAdapter chatSessionAdapter = (ChatSessionAdapter) chatSessionManagerAdapter
.getChatSession(Address.stripResource(sessionID.getRemoteUserId()));
if (chatSessionAdapter != null)
{
Message msg = new Message(body);
msg.setFrom(connection.getLoginUser().getAddress());
final Address to = chatSessionAdapter.getAdaptee().getParticipant().getAddress();
msg.setTo(appendSessionResource(sessionID, to));
msg.setDateTime(new Date());
// msg ID is set by plugin
// msg.setID(msg.getFrom().getBareAddress() + ":" + msg.getDateTime().getTime());
chatSessionManagerAdapter.getChatSessionManager().sendMessageAsync(chatSessionAdapter.getAdaptee(), msg);
}
else
{
OtrDebugLogger.log(sessionID.toString() + ": could not find chatSession");
}
}
else
{
OtrDebugLogger.log(sessionID.toString() + ": could not find ImConnection");
}
}
public void injectMessage(SessionID sessionID, String text) {
OtrDebugLogger.log(sessionID.toString() + ": injecting message: " + text);
sendMessage(sessionID, text);
}
public void showError(SessionID sessionID, String error) {
OtrDebugLogger.log(sessionID.toString() + ": ERROR=" + error);
if (mImService != null)
mImService.showToast("Encryption Error: " + error,Toast.LENGTH_SHORT);
}
public void showWarning(SessionID sessionID, String warning) {
OtrDebugLogger.log(sessionID.toString() + ": WARNING=" + warning);
if (mImService != null)
mImService.showToast("Encryption Warning: " + warning,Toast.LENGTH_SHORT);
}
} |
package br.usp.ime.ep2;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemSelectedListener {
private TextView mHighScoreTextView;
private Button mNewGameButton;
private Button mResetScoreButton;
private Spinner mLevelSpinner;
private SharedPreferences mSharedPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHighScoreTextView = (TextView) findViewById(R.id.mainHighScore);
mNewGameButton = (Button) findViewById(R.id.newGameButton);
mResetScoreButton = (Button) findViewById(R.id.resetScoreButton);
mLevelSpinner = (Spinner) findViewById(R.id.levelSpinner);
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.levels, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mLevelSpinner.setAdapter(adapter);
mLevelSpinner.setOnItemSelectedListener(this);
mLevelSpinner.setSelection(2); // Default to difficult "normal"
mNewGameButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(), UI.class);
startActivity(intent);
}
});
mResetScoreButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = mSharedPrefs.edit();
editor.remove("high_score");
editor.commit();
updateScoreTextView();
}
});
}
@Override
protected void onResume() {
super.onResume();
updateScoreTextView();
}
private void updateScoreTextView() {
long highScore = mSharedPrefs.getLong("high_score", 0);
mHighScoreTextView.setText(getString(R.string.high_score) + String.format("%08d", highScore));
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
SharedPreferences.Editor editor = mSharedPrefs.edit();
switch(pos) {
case 0: /*Can't die*/
editor.putFloat("ball_speed", 0.01f);
editor.putInt("lives", 99);
editor.putInt("hit_score", 0);
editor.putInt("max_multiplier", 1);
editor.putBoolean("invincibility", true);
editor.putFloat("grey_brick_prob", 0.1f);
editor.putFloat("ex_brick_prob", 0.1f);
editor.putFloat("mobile_brick_prob", 0.1f);
break;
case 1: /*Easy*/
editor.putFloat("ball_speed", 0.01f);
editor.putInt("lives", 3);
editor.putInt("hit_score", 50);
editor.putInt("max_multiplier", 4);
editor.putBoolean("invincibility", false);
editor.putFloat("grey_brick_prob", 0.15f);
editor.putFloat("ex_brick_prob", 0.15f);
editor.putFloat("mobile_brick_prob", 0.0f);
break;
case 2: /*Normal*/
editor.putFloat("ball_speed", 0.015f);
editor.putInt("lives", 2);
editor.putInt("hit_score", 100);
editor.putInt("max_multiplier", 8);
editor.putBoolean("invincibility", false);
editor.putFloat("grey_brick_prob", 0.25f);
editor.putFloat("ex_brick_prob", 0.1f);
editor.putFloat("mobile_brick_prob", 0.05f);
break;
case 3: /*Hard*/
editor.putFloat("ball_speed", 0.02f);
editor.putInt("lives", 1);
editor.putInt("hit_score", 150);
editor.putInt("max_multiplier", 16);
editor.putBoolean("invincibility", false);
editor.putFloat("grey_brick_prob", 0.35f);
editor.putFloat("ex_brick_prob", 0.05f);
editor.putFloat("mobile_brick_prob", 0.1f);
break;
}
editor.commit();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} |
package tw.kewang.mapcontroller;
import java.io.IOException;
import java.util.ArrayList;
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapController {
private static Context context;
private static GoogleMap map;
private static ArrayList<Marker> markers;
private static OnCameraChangeListener ccListener;
private static OnMyLocationChangeListener mlListener;
/**
* attach and initialize Google Maps
*
* @param context
* @param map
*/
public static void attach(Context context, GoogleMap map)
throws GooglePlayServicesNotAvailableException {
MapsInitializer.initialize(context);
MapController.context = context;
MapController.map = map;
}
/**
* detach Google Maps
*/
public static void detach() {
context = null;
map = null;
markers = null;
ccListener = null;
mlListener = null;
}
/**
* move to my current location
*
* @param tracking
* @param callback
*/
public static void moveToMyLocation(final boolean tracking,
final MoveMyLocation callback) {
showMyLocation();
if (mlListener == null) {
mlListener = new OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
if (!tracking) {
mlListener = null;
map.setOnMyLocationChangeListener(null);
}
if (callback != null) {
callback.moved(map, location);
}
}
};
}
map.setOnMyLocationChangeListener(mlListener);
}
/**
* move to my current location
*
* @param tracking
*/
public static void moveToMyLocation(boolean tracking) {
moveToMyLocation(tracking, null);
}
/**
* return my current location
*
* @return
*/
public static Location getMyLocation() {
if (!map.isMyLocationEnabled()) {
showMyLocation();
}
return map.getMyLocation();
}
/**
* show my current location
*/
public static void showMyLocation() {
map.setMyLocationEnabled(true);
}
/**
* animate to specific latlng
*
* @param latLng
* @param callback
*/
public static void animateTo(LatLng latLng, final Move callback) {
if (ccListener == null) {
ccListener = new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
map.setOnCameraChangeListener(null);
ccListener = null;
if (callback != null) {
callback.moved(map, position);
}
}
};
map.setOnCameraChangeListener(ccListener);
}
map.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
/**
* animate to specific latlng
*
* @param latLng
*/
public static void animateTo(LatLng latLng) {
animateTo(latLng, null);
}
/**
* move to specific latlng
*
* @param latLng
* @param callback
*/
public static void moveTo(LatLng latLng, final Move callback) {
if (ccListener == null) {
ccListener = new OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition position) {
map.setOnCameraChangeListener(null);
ccListener = null;
if (callback != null) {
callback.moved(map, position);
}
}
};
map.setOnCameraChangeListener(ccListener);
}
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
/**
* move to specific latlng
*
* @param latLng
*/
public static void moveTo(LatLng latLng) {
moveTo(latLng, null);
}
/**
* when map is clicked
*
* @param callback
*/
public static void whenMapClick(final MapClick callback) {
map.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
callback.mapClicked(map, latLng);
}
});
}
/**
* when info window is clicked
*
* @param callback
*/
public static void whenInfoWindowClick(final InfoWindowClick callback) {
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
callback.markerInfoWindowClicked(map, marker);
}
});
}
/**
* when marker is clicked
*
* @param callback
*/
public static void whenMarkerClick(final MarkerClick callback) {
map.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
callback.markerClicked(map, marker);
return true;
}
});
}
/**
* when marker is dragged
*
* @param callback
*/
public static void whenMarkerDrag(final MarkerDrag callback) {
map.setOnMarkerDragListener(new OnMarkerDragListener() {
@Override
public void onMarkerDragStart(Marker marker) {
callback.markerDragStart(map, marker);
}
@Override
public void onMarkerDrag(Marker marker) {
callback.markerDrag(map, marker);
}
@Override
public void onMarkerDragEnd(Marker marker) {
callback.markerDragEnd(map, marker);
}
});
}
/**
* add marker to map
*
* @param opts
* @param callback
*/
public static void add(MarkerOptions opts, MarkerAdd callback) {
Marker marker = map.addMarker(opts);
if (markers == null) {
markers = new ArrayList<Marker>();
}
markers.add(marker);
if (callback != null) {
callback.markerAdded(map, marker);
}
}
/**
* add marker to map
*
* @param opts
*/
public static void add(MarkerOptions opts) {
add(opts, null);
}
/**
* return all markers
*
* @return
*/
public static ArrayList<Marker> getAllMarkers() {
return markers;
}
/**
* return specific marker
*
* @param index
* @return
*/
public static Marker getMarker(int index) {
return markers.get(index);
}
/**
* clear all markers
*/
public static void clearAllMarkers() {
map.clear();
markers.clear();
}
/**
* zoom map
*
* @param zoom
*/
public static void zoom(int zoom) {
map.animateCamera(CameraUpdateFactory.zoomTo(zoom));
}
/**
* find specific location
*
* @param location
* @param callback
*/
public static void find(String location, FindResult callback) {
Geocoder geocoder = new Geocoder(context);
ArrayList<Address> addresses = new ArrayList<Address>();
try {
addresses = (ArrayList<Address>) geocoder.getFromLocationName(
location, 5);
} catch (IOException e) {
e.printStackTrace();
}
findCallback(callback, addresses);
}
/**
* find specific location
*
* @param location
*/
public static void find(String location) {
find(location, null);
}
/**
* find specific location
*
* @param location
* @param callback
*/
public static void findAsync(final String location,
final FindResult callback) {
new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog;
private ArrayList<Address> addresses;
@Override
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
Geocoder geocoder = new Geocoder(context);
try {
addresses = (ArrayList<Address>) geocoder
.getFromLocationName(location, 5);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
findCallback(callback, addresses);
}
}.execute();
}
/**
* find specific location
*
* @param location
*/
public static void findAsync(String location) {
findAsync(location, null);
}
private static void findCallback(FindResult callback,
ArrayList<Address> addresses) {
if (callback != null) {
callback.foundResult(map, addresses);
} else {
for (Address address : addresses) {
MarkerOptions opts = new MarkerOptions();
LatLng latLng = new LatLng(address.getLatitude(),
address.getLongitude());
opts.position(latLng);
opts.title(address.toString());
opts.snippet(latLng.toString());
add(opts);
}
animateTo(new LatLng(addresses.get(0).getLatitude(), addresses.get(
0).getLongitude()));
}
}
public interface MoveMyLocation {
public void moved(GoogleMap map, Location location);
}
public interface Move {
public void moved(GoogleMap map, CameraPosition position);
}
public interface MapClick {
public void mapClicked(GoogleMap map, LatLng latLng);
}
public interface MarkerAdd {
public void markerAdded(GoogleMap map, Marker marker);
}
public interface InfoWindowClick {
public void markerInfoWindowClicked(GoogleMap map, Marker marker);
}
public interface MarkerClick {
public void markerClicked(GoogleMap map, Marker marker);
}
public interface MarkerDrag {
public void markerDragStart(GoogleMap map, Marker marker);
public void markerDrag(GoogleMap map, Marker marker);
public void markerDragEnd(GoogleMap map, Marker marker);
}
public interface FindResult {
public void foundResult(GoogleMap map, ArrayList<Address> addresses);
}
} |
package org.apache.fop.render.ps;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.Color;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.BridgeException;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.SVGTextElementBridge;
import org.apache.batik.bridge.ViewBox;
import org.apache.batik.dom.svg.SVGOMDocument;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.resources.Messages;
import org.apache.batik.transcoder.image.ImageTranscoder;
import org.apache.fop.svg.AbstractFOPTranscoder;
import org.apache.batik.gvt.TextPainter;
import org.apache.batik.gvt.renderer.StrokingTextPainter;
import org.w3c.dom.Document;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.svg.SVGSVGElement;
/**
* This class enables to transcode an input to a PostScript document.
*
* <p>Two transcoding hints (<tt>KEY_WIDTH</tt> and
* <tt>KEY_HEIGHT</tt>) can be used to respectively specify the image
* width and the image height. If only one of these keys is specified,
* the transcoder preserves the aspect ratio of the original image.
*
* <p>The <tt>KEY_BACKGROUND_COLOR</tt> defines the background color
* to use for opaque image formats, or the background color that may
* be used for image formats that support alpha channel.
*
* <p>The <tt>KEY_AOI</tt> represents the area of interest to paint
* in device space.
*
* <p>Three additional transcoding hints that act on the SVG
* processor can be specified:
*
* <p><tt>KEY_LANGUAGE</tt> to set the default language to use (may be
* used by a <switch> SVG element for example),
* <tt>KEY_USER_STYLESHEET_URI</tt> to fix the URI of a user
* stylesheet, and <tt>KEY_PIXEL_TO_MM</tt> to specify the pixel to
* millimeter conversion factor.
*
* @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a>
* @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
* @version $Id: PDFTranscoder.java,v 1.24 2003/03/07 09:51:26 jeremias Exp $
*/
public class PSTranscoder extends AbstractFOPTranscoder {
/**
* Constructs a new <tt>PSTranscoder</tt>.
*/
public PSTranscoder() {
super();
}
/**
* Transcodes the specified Document as an image in the specified output.
*
* @param document the document to transcode
* @param uri the uri of the document or null if any
* @param output the ouput where to transcode
* @exception TranscoderException if an error occured while transcoding
*/
protected void transcode(Document document, String uri,
TranscoderOutput output) throws TranscoderException {
if (!(document instanceof SVGOMDocument)) {
throw new TranscoderException(Messages.formatMessage("notsvg",
null));
}
SVGDocument svgDoc = (SVGDocument)document;
SVGSVGElement root = svgDoc.getRootElement();
// initialize the SVG document with the appropriate context
String parserClassname = (String)hints.get(KEY_XML_PARSER_CLASSNAME);
PSDocumentGraphics2D graphics = new PSDocumentGraphics2D(false);
// build the GVT tree
GVTBuilder builder = new GVTBuilder();
BridgeContext ctx = new BridgeContext(userAgent);
TextPainter textPainter = null;
textPainter = new StrokingTextPainter();
ctx.setTextPainter(textPainter);
SVGTextElementBridge textElementBridge =
new PSTextElementBridge(graphics.getFontInfo());
ctx.putBridge(textElementBridge);
//PDFAElementBridge pdfAElementBridge = new PDFAElementBridge();
//AffineTransform currentTransform = new AffineTransform(1, 0, 0, 1, 0, 0);
//pdfAElementBridge.setCurrentTransform(currentTransform);
//ctx.putBridge(pdfAElementBridge);
//ctx.putBridge(new PSImageElementBridge());
GraphicsNode gvtRoot;
try {
gvtRoot = builder.build(ctx, svgDoc);
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
// get the 'width' and 'height' attributes of the SVG document
float docWidth = (float)ctx.getDocumentSize().getWidth();
float docHeight = (float)ctx.getDocumentSize().getHeight();
ctx = null;
builder = null;
// compute the image's width and height according the hints
float imgWidth = -1;
if (hints.containsKey(ImageTranscoder.KEY_WIDTH)) {
imgWidth =
((Float)hints.get(ImageTranscoder.KEY_WIDTH)).floatValue();
}
float imgHeight = -1;
if (hints.containsKey(ImageTranscoder.KEY_HEIGHT)) {
imgHeight =
((Float)hints.get(ImageTranscoder.KEY_HEIGHT)).floatValue();
}
float width, height;
if (imgWidth > 0 && imgHeight > 0) {
width = imgWidth;
height = imgHeight;
} else if (imgHeight > 0) {
width = (docWidth * imgHeight) / docHeight;
height = imgHeight;
} else if (imgWidth > 0) {
width = imgWidth;
height = (docHeight * imgWidth) / docWidth;
} else {
width = docWidth;
height = docHeight;
}
// compute the preserveAspectRatio matrix
AffineTransform px;
String ref = null;
try {
ref = new URL(uri).getRef();
} catch (MalformedURLException ex) {
// nothing to do, catched previously
}
try {
px = ViewBox.getViewTransform(ref, root, width, height);
} catch (BridgeException ex) {
throw new TranscoderException(ex);
}
if (px.isIdentity() && (width != docWidth || height != docHeight)) {
// The document has no viewBox, we need to resize it by hand.
// we want to keep the document size ratio
float d = Math.max(docWidth, docHeight);
float dd = Math.max(width, height);
float scale = dd / d;
px = AffineTransform.getScaleInstance(scale, scale);
}
// take the AOI into account if any
if (hints.containsKey(ImageTranscoder.KEY_AOI)) {
Rectangle2D aoi = (Rectangle2D)hints.get(ImageTranscoder.KEY_AOI);
// transform the AOI into the image's coordinate system
aoi = px.createTransformedShape(aoi).getBounds2D();
AffineTransform mx = new AffineTransform();
double sx = width / aoi.getWidth();
double sy = height / aoi.getHeight();
mx.scale(sx, sy);
double tx = -aoi.getX();
double ty = -aoi.getY();
mx.translate(tx, ty);
// take the AOI transformation matrix into account
// we apply first the preserveAspectRatio matrix
px.preConcatenate(mx);
}
// prepare the image to be painted
int w = (int)width;
int h = (int)height;
try {
graphics.setupDocument(output.getOutputStream(), w, h);
graphics.setSVGDimension(docWidth, docHeight);
if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) {
graphics.setBackgroundColor((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR));
}
graphics.setGraphicContext(new org.apache.batik.ext.awt.g2d.GraphicContext());
graphics.setTransform(px);
gvtRoot.paint(graphics);
graphics.finish();
} catch (IOException ex) {
throw new TranscoderException(ex);
}
}
} |
package org.apache.velocity.anakia;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.StringTokenizer;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.apache.velocity.Context;
import org.apache.velocity.Template;
import org.apache.velocity.runtime.Runtime;
import org.apache.velocity.util.StringUtils;
public class AnakiaTask extends MatchingTask
{
/** Default SAX Driver class to use */
private static final String DEFAULT_SAX_DRIVER_CLASS =
"org.apache.xerces.parsers.SAXParser";
/** <code>{@link SAXBuilder}</code> instance to use */
private SAXBuilder builder;
/** the destination directory */
private File destDir = null;
/** the base directory */
private File baseDir = null;
/** the style= attribute */
private String style = null;
/** the File to the style file */
private File styleFile = null;
/** last modified of the style sheet */
private long styleSheetLastModified = 0;
/** the projectFile= attribute */
private String projectAttribute = null;
/** the File for the project.xml file */
private File projectFile = null;
/** last modified of the project file if it exists */
private long projectFileLastModified = 0;
/** check the last modified date on files. defaults to true */
private boolean lastModifiedCheck = true;
/** the default output extension is .html */
private String extension = ".html";
/** the file to get the velocity properties file */
private File velocityPropertiesFile = null;
/**
* Constructor creates the SAXBuilder.
*/
public AnakiaTask()
{
builder = new SAXBuilder(DEFAULT_SAX_DRIVER_CLASS);
}
/**
* Set the base directory.
*/
public void setBasedir(File dir)
{
baseDir = dir;
}
/**
* Set the destination directory into which the VSL result
* files should be copied to
* @param dirName the name of the destination directory
*/
public void setDestdir(File dir)
{
destDir = dir;
}
/**
* Allow people to set the default output file extension
*/
public void setExtension(String extension)
{
this.extension = extension;
}
/**
* Allow people to set the path to the .vsl file
*/
public void setStyle(String style)
{
this.style = style;
}
/**
* Allow people to set the path to the project.xml file
*/
public void setProjectFile(String projectAttribute)
{
this.projectAttribute = projectAttribute;
}
/**
* Allow people to set the path to the velocity.properties file
* This file is found relative to the path where the JVM was run.
* For example, if build.sh was executed in the ./build directory,
* then the path would be relative to this directory.
*/
public void setVelocityPropertiesFile(File velocityPropertiesFile)
{
this.velocityPropertiesFile = velocityPropertiesFile;
}
/**
* Turn on/off last modified checking. by default, it is on.
*/
public void setLastModifiedCheck(String lastmod)
{
if (lastmod.equalsIgnoreCase("false") || lastmod.equalsIgnoreCase("no")
|| lastmod.equalsIgnoreCase("off"))
{
this.lastModifiedCheck = false;
}
}
/**
* Main body of the application
*/
public void execute () throws BuildException
{
DirectoryScanner scanner;
String[] list;
String[] dirs;
if (baseDir == null)
{
baseDir = project.resolveFile(".");
}
if (destDir == null )
{
String msg = "destdir attribute must be set!";
throw new BuildException(msg);
}
if (style == null)
{
throw new BuildException("style attribute must be set!");
}
if (velocityPropertiesFile == null)
{
velocityPropertiesFile = new File("velocity.properties");
}
if (!velocityPropertiesFile.exists())
throw new BuildException ("Could not locate velocity.properties file: " +
velocityPropertiesFile.getAbsolutePath());
log("Transforming into: " + destDir.getAbsolutePath(), Project.MSG_INFO);
// projectFile relative to baseDir
if (projectAttribute != null && projectAttribute.length() > 0)
{
projectFile = new File(baseDir, projectAttribute);
if (projectFile.exists())
projectFileLastModified = projectFile.lastModified();
else
{
log ("Project file is defined, but could not be located: " +
projectFile.getAbsolutePath(), Project.MSG_INFO );
projectFile = null;
}
}
try
{
// initialize Velocity
Runtime.init(velocityPropertiesFile.getAbsolutePath());
// get the last modification of the VSL stylesheet
styleSheetLastModified = Runtime.getTemplate(style).getLastModified();
}
catch (Exception e)
{
log("Error: " + e.toString(), Project.MSG_INFO);
}
// find the files/directories
scanner = getDirectoryScanner(baseDir);
// get a list of files to work on
list = scanner.getIncludedFiles();
for (int i = 0;i < list.length; ++i)
{
process( baseDir, list[i], destDir );
}
}
/**
* Process an XML file using Velocity
*/
private void process(File baseDir, String xmlFile, File destDir)
throws BuildException
{
File outFile=null;
File inFile=null;
Writer writer = null;
try
{
// the current input file relative to the baseDir
inFile = new File(baseDir,xmlFile);
// the output file relative to basedir
outFile = new File(destDir,xmlFile.substring(0,xmlFile.lastIndexOf('.'))+extension);
// only process files that have changed
if (lastModifiedCheck == false || (inFile.lastModified() > outFile.lastModified() ||
styleSheetLastModified > outFile.lastModified() ||
projectFileLastModified > outFile.lastModified()))
{
ensureDirectoryFor( outFile );
//-- command line status
log("Input: " + xmlFile, Project.MSG_INFO );
log("Output: " + outFile, Project.MSG_INFO );
// Build the JDOM Document
Document root = builder.build(inFile);
// Build the Project file document
// FIXME: this should happen in the execute method since
// it really only needs to be done once
Document projectDocument = null;
if (projectFile != null)
projectDocument = builder.build(projectFile);
// Shove things into the Context
Context context = new Context();
context.put ("root", root.getRootElement());
context.put ("xmlout", new XMLOutputter());
context.put ("relativePath", getRelativePath(xmlFile));
context.put ("treeWalk", new TreeWalker());
context.put ("xpath", new XPathTool() );
context.put ("escape", new Escape() );
// only put this into the context if it exists.
if (projectDocument != null)
context.put ("project", projectDocument.getRootElement());
// Process the VSL template with the context and write out
// the result as the outFile.
writer = new BufferedWriter(new FileWriter(outFile));
// get the template to process
Template template = Runtime.getTemplate(style);
template.merge(context, writer);
}
}
catch (JDOMException e)
{
if (e.getRootCause() != null)
{
e.getRootCause().printStackTrace();
}
else
{
e.printStackTrace();
}
// log("Failed to process " + inFile, Project.MSG_INFO);
if (outFile != null ) outFile.delete();
}
catch (Throwable e)
{
// log("Failed to process " + inFile, Project.MSG_INFO);
if (outFile != null ) outFile.delete();
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.flush();
writer.close();
}
catch (Exception e)
{
}
}
}
}
/**
* Hacky method to figure out the relative path
* that we are currently in. This is good for getting
* the relative path for images and anchor's.
*/
private String getRelativePath(String file)
{
if (file == null || file.length()==0)
return "";
StringTokenizer st = new StringTokenizer(file, "/\\");
// needs to be -1 cause ST returns 1 even if there are no matches. huh?
int slashCount = st.countTokens() - 1;
StringBuffer sb = new StringBuffer();
for (int i=0;i<slashCount ;i++ )
{
sb.append ("../");
}
if (sb.toString().length() > 0)
return StringUtils.chop(sb.toString(), 1);
else
return ".";
}
/**
* create directories as needed
*/
private void ensureDirectoryFor( File targetFile ) throws BuildException {
File directory = new File( targetFile.getParent() );
if (!directory.exists()) {
if (!directory.mkdirs()) {
throw new BuildException("Unable to create directory: "
+ directory.getAbsolutePath() );
}
}
}
} |
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.Border;
/**
* <code>JXCollapsiblePane</code> provides a component which can collapse or
* expand its content area with animation and fade in/fade out effects.
* It also acts as a standard container for other Swing components.
*
* <p>
* In this example, the <code>JXCollapsiblePane</code> is used to build
* a Search pane which can be shown and hidden on demand.
*
* <pre>
* <code>
* JXCollapsiblePane cp = new JXCollapsiblePane();
*
* // JXCollapsiblePane can be used like any other container
* cp.setLayout(new BorderLayout());
*
* // the Controls panel with a textfield to filter the tree
* JPanel controls = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
* controls.add(new JLabel("Search:"));
* controls.add(new JTextField(10));
* controls.add(new JButton("Refresh"));
* controls.setBorder(new TitledBorder("Filters"));
* cp.add("Center", controls);
*
* JXFrame frame = new JXFrame();
* frame.setLayout(new BorderLayout());
*
* // Put the "Controls" first
* frame.add("North", cp);
*
* // Then the tree - we assume the Controls would somehow filter the tree
* JScrollPane scroll = new JScrollPane(new JTree());
* frame.add("Center", scroll);
*
* // Show/hide the "Controls"
* JButton toggle = new JButton(cp.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
* toggle.setText("Show/Hide Search Panel");
* frame.add("South", toggle);
*
* frame.pack();
* frame.setVisible(true);
* </code>
* </pre>
*
* <p>
* The <code>JXCollapsiblePane</code> has a default toggle action registered
* under the name {@link #TOGGLE_ACTION}. Bind this action to a button and
* pressing the button will automatically toggle the pane between expanded
* and collapsed states. Additionally, you can define the icons to use through
* the {@link #EXPAND_ICON} and {@link #COLLAPSE_ICON} properties on the action.
* Example
* <pre>
* <code>
* // get the built-in toggle action
* Action toggleAction = collapsible.getActionMap().
* get(JXCollapsiblePane.TOGGLE_ACTION);
*
* // use the collapse/expand icons from the JTree UI
* toggleAction.putValue(JXCollapsiblePane.COLLAPSE_ICON,
* UIManager.getIcon("Tree.expandedIcon"));
* toggleAction.putValue(JXCollapsiblePane.EXPAND_ICON,
* UIManager.getIcon("Tree.collapsedIcon"));
* </code>
* </pre>
*
* <p>
* Note: <code>JXCollapsiblePane</code> requires its parent container to have a
* {@link java.awt.LayoutManager} using {@link #getPreferredSize()} when
* calculating its layout (example {@link org.jdesktop.swingx.VerticalLayout},
* {@link java.awt.BorderLayout}).
*
* @javabean.attribute
* name="isContainer"
* value="Boolean.TRUE"
* rtexpr="true"
*
* @javabean.attribute
* name="containerDelegate"
* value="getContentPane"
*
* @javabean.class
* name="JXCollapsiblePane"
* shortDescription="A pane which hides its content with an animation."
* stopClass="java.awt.Component"
*
* @author rbair (from the JDNC project)
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public class JXCollapsiblePane extends JXPanel {
/**
* The orientation defines in which direction the collapsible pane will
* expand.
*/
public enum Orientation {
/**
* The horizontal orientation makes the collapsible pane
* expand horizontally
*/
HORIZONTAL,
/**
* The horizontal orientation makes the collapsible pane
* expand vertically
*/
VERTICAL
}
/**
* Used when generating PropertyChangeEvents for the "animationState"
* property. The PropertyChangeEvent will takes the following different values
* for {@link PropertyChangeEvent#getNewValue()}:
* <ul>
* <li><code>reinit</code> every time the animation starts
* <li><code>expanded</code> when the animation ends and the pane is expanded
* <li><code>collapsed</code> when the animation ends and the pane is collapsed
* </ul>
*/
public final static String ANIMATION_STATE_KEY = "animationState";
/**
* JXCollapsible has a built-in toggle action which can be bound to buttons.
* Accesses the action through
* <code>collapsiblePane.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)</code>.
*/
public final static String TOGGLE_ACTION = "toggle";
/**
* The icon used by the "toggle" action when the JXCollapsiblePane is
* expanded, i.e the icon which indicates the pane can be collapsed.
*/
public final static String COLLAPSE_ICON = "collapseIcon";
/**
* The icon used by the "toggle" action when the JXCollapsiblePane is
* collapsed, i.e the icon which indicates the pane can be expanded.
*/
public final static String EXPAND_ICON = "expandIcon";
/**
* Indicates whether the component is collapsed or expanded
*/
private boolean collapsed = false;
/**
* Defines the orientation of the component.
*/
private Orientation orientation = Orientation.VERTICAL;
/**
* Timer used for doing the transparency animation (fade-in)
*/
private Timer animateTimer;
private AnimationListener animator;
private int currentDimension = -1;
private WrapperContainer wrapper;
private boolean useAnimation = true;
private AnimationParams animationParams;
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and a vertical {@link VerticalLayout} with a gap of 2 pixels as layout
* manager and a vertical orientation.
*/
public JXCollapsiblePane() {
this(Orientation.VERTICAL, new BorderLayout(0, 0));
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the specified orientation.
*/
public JXCollapsiblePane(Orientation orientation) {
this(orientation, new BorderLayout(0, 0));
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the given LayoutManager and a vertical orientation
*/
public JXCollapsiblePane(LayoutManager layout) {
this(Orientation.VERTICAL, layout);
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the given LayoutManager and orientation. A vertical orientation enables
* a vertical {@link VerticalLayout} with a gap of 2 pixels as layout
* manager. A horizontal orientation enables a horizontal
* {@link HorizontalLayout} with a gap of 2 pixels as layout manager
*/
public JXCollapsiblePane(Orientation orientation, LayoutManager layout) {
super.setLayout(layout);
this.orientation = orientation;
JPanel panel = new JPanel();
if (orientation == Orientation.VERTICAL) {
panel.setLayout(new VerticalLayout(2));
} else {
panel.setLayout(new HorizontalLayout(2));
}
setContentPane(panel);
animator = new AnimationListener();
setAnimationParams(new AnimationParams(30, 8, 0.01f, 1.0f));
// add an action to automatically toggle the state of the pane
getActionMap().put(TOGGLE_ACTION, new ToggleAction());
}
/**
* Toggles the JXCollapsiblePane state and updates its icon based on the
* JXCollapsiblePane "collapsed" status.
*/
private class ToggleAction extends AbstractAction implements
PropertyChangeListener {
public ToggleAction() {
super(TOGGLE_ACTION);
// the action must track the collapsed status of the pane to update its
// icon
JXCollapsiblePane.this.addPropertyChangeListener("collapsed", this);
}
@Override
public void putValue(String key, Object newValue) {
super.putValue(key, newValue);
if (EXPAND_ICON.equals(key) || COLLAPSE_ICON.equals(key)) {
updateIcon();
}
}
public void actionPerformed(ActionEvent e) {
setCollapsed(!isCollapsed());
}
public void propertyChange(PropertyChangeEvent evt) {
updateIcon();
}
void updateIcon() {
if (isCollapsed()) {
putValue(SMALL_ICON, getValue(EXPAND_ICON));
} else {
putValue(SMALL_ICON, getValue(COLLAPSE_ICON));
}
}
}
public void setContentPane(Container contentPanel) {
if (contentPanel == null) {
throw new IllegalArgumentException("Content pane can't be null");
}
if (wrapper != null) {
//these next two lines are as they are because if I try to remove
//the "wrapper" component directly, then super.remove(comp) ends up
//calling remove(int), which is overridden in this class, leading to
//improper behavior.
assert super.getComponent(0) == wrapper;
super.remove(0);
}
wrapper = new WrapperContainer(contentPanel);
wrapper.collapsedState = isCollapsed();
super.addImpl(wrapper, BorderLayout.CENTER, -1);
}
/**
* @return the content pane
*/
public Container getContentPane() {
if (wrapper == null) {
return null;
}
return (Container) wrapper.getView();
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void setLayout(LayoutManager mgr) {
// wrapper can be null when setLayout is called by "super()" constructor
if (wrapper != null) {
getContentPane().setLayout(mgr);
}
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
protected void addImpl(Component comp, Object constraints, int index) {
getContentPane().add(comp, constraints, index);
}
/**
* Overriden to redirect call to the content pane
*/
@Override
public void remove(Component comp) {
getContentPane().remove(comp);
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void remove(int index) {
getContentPane().remove(index);
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void removeAll() {
getContentPane().removeAll();
}
/**
* If true, enables the animation when pane is collapsed/expanded. If false,
* animation is turned off.
*
* <p>
* When animated, the <code>JXCollapsiblePane</code> will progressively
* reduce (when collapsing) or enlarge (when expanding) the height of its
* content area until it becomes 0 or until it reaches the preferred height of
* the components it contains. The transparency of the content area will also
* change during the animation.
*
* <p>
* If not animated, the <code>JXCollapsiblePane</code> will simply hide
* (collapsing) or show (expanding) its content area.
*
* @param animated
* @javabean.property bound="true" preferred="true"
*/
public void setAnimated(boolean animated) {
if (animated != useAnimation) {
useAnimation = animated;
firePropertyChange("animated", !useAnimation, useAnimation);
}
}
/**
* @return true if the pane is animated, false otherwise
* @see #setAnimated(boolean)
*/
public boolean isAnimated() {
return useAnimation;
}
public void setOrientation(Orientation orientation) {
if (orientation != this.orientation) {
if (animateTimer.isRunning()) {
throw new IllegalStateException("Orientation cannot be changed " +
"during collapsing.");
}
this.orientation = orientation;
if (orientation == Orientation.VERTICAL) {
getContentPane().setLayout(new VerticalLayout(2));
} else {
getContentPane().setLayout(new HorizontalLayout(2));
}
}
}
/**
* @see #setOrientation(Orientation)
* @return the current {@link Orientation}
*/
public Orientation getOrientation() {
return orientation;
}
/**
* @return true if the pane is collapsed, false if expanded
*/
public boolean isCollapsed() {
return collapsed;
}
/**
* Expands or collapses this <code>JXCollapsiblePane</code>.
*
* <p>
* If the component is collapsed and <code>val</code> is false, then this
* call expands the JXCollapsiblePane, such that the entire JXCollapsiblePane
* will be visible. If {@link #isAnimated()} returns true, the expansion will
* be accompanied by an animation.
*
* <p>
* However, if the component is expanded and <code>val</code> is true, then
* this call collapses the JXCollapsiblePane, such that the entire
* JXCollapsiblePane will be invisible. If {@link #isAnimated()} returns true,
* the collapse will be accompanied by an animation.
*
* @see #isAnimated()
* @see #setAnimated(boolean)
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setCollapsed(boolean val) {
if (collapsed != val) {
collapsed = val;
if (isAnimated()) {
if (collapsed) {
int dimension = orientation == Orientation.VERTICAL ?
wrapper.getHeight() : wrapper.getWidth();
setAnimationParams(new AnimationParams(30,
Math.max(8, dimension / 10), 1.0f, 0.01f));
animator.reinit(dimension, 0);
animateTimer.start();
} else {
int dimension = orientation == Orientation.VERTICAL ?
wrapper.getHeight() : wrapper.getWidth();
int preferredDimension = orientation == Orientation.VERTICAL ?
getContentPane().getPreferredSize().height :
getContentPane().getPreferredSize().width;
int delta = Math.max(8, preferredDimension / 10);
setAnimationParams(new AnimationParams(30, delta, 0.01f, 1.0f));
animator.reinit(dimension, preferredDimension);
animateTimer.start();
}
} else {
wrapper.collapsedState = collapsed;
revalidate();
}
repaint();
firePropertyChange("collapsed", !collapsed, collapsed);
}
}
/**
* {@inheritDoc}
*/
public Border getBorder() {
if (getContentPane() instanceof JComponent) {
return ((JComponent) getContentPane()).getBorder();
}
return null;
}
/**
* {@inheritDoc}
*/
public void setBorder(Border border) {
if (getContentPane() instanceof JComponent) {
((JComponent) getContentPane()).setBorder(border);
}
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* The critical part of the animation of this <code>JXCollapsiblePane</code>
* relies on the calculation of its preferred size. During the animation, its
* preferred size (specially its height) will change, when expanding, from 0
* to the preferred size of the content pane, and the reverse when collapsing.
*
* @return this component preferred size
*/
@Override
public Dimension getPreferredSize() {
/*
* The preferred size is calculated based on the current position of the
* component in its animation sequence. If the Component is expanded, then
* the preferred size will be the preferred size of the top component plus
* the preferred size of the embedded content container. <p>However, if the
* scroll up is in any state of animation, the height component of the
* preferred size will be the current height of the component (as contained
* in the currentDimension variable and when orientation is VERTICAL, otherwise
* the same applies to the width)
*/
Dimension dim = getContentPane().getPreferredSize();
if (currentDimension != -1) {
if (orientation == Orientation.VERTICAL) {
dim.height = currentDimension;
} else {
dim.width = currentDimension;
}
} else if(wrapper.collapsedState) {
if (orientation == Orientation.VERTICAL) {
dim.height = 0;
} else {
dim.width = 0;
}
}
return dim;
}
private void setAnimationParams(AnimationParams params) {
if (params == null) { throw new IllegalArgumentException(
"params can't be null"); }
if (animateTimer != null) {
animateTimer.stop();
}
animationParams = params;
animateTimer = new Timer(animationParams.waitTime, animator);
animateTimer.setInitialDelay(0);
}
/**
* Tagging interface for containers in a JXCollapsiblePane hierarchy who needs
* to be revalidated (invalidate/validate/repaint) when the pane is expanding
* or collapsing. Usually validating only the parent of the JXCollapsiblePane
* is enough but there might be cases where the parent parent must be
* validated.
*/
public static interface CollapsiblePaneContainer {
Container getValidatingContainer();
}
/**
* Parameters controlling the animations
*/
private static class AnimationParams {
final int waitTime;
final int delta;
final float alphaStart;
final float alphaEnd;
/**
* @param waitTime
* the amount of time in milliseconds to wait between calls to the
* animation thread
* @param delta
* the delta, in the direction as specified by the orientation,
* to inc/dec the size of the scroll up by
* @param alphaStart
* the starting alpha transparency level
* @param alphaEnd
* the ending alpha transparency level
*/
public AnimationParams(int waitTime, int delta, float alphaStart,
float alphaEnd) {
this.waitTime = waitTime;
this.delta = delta;
this.alphaStart = alphaStart;
this.alphaEnd = alphaEnd;
}
}
/**
* This class actual provides the animation support for scrolling up/down this
* component. This listener is called whenever the animateTimer fires off. It
* fires off in response to scroll up/down requests. This listener is
* responsible for modifying the size of the content container and causing it
* to be repainted.
*
* @author Richard Bair
*/
private final class AnimationListener implements ActionListener {
/**
* Mutex used to ensure that the startDimension/finalDimension are not changed
* during a repaint operation.
*/
private final Object ANIMATION_MUTEX = "Animation Synchronization Mutex";
/**
* This is the starting dimension when animating. If > finalDimension, then the
* animation is going to be to scroll up the component. If it is less than
* finalDimension, then the animation will scroll down the component.
*/
private int startDimension = 0;
/**
* This is the final dimension that the content container is going to be when
* scrolling is finished.
*/
private int finalDimension = 0;
/**
* The current alpha setting used during "animation" (fade-in/fade-out)
*/
@SuppressWarnings({"FieldCanBeLocal"})
private float animateAlpha = 1.0f;
public void actionPerformed(ActionEvent e) {
/*
* Pre-1) If startDimension == finalDimension, then we're done so stop the timer
* 1) Calculate whether we're contracting or expanding. 2) Calculate the
* delta (which is either positive or negative, depending on the results
* of (1)) 3) Calculate the alpha value 4) Resize the ContentContainer 5)
* Revalidate/Repaint the content container
*/
synchronized (ANIMATION_MUTEX) {
if (startDimension == finalDimension) {
animateTimer.stop();
animateAlpha = animationParams.alphaEnd;
// keep the content pane hidden when it is collapsed, other it may
// still receive focus.
if (finalDimension > 0) {
currentDimension = -1;
wrapper.collapsedState = false;
validate();
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"expanded");
return;
} else {
wrapper.collapsedState = true;
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"collapsed");
}
}
final boolean contracting = startDimension > finalDimension;
final int delta = contracting?-1 * animationParams.delta
:animationParams.delta;
int newDimension;
if (orientation == Orientation.VERTICAL) {
newDimension = wrapper.getHeight() + delta;
} else {
newDimension = wrapper.getWidth() + delta;
}
if (contracting) {
if (newDimension < finalDimension) {
newDimension = finalDimension;
}
} else {
if (newDimension > finalDimension) {
newDimension = finalDimension;
}
}
int dimension;
if (orientation == Orientation.VERTICAL) {
dimension = wrapper.getView().getPreferredSize().height;
} else {
dimension = wrapper.getView().getPreferredSize().width;
}
animateAlpha = (float)newDimension / (float)dimension;
Rectangle bounds = wrapper.getBounds();
if (orientation == Orientation.VERTICAL) {
int oldHeight = bounds.height;
bounds.height = newDimension;
wrapper.setBounds(bounds);
//TODO this is the open a window vs. open a shade
// wrapper.setViewPosition(new Point(0, wrapper.getView().getPreferredSize().height - newDimension));
bounds = getBounds();
bounds.height = (bounds.height - oldHeight) + newDimension;
currentDimension = bounds.height;
} else {
int oldWidth = bounds.width;
bounds.width = newDimension;
wrapper.setBounds(bounds);
bounds = getBounds();
bounds.width = (bounds.width - oldWidth) + newDimension;
currentDimension = bounds.width;
}
setBounds(bounds);
startDimension = newDimension;
// it happens the animateAlpha goes over the alphaStart/alphaEnd range
// this code ensures it stays in bounds. This behavior is seen when
// component such as JTextComponents are used in the container.
if (contracting) {
// alphaStart > animateAlpha > alphaEnd
if (animateAlpha < animationParams.alphaEnd) {
animateAlpha = animationParams.alphaEnd;
}
if (animateAlpha > animationParams.alphaStart) {
animateAlpha = animationParams.alphaStart;
}
} else {
// alphaStart < animateAlpha < alphaEnd
if (animateAlpha > animationParams.alphaEnd) {
animateAlpha = animationParams.alphaEnd;
}
if (animateAlpha < animationParams.alphaStart) {
animateAlpha = animationParams.alphaStart;
}
}
wrapper.alpha = animateAlpha;
validate();
}
}
void validate() {
Container parent = SwingUtilities.getAncestorOfClass(
CollapsiblePaneContainer.class, JXCollapsiblePane.this);
if (parent != null) {
parent = ((CollapsiblePaneContainer)parent).getValidatingContainer();
} else {
parent = getParent();
}
if (parent != null) {
if (parent instanceof JComponent) {
((JComponent)parent).revalidate();
} else {
parent.invalidate();
}
parent.doLayout();
parent.repaint();
}
}
/**
* Reinitializes the timer for scrolling up/down the component. This method
* is properly synchronized, so you may make this call regardless of whether
* the timer is currently executing or not.
*
* @param startDimension
* @param stopDimension
*/
public void reinit(int startDimension, int stopDimension) {
synchronized (ANIMATION_MUTEX) {
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"reinit");
this.startDimension = startDimension;
this.finalDimension = stopDimension;
animateAlpha = animationParams.alphaStart;
currentDimension = -1;
}
}
}
private final class WrapperContainer extends JViewport {
float alpha;
boolean collapsedState;
public WrapperContainer(Container c) {
alpha = 1.0f;
collapsedState = false;
setView(c);
// we must ensure the container is opaque. It is not opaque it introduces
// painting glitches specially on Linux with JDK 1.5 and GTK look and feel.
// GTK look and feel calls setOpaque(false)
if (c instanceof JComponent && !c.isOpaque()) {
((JComponent) c).setOpaque(true);
}
}
}
// TEST CASE
// public static void main(String[] args) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// JFrame f = new JFrame("Test Oriented Collapsible Pane");
// f.add(new JLabel("Press Ctrl+F or Ctrl+G to collapse panes."),
// BorderLayout.NORTH);
// JTree tree1 = new JTree();
// tree1.setBorder(BorderFactory.createEtchedBorder());
// f.add(tree1);
// JXCollapsiblePane pane = new JXCollapsiblePane(Orientation.VERTICAL);
// pane.setCollapsed(true);
// JTree tree2 = new JTree();
// tree2.setBorder(BorderFactory.createEtchedBorder());
// pane.add(tree2);
// f.add(pane, BorderLayout.SOUTH);
// pane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
// KeyStroke.getKeyStroke("ctrl F"),
// PatchedJXCollapsiblePane.TOGGLE_ACTION);
// pane = new JXCollapsiblePane(Orientation.HORIZONTAL);
// JTree tree3 = new JTree();
// pane.add(tree3);
// tree3.setBorder(BorderFactory.createEtchedBorder());
// f.add(pane, BorderLayout.WEST);
// pane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
// KeyStroke.getKeyStroke("ctrl G"),
// PatchedJXCollapsiblePane.TOGGLE_ACTION);
// f.setSize(640, 480);
// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.setVisible(true);
} |
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.Border;
/**
* <code>JXCollapsiblePane</code> provides a component which can collapse or
* expand its content area with animation and fade in/fade out effects.
* It also acts as a standard container for other Swing components.
*
* <p>
* In this example, the <code>JXCollapsiblePane</code> is used to build
* a Search pane which can be shown and hidden on demand.
*
* <pre>
* <code>
* JXCollapsiblePane cp = new JXCollapsiblePane();
*
* // JXCollapsiblePane can be used like any other container
* cp.setLayout(new BorderLayout());
*
* // the Controls panel with a textfield to filter the tree
* JPanel controls = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 0));
* controls.add(new JLabel("Search:"));
* controls.add(new JTextField(10));
* controls.add(new JButton("Refresh"));
* controls.setBorder(new TitledBorder("Filters"));
* cp.add("Center", controls);
*
* JXFrame frame = new JXFrame();
* frame.setLayout(new BorderLayout());
*
* // Put the "Controls" first
* frame.add("North", cp);
*
* // Then the tree - we assume the Controls would somehow filter the tree
* JScrollPane scroll = new JScrollPane(new JTree());
* frame.add("Center", scroll);
*
* // Show/hide the "Controls"
* JButton toggle = new JButton(cp.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
* toggle.setText("Show/Hide Search Panel");
* frame.add("South", toggle);
*
* frame.pack();
* frame.setVisible(true);
* </code>
* </pre>
*
* <p>
* The <code>JXCollapsiblePane</code> has a default toggle action registered
* under the name {@link #TOGGLE_ACTION}. Bind this action to a button and
* pressing the button will automatically toggle the pane between expanded
* and collapsed states. Additionally, you can define the icons to use through
* the {@link #EXPAND_ICON} and {@link #COLLAPSE_ICON} properties on the action.
* Example
* <pre>
* <code>
* // get the built-in toggle action
* Action toggleAction = collapsible.getActionMap().
* get(JXCollapsiblePane.TOGGLE_ACTION);
*
* // use the collapse/expand icons from the JTree UI
* toggleAction.putValue(JXCollapsiblePane.COLLAPSE_ICON,
* UIManager.getIcon("Tree.expandedIcon"));
* toggleAction.putValue(JXCollapsiblePane.EXPAND_ICON,
* UIManager.getIcon("Tree.collapsedIcon"));
* </code>
* </pre>
*
* <p>
* Note: <code>JXCollapsiblePane</code> requires its parent container to have a
* {@link java.awt.LayoutManager} using {@link #getPreferredSize()} when
* calculating its layout (example {@link org.jdesktop.swingx.VerticalLayout},
* {@link java.awt.BorderLayout}).
*
* @javabean.attribute
* name="isContainer"
* value="Boolean.TRUE"
* rtexpr="true"
*
* @javabean.attribute
* name="containerDelegate"
* value="getContentPane"
*
* @javabean.class
* name="JXCollapsiblePane"
* shortDescription="A pane which hides its content with an animation."
* stopClass="java.awt.Component"
*
* @author rbair (from the JDNC project)
* @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a>
*/
public class JXCollapsiblePane extends JXPanel {
/**
* The orientation defines in which direction the collapsible pane will
* expand.
*/
public enum Orientation {
/**
* The horizontal orientation makes the collapsible pane
* expand horizontally
*/
HORIZONTAL,
/**
* The horizontal orientation makes the collapsible pane
* expand vertically
*/
VERTICAL
}
/**
* Used when generating PropertyChangeEvents for the "animationState"
* property. The PropertyChangeEvent will takes the following different values
* for {@link PropertyChangeEvent#getNewValue()}:
* <ul>
* <li><code>reinit</code> every time the animation starts
* <li><code>expanded</code> when the animation ends and the pane is expanded
* <li><code>collapsed</code> when the animation ends and the pane is collapsed
* </ul>
*/
public final static String ANIMATION_STATE_KEY = "animationState";
/**
* JXCollapsible has a built-in toggle action which can be bound to buttons.
* Accesses the action through
* <code>collapsiblePane.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION)</code>.
*/
public final static String TOGGLE_ACTION = "toggle";
/**
* The icon used by the "toggle" action when the JXCollapsiblePane is
* expanded, i.e the icon which indicates the pane can be collapsed.
*/
public final static String COLLAPSE_ICON = "collapseIcon";
/**
* The icon used by the "toggle" action when the JXCollapsiblePane is
* collapsed, i.e the icon which indicates the pane can be expanded.
*/
public final static String EXPAND_ICON = "expandIcon";
/**
* Indicates whether the component is collapsed or expanded
*/
private boolean collapsed = false;
/**
* Defines the orientation of the component.
*/
private Orientation orientation = Orientation.VERTICAL;
/**
* Timer used for doing the transparency animation (fade-in)
*/
private Timer animateTimer;
private AnimationListener animator;
private int currentDimension = -1;
private WrapperContainer wrapper;
private boolean useAnimation = true;
private AnimationParams animationParams;
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and a vertical {@link VerticalLayout} with a gap of 2 pixels as layout
* manager and a vertical orientation.
*/
public JXCollapsiblePane() {
this(Orientation.VERTICAL, new BorderLayout(0, 0));
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the specified orientation.
*/
public JXCollapsiblePane(Orientation orientation) {
this(orientation, new BorderLayout(0, 0));
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the given LayoutManager and a vertical orientation
*/
public JXCollapsiblePane(LayoutManager layout) {
this(Orientation.VERTICAL, layout);
}
/**
* Constructs a new JXCollapsiblePane with a {@link JPanel} as content pane
* and the given LayoutManager and orientation. A vertical orientation enables
* a vertical {@link VerticalLayout} with a gap of 2 pixels as layout
* manager. A horizontal orientation enables a horizontal
* {@link HorizontalLayout} with a gap of 2 pixels as layout manager
*/
public JXCollapsiblePane(Orientation orientation, LayoutManager layout) {
super.setLayout(layout);
this.orientation = orientation;
JPanel panel = new JPanel();
if (orientation == Orientation.VERTICAL) {
panel.setLayout(new VerticalLayout(2));
} else {
panel.setLayout(new HorizontalLayout(2));
}
setContentPane(panel);
animator = new AnimationListener();
setAnimationParams(new AnimationParams(30, 8, 0.01f, 1.0f));
// add an action to automatically toggle the state of the pane
getActionMap().put(TOGGLE_ACTION, new ToggleAction());
}
/**
* Toggles the JXCollapsiblePane state and updates its icon based on the
* JXCollapsiblePane "collapsed" status.
*/
private class ToggleAction extends AbstractAction implements
PropertyChangeListener {
public ToggleAction() {
super(TOGGLE_ACTION);
// the action must track the collapsed status of the pane to update its
// icon
JXCollapsiblePane.this.addPropertyChangeListener("collapsed", this);
}
@Override
public void putValue(String key, Object newValue) {
super.putValue(key, newValue);
if (EXPAND_ICON.equals(key) || COLLAPSE_ICON.equals(key)) {
updateIcon();
}
}
public void actionPerformed(ActionEvent e) {
setCollapsed(!isCollapsed());
}
public void propertyChange(PropertyChangeEvent evt) {
updateIcon();
}
void updateIcon() {
if (isCollapsed()) {
putValue(SMALL_ICON, getValue(EXPAND_ICON));
} else {
putValue(SMALL_ICON, getValue(COLLAPSE_ICON));
}
}
}
public void setContentPane(Container contentPanel) {
if (contentPanel == null) {
throw new IllegalArgumentException("Content pane can't be null");
}
if (wrapper != null) {
//these next two lines are as they are because if I try to remove
//the "wrapper" component directly, then super.remove(comp) ends up
//calling remove(int), which is overridden in this class, leading to
//improper behavior.
assert super.getComponent(0) == wrapper;
super.remove(0);
}
wrapper = new WrapperContainer(contentPanel);
wrapper.collapsedState = isCollapsed();
super.addImpl(wrapper, BorderLayout.CENTER, -1);
}
/**
* @return the content pane
*/
public Container getContentPane() {
if (wrapper == null) {
return null;
}
return (Container) wrapper.getView();
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void setLayout(LayoutManager mgr) {
// wrapper can be null when setLayout is called by "super()" constructor
if (wrapper != null) {
getContentPane().setLayout(mgr);
}
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
protected void addImpl(Component comp, Object constraints, int index) {
getContentPane().add(comp, constraints, index);
}
/**
* Overriden to redirect call to the content pane
*/
@Override
public void remove(Component comp) {
getContentPane().remove(comp);
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void remove(int index) {
getContentPane().remove(index);
}
/**
* Overriden to redirect call to the content pane.
*/
@Override
public void removeAll() {
getContentPane().removeAll();
}
/**
* If true, enables the animation when pane is collapsed/expanded. If false,
* animation is turned off.
*
* <p>
* When animated, the <code>JXCollapsiblePane</code> will progressively
* reduce (when collapsing) or enlarge (when expanding) the height of its
* content area until it becomes 0 or until it reaches the preferred height of
* the components it contains. The transparency of the content area will also
* change during the animation.
*
* <p>
* If not animated, the <code>JXCollapsiblePane</code> will simply hide
* (collapsing) or show (expanding) its content area.
*
* @param animated
* @javabean.property bound="true" preferred="true"
*/
public void setAnimated(boolean animated) {
if (animated != useAnimation) {
useAnimation = animated;
firePropertyChange("animated", !useAnimation, useAnimation);
}
}
/**
* @return true if the pane is animated, false otherwise
* @see #setAnimated(boolean)
*/
public boolean isAnimated() {
return useAnimation;
}
public void setOrientation(Orientation orientation) {
if (orientation != this.orientation) {
if (animateTimer.isRunning()) {
throw new IllegalStateException("Orientation cannot be changed " +
"during collapsing.");
}
this.orientation = orientation;
if (orientation == Orientation.VERTICAL) {
getContentPane().setLayout(new VerticalLayout(2));
} else {
getContentPane().setLayout(new HorizontalLayout(2));
}
}
}
/**
* @see #setOrientation(Orientation)
* @return the current {@link Orientation}
*/
public Orientation getOrientation() {
return orientation;
}
/**
* @return true if the pane is collapsed, false if expanded
*/
public boolean isCollapsed() {
return collapsed;
}
/**
* Expands or collapses this <code>JXCollapsiblePane</code>.
*
* <p>
* If the component is collapsed and <code>val</code> is false, then this
* call expands the JXCollapsiblePane, such that the entire JXCollapsiblePane
* will be visible. If {@link #isAnimated()} returns true, the expansion will
* be accompanied by an animation.
*
* <p>
* However, if the component is expanded and <code>val</code> is true, then
* this call collapses the JXCollapsiblePane, such that the entire
* JXCollapsiblePane will be invisible. If {@link #isAnimated()} returns true,
* the collapse will be accompanied by an animation.
*
* @see #isAnimated()
* @see #setAnimated(boolean)
* @javabean.property
* bound="true"
* preferred="true"
*/
public void setCollapsed(boolean val) {
if (collapsed != val) {
collapsed = val;
if (isAnimated()) {
if (collapsed) {
int dimension = orientation == Orientation.VERTICAL ?
wrapper.getHeight() : wrapper.getWidth();
setAnimationParams(new AnimationParams(30,
Math.max(8, dimension / 10), 1.0f, 0.01f));
animator.reinit(dimension, 0);
animateTimer.start();
} else {
int dimension = orientation == Orientation.VERTICAL ?
wrapper.getHeight() : wrapper.getWidth();
int preferredDimension = orientation == Orientation.VERTICAL ?
getContentPane().getPreferredSize().height :
getContentPane().getPreferredSize().width;
int delta = Math.max(8, preferredDimension / 10);
setAnimationParams(new AnimationParams(30, delta, 0.01f, 1.0f));
animator.reinit(dimension, preferredDimension);
animateTimer.start();
}
} else {
wrapper.collapsedState = collapsed;
revalidate();
}
repaint();
firePropertyChange("collapsed", !collapsed, collapsed);
}
}
/**
* {@inheritDoc}
*/
public Border getBorder() {
if (getContentPane() instanceof JComponent) {
return ((JComponent) getContentPane()).getBorder();
}
return null;
}
/**
* {@inheritDoc}
*/
public void setBorder(Border border) {
if (getContentPane() instanceof JComponent) {
((JComponent) getContentPane()).setBorder(border);
}
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
/**
* The critical part of the animation of this <code>JXCollapsiblePane</code>
* relies on the calculation of its preferred size. During the animation, its
* preferred size (specially its height) will change, when expanding, from 0
* to the preferred size of the content pane, and the reverse when collapsing.
*
* @return this component preferred size
*/
@Override
public Dimension getPreferredSize() {
/*
* The preferred size is calculated based on the current position of the
* component in its animation sequence. If the Component is expanded, then
* the preferred size will be the preferred size of the top component plus
* the preferred size of the embedded content container. <p>However, if the
* scroll up is in any state of animation, the height component of the
* preferred size will be the current height of the component (as contained
* in the currentDimension variable and when orientation is VERTICAL, otherwise
* the same applies to the width)
*/
Dimension dim = getContentPane().getPreferredSize();
if (currentDimension != -1) {
if (orientation == Orientation.VERTICAL) {
dim.height = currentDimension;
} else {
dim.width = currentDimension;
}
} else if(wrapper.collapsedState) {
if (orientation == Orientation.VERTICAL) {
dim.height = 0;
} else {
dim.width = 0;
}
}
return dim;
}
@Override
public void setPreferredSize(Dimension preferredSize) {
getContentPane().setPreferredSize(preferredSize);
}
private void setAnimationParams(AnimationParams params) {
if (params == null) { throw new IllegalArgumentException(
"params can't be null"); }
if (animateTimer != null) {
animateTimer.stop();
}
animationParams = params;
animateTimer = new Timer(animationParams.waitTime, animator);
animateTimer.setInitialDelay(0);
}
/**
* Tagging interface for containers in a JXCollapsiblePane hierarchy who needs
* to be revalidated (invalidate/validate/repaint) when the pane is expanding
* or collapsing. Usually validating only the parent of the JXCollapsiblePane
* is enough but there might be cases where the parent parent must be
* validated.
*/
public static interface CollapsiblePaneContainer {
Container getValidatingContainer();
}
/**
* Parameters controlling the animations
*/
private static class AnimationParams {
final int waitTime;
final int delta;
final float alphaStart;
final float alphaEnd;
/**
* @param waitTime
* the amount of time in milliseconds to wait between calls to the
* animation thread
* @param delta
* the delta, in the direction as specified by the orientation,
* to inc/dec the size of the scroll up by
* @param alphaStart
* the starting alpha transparency level
* @param alphaEnd
* the ending alpha transparency level
*/
public AnimationParams(int waitTime, int delta, float alphaStart,
float alphaEnd) {
this.waitTime = waitTime;
this.delta = delta;
this.alphaStart = alphaStart;
this.alphaEnd = alphaEnd;
}
}
/**
* This class actual provides the animation support for scrolling up/down this
* component. This listener is called whenever the animateTimer fires off. It
* fires off in response to scroll up/down requests. This listener is
* responsible for modifying the size of the content container and causing it
* to be repainted.
*
* @author Richard Bair
*/
private final class AnimationListener implements ActionListener {
/**
* Mutex used to ensure that the startDimension/finalDimension are not changed
* during a repaint operation.
*/
private final Object ANIMATION_MUTEX = "Animation Synchronization Mutex";
/**
* This is the starting dimension when animating. If > finalDimension, then the
* animation is going to be to scroll up the component. If it is less than
* finalDimension, then the animation will scroll down the component.
*/
private int startDimension = 0;
/**
* This is the final dimension that the content container is going to be when
* scrolling is finished.
*/
private int finalDimension = 0;
/**
* The current alpha setting used during "animation" (fade-in/fade-out)
*/
@SuppressWarnings({"FieldCanBeLocal"})
private float animateAlpha = 1.0f;
public void actionPerformed(ActionEvent e) {
/*
* Pre-1) If startDimension == finalDimension, then we're done so stop the timer
* 1) Calculate whether we're contracting or expanding. 2) Calculate the
* delta (which is either positive or negative, depending on the results
* of (1)) 3) Calculate the alpha value 4) Resize the ContentContainer 5)
* Revalidate/Repaint the content container
*/
synchronized (ANIMATION_MUTEX) {
if (startDimension == finalDimension) {
animateTimer.stop();
animateAlpha = animationParams.alphaEnd;
// keep the content pane hidden when it is collapsed, other it may
// still receive focus.
if (finalDimension > 0) {
currentDimension = -1;
wrapper.collapsedState = false;
validate();
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"expanded");
return;
} else {
wrapper.collapsedState = true;
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"collapsed");
}
}
final boolean contracting = startDimension > finalDimension;
final int delta = contracting?-1 * animationParams.delta
:animationParams.delta;
int newDimension;
if (orientation == Orientation.VERTICAL) {
newDimension = wrapper.getHeight() + delta;
} else {
newDimension = wrapper.getWidth() + delta;
}
if (contracting) {
if (newDimension < finalDimension) {
newDimension = finalDimension;
}
} else {
if (newDimension > finalDimension) {
newDimension = finalDimension;
}
}
int dimension;
if (orientation == Orientation.VERTICAL) {
dimension = wrapper.getView().getPreferredSize().height;
} else {
dimension = wrapper.getView().getPreferredSize().width;
}
animateAlpha = (float)newDimension / (float)dimension;
Rectangle bounds = wrapper.getBounds();
if (orientation == Orientation.VERTICAL) {
int oldHeight = bounds.height;
bounds.height = newDimension;
wrapper.setBounds(bounds);
wrapper.setViewPosition(new Point(0, wrapper.getView().getPreferredSize().height - newDimension));
bounds = getBounds();
bounds.height = (bounds.height - oldHeight) + newDimension;
currentDimension = bounds.height;
} else {
int oldWidth = bounds.width;
bounds.width = newDimension;
wrapper.setBounds(bounds);
wrapper.setViewPosition(new Point(wrapper.getView().getPreferredSize().width - newDimension, 0));
bounds = getBounds();
bounds.width = (bounds.width - oldWidth) + newDimension;
currentDimension = bounds.width;
}
setBounds(bounds);
startDimension = newDimension;
// it happens the animateAlpha goes over the alphaStart/alphaEnd range
// this code ensures it stays in bounds. This behavior is seen when
// component such as JTextComponents are used in the container.
if (contracting) {
// alphaStart > animateAlpha > alphaEnd
if (animateAlpha < animationParams.alphaEnd) {
animateAlpha = animationParams.alphaEnd;
}
if (animateAlpha > animationParams.alphaStart) {
animateAlpha = animationParams.alphaStart;
}
} else {
// alphaStart < animateAlpha < alphaEnd
if (animateAlpha > animationParams.alphaEnd) {
animateAlpha = animationParams.alphaEnd;
}
if (animateAlpha < animationParams.alphaStart) {
animateAlpha = animationParams.alphaStart;
}
}
wrapper.alpha = animateAlpha;
validate();
}
}
void validate() {
Container parent = SwingUtilities.getAncestorOfClass(
CollapsiblePaneContainer.class, JXCollapsiblePane.this);
if (parent != null) {
parent = ((CollapsiblePaneContainer)parent).getValidatingContainer();
} else {
parent = getParent();
}
if (parent != null) {
if (parent instanceof JComponent) {
((JComponent)parent).revalidate();
} else {
parent.invalidate();
}
parent.doLayout();
parent.repaint();
}
}
/**
* Reinitializes the timer for scrolling up/down the component. This method
* is properly synchronized, so you may make this call regardless of whether
* the timer is currently executing or not.
*
* @param startDimension
* @param stopDimension
*/
public void reinit(int startDimension, int stopDimension) {
synchronized (ANIMATION_MUTEX) {
JXCollapsiblePane.this.firePropertyChange(ANIMATION_STATE_KEY, null,
"reinit");
this.startDimension = startDimension;
this.finalDimension = stopDimension;
animateAlpha = animationParams.alphaStart;
currentDimension = -1;
}
}
}
private final class WrapperContainer extends JViewport {
float alpha;
boolean collapsedState;
public WrapperContainer(Container c) {
alpha = 1.0f;
collapsedState = false;
setView(c);
// we must ensure the container is opaque. It is not opaque it introduces
// painting glitches specially on Linux with JDK 1.5 and GTK look and feel.
// GTK look and feel calls setOpaque(false)
if (c instanceof JComponent && !c.isOpaque()) {
((JComponent) c).setOpaque(true);
}
}
}
// TEST CASE
// public static void main(String[] args) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// JFrame f = new JFrame("Test Oriented Collapsible Pane");
// f.add(new JLabel("Press Ctrl+F or Ctrl+G to collapse panes."),
// BorderLayout.NORTH);
// JTree tree1 = new JTree();
// tree1.setBorder(BorderFactory.createEtchedBorder());
// f.add(tree1);
// JXCollapsiblePane pane = new JXCollapsiblePane(Orientation.VERTICAL);
// pane.setCollapsed(true);
// JTree tree2 = new JTree();
// tree2.setBorder(BorderFactory.createEtchedBorder());
// pane.add(tree2);
// f.add(pane, BorderLayout.SOUTH);
// pane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
// KeyStroke.getKeyStroke("ctrl F"),
// JXCollapsiblePane.TOGGLE_ACTION);
// pane = new JXCollapsiblePane(Orientation.HORIZONTAL);
// JTree tree3 = new JTree();
// pane.add(tree3);
// tree3.setBorder(BorderFactory.createEtchedBorder());
// f.add(pane, BorderLayout.WEST);
// pane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
// KeyStroke.getKeyStroke("ctrl G"),
// JXCollapsiblePane.TOGGLE_ACTION);
// f.setSize(640, 480);
// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.setVisible(true);
} |
package org.jdesktop.swingx;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
/**
* <p>A simple horizontal separator that contains a title.<br/>
*
* <p>JXTitledSeparator allows you to specify the title via the {@link #setTitle} method.
* The title alignment may be specified by using the {@link #setHorizontalAlignment}
* method, and accepts all the same arguments as the {@link javax.swing.JLabel#setHorizontalAlignment}
* method.</p>
*
* <p>In addition, you may specify an Icon to use with this separator. The icon
* will appear "leading" the title (on the left in left-to-right languages,
* on the right in right-to-left languages). To change the position of the
* title with respect to the icon, call {@link #setHorizontalTextPosition}.</p>
*
* <p>The default font and color of the title comes from the <code>LookAndFeel</code>, mimicking
* the font and color of the {@link javax.swing.TitledBorder}</p>
*
* <p>Here are a few example code snippets:
* <pre><code>
* //create a plain separator
* JXTitledSeparator sep = new JXTitledSeparator();
* sep.setText("Customer Info");
*
* //create a separator with an icon
* sep = new JXTitledSeparator();
* sep.setText("Customer Info");
* sep.setIcon(new ImageIcon("myimage.png"));
*
* //create a separator with an icon to the right of the title,
* //center justified
* sep = new JXTitledSeparator();
* sep.setText("Customer Info");
* sep.setIcon(new ImageIcon("myimage.png"));
* sep.setHorizontalAlignment(SwingConstants.CENTER);
* sep.setHorizontalTextPosition(SwingConstants.TRAILING);
* </code></pre>
*
* @author rbair
*/
public class JXTitledSeparator extends JXPanel {
/**
* Implementation detail: the label used to display the title
*/
private JLabel label;
/**
* Implementation detail: a separator to use on the left of the
* title if alignment is centered or right justified
*/
private JSeparator leftSeparator;
/**
* Implementation detail: a separator to use on the right of the
* title if alignment is centered or left justified
*/
private JSeparator rightSeparator;
/**
* Creates a new instance of <code>JXTitledSeparator</code>. The default title is simply
* an empty string. Default justification is <code>LEADING</code>, and the default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator() {
this("Untitled");
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title. Default horizontal alignment is <code>LEADING</code>, and the default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title) {
this(title, SwingConstants.LEADING, null);
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title and horizontal alignment. The default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title, int horizontalAlignment) {
this(title, horizontalAlignment, null);
}
/**
* Creates a new instance of <code>JXTitledSeparator</code> with the specified
* title, icon, and horizontal alignment. The default
* horizontal text position is <code>TRAILING</code> (title follows icon)
*/
public JXTitledSeparator(String title, int horizontalAlignment, Icon icon) {
setLayout(new GridBagLayout());
label = new JLabel(title);
label.setIcon(icon);
label.setHorizontalAlignment(horizontalAlignment);
leftSeparator = new JSeparator();
rightSeparator = new JSeparator();
layoutSeparator();
label.setForeground(UIManager.getColor("TitledBorder.titleColor"));
label.setFont(UIManager.getFont("TitledBorder.font"));
}
/**
* Implementation detail. lays out this component, showing/hiding components
* as necessary. Actually changes the containment (removes and adds components).
* <code>JXTitledSeparator</code> is treated as a single component rather than
* a container.
*/
private void layoutSeparator() {
removeAll();
switch (label.getHorizontalAlignment()) {
case SwingConstants.LEFT:
case SwingConstants.LEADING:
case SwingConstants.WEST:
add(label, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(rightSeparator, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
break;
case SwingConstants.RIGHT:
case SwingConstants.TRAILING:
case SwingConstants.EAST:
add(rightSeparator, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
break;
case SwingConstants.CENTER:
default:
add(leftSeparator, new GridBagConstraints(0, 0, 1, 1, 0.5, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(label, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(Box.createHorizontalStrut(3), new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0,0,0,0), 0, 0));
add(rightSeparator, new GridBagConstraints(4, 0, 1, 1, 0.5, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,0), 0, 0));
}
}
/**
* Sets the title for the separator. This may be simple html, or plain
* text.
*
* @param title the new title. Any string input is acceptable
*/
public void setTitle(String title) {
String old = getTitle();
label.setText(title);
firePropertyChange("title", old, getTitle());
}
/**
* Gets the title.
*
* @return the title being used for this <code>JXTitledSeparator</code>.
* This will be the raw title text, and so may include html tags etc
* if they were so specified in #setTitle.
*/
public String getTitle() {
return label.getText();
}
public void setHorizontalAlignment(int alignment) {
int old = getHorizontalAlignment();
label.setHorizontalAlignment(alignment);
if (old != getHorizontalAlignment()) {
layoutSeparator();
}
firePropertyChange("horizontalAlignment", old, getHorizontalAlignment());
}
/**
* Returns the alignment of the title contents along the X axis.
*
* @return The value of the horizontalAlignment property, one of the
* following constants defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see #setHorizontalAlignment
* @see SwingConstants
*/
public int getHorizontalAlignment() {
return label.getHorizontalAlignment();
}
public void setHorizontalTextPosition(int position) {
int old = getHorizontalTextPosition();
label.setHorizontalTextPosition(position);
firePropertyChange("horizontalTextPosition", old, getHorizontalTextPosition());
}
/**
* Returns the horizontal position of the title's text,
* relative to the icon.
*
* @return One of the following constants
* defined in <code>SwingConstants</code>:
* <code>LEFT</code>,
* <code>CENTER</code>,
* <code>RIGHT</code>,
* <code>LEADING</code> or
* <code>TRAILING</code>.
*
* @see SwingConstants
*/
public int getHorizontalTextPosition() {
return label.getHorizontalTextPosition();
}
/**
* Defines the icon this component will display. If
* the value of icon is null, nothing is displayed.
* <p>
* The default value of this property is null.
*
* @see #setHorizontalTextPosition
* @see #getIcon
*/
public void setIcon(Icon icon) {
Icon old = getIcon();
label.setIcon(icon);
firePropertyChange("icon", old, getIcon());
}
/**
* Returns the graphic image (glyph, icon) that the
* <code>JXTitledSeparator</code> displays.
*
* @return an Icon
* @see #setIcon
*/
public Icon getIcon() {
return label.getIcon();
}
/**
* @inheritDoc
*/
@Override
public void setForeground(Color foreground) {
if (label != null) {
label.setForeground(foreground);
}
super.setForeground(foreground);
}
/**
* @inheritDoc
*/
@Override
public void setFont(Font font) {
if (label != null) {
label.setFont(font);
}
super.setFont(font);
}
} |
package org.jivesoftware.openfire.group;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.event.GroupEventDispatcher;
import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.util.Cacheable;
import org.jivesoftware.util.Log;
import org.xmpp.packet.JID;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Groups organize users into a single entity for easier management.<p>
*
* The actual group implementation is controlled by the {@link GroupProvider}, which
* includes things like the group name, the members, and adminstrators. Each group
* also has properties, which are always stored in the Openfire database.
*
* @see GroupManager#createGroup(String)
*
* @author Matt Tucker
*/
public class Group implements Cacheable {
private static final String LOAD_PROPERTIES =
"SELECT name, propValue FROM jiveGroupProp WHERE groupName=?";
private static final String DELETE_PROPERTY =
"DELETE FROM jiveGroupProp WHERE groupName=? AND name=?";
private static final String UPDATE_PROPERTY =
"UPDATE jiveGroupProp SET propValue=? WHERE name=? AND groupName=?";
private static final String INSERT_PROPERTY =
"INSERT INTO jiveGroupProp (groupName, name, propValue) VALUES (?, ?, ?)";
private static final String LOAD_SHARED_GROUPS =
"SELECT groupName FROM jiveGroupProp WHERE name='sharedRoster.showInRoster' " +
"AND propValue IS NOT NULL AND propValue <> 'nobody'";
private transient GroupProvider provider;
private transient GroupManager groupManager;
private String name;
private String description;
private Map<String, String> properties;
private Set<JID> members;
private Set<JID> administrators;
/**
* Returns the name of the groups that are shared groups.
*
* @return the name of the groups that are shared groups.
*/
static Set<String> getSharedGroupsNames() {
Set<String> groupNames = new HashSet<String>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_SHARED_GROUPS);
rs = pstmt.executeQuery();
while (rs.next()) {
groupNames.add(rs.getString(1));
}
}
catch (SQLException sqle) {
Log.error(sqle);
}
finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
return groupNames;
}
/**
* Constructs a new group. Note: this constructor is intended for implementors of the
* {@link GroupProvider} interface. To create a new group, use the
* {@link GroupManager#createGroup(String)} method.
*
* @param name the name.
* @param description the description.
* @param members a Collection of the group members.
* @param administrators a Collection of the group administrators.
*/
public Group(String name, String description, Collection<JID> members,
Collection<JID> administrators)
{
this.groupManager = GroupManager.getInstance();
this.provider = groupManager.getProvider();
this.name = name;
this.description = description;
this.members = new HashSet<JID>(members);
this.administrators = new HashSet<JID>(administrators);
}
/**
* Returns the name of the group. For example, 'XYZ Admins'.
*
* @return the name of the group.
*/
public String getName() {
return name;
}
public void setName(String name) {
if (name == this.name || (name != null && name.equals(this.name)) || provider.isReadOnly())
{
// Do nothing
return;
}
try {
String originalName = this.name;
provider.setName(this.name, name);
groupManager.groupCache.remove(this.name);
this.name = name;
groupManager.groupCache.put(name, this);
// Fire event.
Map<String, Object> params = new HashMap<String, Object>();
params.put("type", "nameModified");
params.put("originalValue", originalName);
GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified,
params);
}
catch (Exception e) {
Log.error(e);
}
}
/**
* Returns the description of the group. The description often
* summarizes a group's function, such as 'Administrators of the XYZ forum'.
*
* @return the description of the group.
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
if (description == this.description ||
(description != null && description.equals(this.description)) ||
provider.isReadOnly())
{
// Do nothing
return;
}
try {
String originalDescription = this.description;
provider.setDescription(name, description);
this.description = description;
// Fire event.
Map<String, Object> params = new HashMap<String, Object>();
params.put("type", "descriptionModified");
params.put("originalValue", originalDescription);
GroupEventDispatcher.dispatchEvent(this,
GroupEventDispatcher.EventType.group_modified, params);
}
catch (Exception e) {
Log.error(e);
}
}
public String toString() {
return name;
}
/**
* Returns all extended properties of the group. Groups
* have an arbitrary number of extended properties.
*
* @return the extended properties.
*/
public Map<String,String> getProperties() {
synchronized (this) {
if (properties == null) {
properties = new ConcurrentHashMap<String, String>();
loadProperties();
}
}
// Return a wrapper that will intercept add and remove commands.
return new PropertiesMap();
}
/**
* Returns a Collection of the group administrators.
*
* @return a Collection of the group administrators.
*/
public Collection<JID> getAdmins() {
// Return a wrapper that will intercept add and remove commands.
return new MemberCollection(administrators, true);
}
/**
* Returns a Collection of the group members.
*
* @return a Collection of the group members.
*/
public Collection<JID> getMembers() {
// Return a wrapper that will intercept add and remove commands.
return new MemberCollection(members, false);
}
/**
* Returns true if the provided JID belongs to a user that is part of the group.
*
* @param user the JID address of the user to check.
* @return true if the specified user is a group user.
*/
public boolean isUser(JID user) {
// Make sure that we are always checking bare JIDs
if (user != null && user.getResource() != null) {
user = new JID(user.toBareJID());
}
return user != null && (members.contains(user) || administrators.contains(user));
}
/**
* Returns true if the provided username belongs to a user of the group.
*
* @param username the username to check.
* @return true if the provided username belongs to a user of the group.
*/
public boolean isUser(String username) {
if (username != null) {
return isUser(XMPPServer.getInstance().createJID(username, null));
}
else {
return false;
}
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
groupManager = GroupManager.getInstance();
provider = groupManager.getProvider();
}
public int getCachedSize() {
// Approximate the size of the object in bytes by calculating the size
// of each field.
int size = 0;
size += CacheSizes.sizeOfObject(); // overhead of object
size += CacheSizes.sizeOfString(name);
size += CacheSizes.sizeOfString(description);
size += CacheSizes.sizeOfMap(properties);
for (JID member: members) {
size += CacheSizes.sizeOfString(member.toString());
}
for (JID admin: administrators) {
size += CacheSizes.sizeOfString(admin.toString());
}
return size;
}
public int hashCode() {
return name.hashCode();
}
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object != null && object instanceof Group) {
return name.equals(((Group)object).getName());
}
else {
return false;
}
}
/**
* Collection implementation that notifies the GroupProvider of any
* changes to the collection.
*/
private class MemberCollection extends AbstractCollection {
private Collection<JID> users;
private boolean adminCollection;
public MemberCollection(Collection<JID> users, boolean adminCollection) {
this.users = users;
this.adminCollection = adminCollection;
}
public Iterator<JID> iterator() {
return new Iterator() {
Iterator<JID> iter = users.iterator();
Object current = null;
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
current = iter.next();
return current;
}
public void remove() {
if (current == null) {
throw new IllegalStateException();
}
// Do nothing if the provider is read-only.
if (provider.isReadOnly()) {
return;
}
JID user = (JID)current;
// Remove the user from the collection in memory.
iter.remove();
// Remove the group user from the backend store.
provider.deleteMember(name, user);
// Fire event.
if (adminCollection) {
Map<String, String> params = new HashMap<String, String>();
params.put("admin", user.toString());
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.admin_removed, params);
}
else {
Map<String, String> params = new HashMap<String, String>();
params.put("member", user.toString());
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.member_removed, params);
}
}
};
}
public int size() {
return users.size();
}
public boolean add(Object member) {
// Do nothing if the provider is read-only.
if (provider.isReadOnly()) {
return false;
}
JID user = (JID) member;
// Find out if the user was already a group user.
boolean alreadyGroupUser;
if (adminCollection) {
alreadyGroupUser = members.contains(user);
}
else {
alreadyGroupUser = administrators.contains(user);
}
if (users.add(user)) {
if (alreadyGroupUser) {
// Update the group user privileges in the backend store.
provider.updateMember(name, user, adminCollection);
}
else {
// Add the group user to the backend store.
provider.addMember(name, user, adminCollection);
}
// Fire event.
if (adminCollection) {
Map<String, String> params = new HashMap<String, String>();
params.put("admin", user.toString());
if (alreadyGroupUser) {
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.member_removed, params);
}
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.admin_added, params);
}
else {
Map<String, String> params = new HashMap<String, String>();
params.put("member", user.toString());
if (alreadyGroupUser) {
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.admin_removed, params);
}
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.member_added, params);
}
// If the user was a member that became an admin or vice versa then remove the
// user from the other collection
if (alreadyGroupUser) {
if (adminCollection) {
if (members.contains(user)) {
members.remove(user);
}
}
else {
if (administrators.contains(user)) {
administrators.remove(user);
}
}
}
return true;
}
return false;
}
}
/**
* Map implementation that updates the database when properties are modified.
*/
private class PropertiesMap extends AbstractMap {
public Object put(Object key, Object value) {
if (key == null || value == null) {
throw new NullPointerException();
}
Map<String, Object> eventParams = new HashMap<String, Object>();
Object answer;
String keyString = (String) key;
synchronized (keyString.intern()) {
if (properties.containsKey(keyString)) {
String originalValue = properties.get(keyString);
answer = properties.put(keyString, (String)value);
updateProperty(keyString, (String)value);
// Configure event.
eventParams.put("type", "propertyModified");
eventParams.put("propertyKey", key);
eventParams.put("originalValue", originalValue);
}
else {
answer = properties.put(keyString, (String)value);
insertProperty(keyString, (String)value);
// Configure event.
eventParams.put("type", "propertyAdded");
eventParams.put("propertyKey", key);
}
}
// Fire event.
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.group_modified, eventParams);
return answer;
}
public Set<Entry> entrySet() {
return new PropertiesEntrySet();
}
}
/**
* Set implementation that updates the database when properties are deleted.
*/
private class PropertiesEntrySet extends AbstractSet {
public int size() {
return properties.entrySet().size();
}
public Iterator iterator() {
return new Iterator() {
Iterator iter = properties.entrySet().iterator();
Map.Entry current = null;
public boolean hasNext() {
return iter.hasNext();
}
public Object next() {
current = (Map.Entry)iter.next();
return current;
}
public void remove() {
if (current == null) {
throw new IllegalStateException();
}
String key = (String)current.getKey();
deleteProperty(key);
iter.remove();
// Fire event.
Map<String, Object> params = new HashMap<String, Object>();
params.put("type", "propertyDeleted");
params.put("propertyKey", key);
GroupEventDispatcher.dispatchEvent(Group.this,
GroupEventDispatcher.EventType.group_modified, params);
}
};
}
}
private void loadProperties() {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOAD_PROPERTIES);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
while (rs.next()) {
String key = rs.getString(1);
String value = rs.getString(2);
if (key != null) {
if (value == null) {
value = "";
Log.warn("There is a group property whose value is null of Group: " + name);
}
properties.put(key, value);
}
else {
Log.warn("There is a group property whose key is null of Group: " + name);
}
}
}
catch (SQLException sqle) {
Log.error(sqle);
}
finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
}
private void insertProperty(String propName, String propValue) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(INSERT_PROPERTY);
pstmt.setString(1, name);
pstmt.setString(2, propName);
pstmt.setString(3, propValue);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(e);
}
finally {
DbConnectionManager.closeConnection(pstmt, con);
}
}
private void updateProperty(String propName, String propValue) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(UPDATE_PROPERTY);
pstmt.setString(1, propValue);
pstmt.setString(2, propName);
pstmt.setString(3, name);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(e);
}
finally {
DbConnectionManager.closeConnection(pstmt, con);
}
}
private void deleteProperty(String propName) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(DELETE_PROPERTY);
pstmt.setString(1, name);
pstmt.setString(2, propName);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.error(e);
}
finally {
DbConnectionManager.closeConnection(pstmt, con);
}
}
} |
package org.jivesoftware.spark.ui;
import org.jivesoftware.MainWindowListener;
import org.jivesoftware.Spark;
import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.RosterPacket;
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.SharedGroupManager;
import org.jivesoftware.smackx.packet.LastActivity;
import org.jivesoftware.spark.ChatManager;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.UserManager;
import org.jivesoftware.spark.Workspace;
import org.jivesoftware.spark.component.InputDialog;
import org.jivesoftware.spark.component.RolloverButton;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.component.WrappedLabel;
import org.jivesoftware.spark.plugin.ContextMenuListener;
import org.jivesoftware.spark.plugin.Plugin;
import org.jivesoftware.spark.ui.status.StatusBar;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.SwingWorker;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.profile.VCardManager;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public final class ContactList extends JPanel implements ActionListener, ContactGroupListener, Plugin, RosterListener, ConnectionListener {
private JPanel mainPanel = new JPanel();
private JScrollPane treeScroller;
private final List<ContactGroup> groupList = new ArrayList<ContactGroup>();
private final RolloverButton addingGroupButton;
private ContactItem activeItem;
private ContactGroup activeGroup;
private ContactGroup unfiledGroup = new ContactGroup("Unfiled");
// Create Menus
private JMenuItem addContactMenu;
private JMenuItem addContactGroupMenu;
private JMenuItem removeContactFromGroupMenu;
private JMenuItem chatMenu;
private JMenuItem renameMenu;
private ContactGroup offlineGroup;
final JCheckBoxMenuItem showHideMenu = new JCheckBoxMenuItem();
private List sharedGroups = new ArrayList();
private final List contextListeners = new ArrayList();
private List initialPresences = new ArrayList();
private final Timer presenceTimer = new Timer();
private final List dndListeners = new ArrayList();
private final List contactListListeners = new ArrayList();
private Properties props;
private File propertiesFile;
private LocalPreferences localPreferences;
public final static String RETRY_PANEL = "RETRY_PANEL";
private RetryPanel retryPanel;
private RetryPanel.ReconnectListener reconnectListener;
private Workspace workspace;
public ContactList() {
// Load Local Preferences
localPreferences = SettingsManager.getLocalPreferences();
offlineGroup = new ContactGroup("Offline Group");
JToolBar toolbar = new JToolBar();
toolbar.setFloatable(false);
addContactMenu = new JMenuItem(Res.getString("menuitem.add.contact"), SparkRes.getImageIcon(SparkRes.USER1_ADD_16x16));
addContactGroupMenu = new JMenuItem(Res.getString("menuitem.add.contact.group"), SparkRes.getImageIcon(SparkRes.SMALL_ADD_IMAGE));
removeContactFromGroupMenu = new JMenuItem(Res.getString("menuitem.remove.from.group"), SparkRes.getImageIcon(SparkRes.SMALL_DELETE));
chatMenu = new JMenuItem(Res.getString("menuitem.start.a.chat"), SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE));
renameMenu = new JMenuItem(Res.getString("menuitem.rename"), SparkRes.getImageIcon(SparkRes.DESKTOP_IMAGE));
addContactMenu.addActionListener(this);
removeContactFromGroupMenu.addActionListener(this);
chatMenu.addActionListener(this);
renameMenu.addActionListener(this);
setLayout(new BorderLayout());
addingGroupButton = new RolloverButton(SparkRes.getImageIcon(SparkRes.ADD_CONTACT_IMAGE));
RolloverButton groupChatButton = new RolloverButton(SparkRes.getImageIcon(SparkRes.JOIN_GROUPCHAT_IMAGE));
toolbar.add(addingGroupButton);
toolbar.add(groupChatButton);
addingGroupButton.addActionListener(this);
mainPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false));
mainPanel.setBackground((Color)UIManager.get("List.background"));
treeScroller = new JScrollPane(mainPanel);
treeScroller.setBorder(BorderFactory.createEmptyBorder());
treeScroller.getVerticalScrollBar().setBlockIncrement(50);
treeScroller.getVerticalScrollBar().setUnitIncrement(20);
retryPanel = new RetryPanel();
workspace = SparkManager.getWorkspace();
workspace.getCardPanel().add(RETRY_PANEL, retryPanel);
add(treeScroller, BorderLayout.CENTER);
// Load Properties file
props = new Properties();
// Save to properties file.
propertiesFile = new File(new File(Spark.getUserHome(), "Spark"), "groups.properties");
try {
props.load(new FileInputStream(propertiesFile));
}
catch (IOException e) {
// File does not exist.
}
// Add ActionListener(s) to menus
addContactGroup(unfiledGroup);
addContactGroup(offlineGroup);
showHideMenu.setSelected(false);
// Add KeyMappings
SparkManager.getMainWindow().getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control F"), "searchContacts");
SparkManager.getMainWindow().getRootPane().getActionMap().put("searchContacts", new AbstractAction("searchContacts") {
public void actionPerformed(ActionEvent evt) {
SparkManager.getUserManager().searchContacts("", SparkManager.getMainWindow());
}
});
// Save state on shutdown.
SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() {
public void shutdown() {
saveState();
}
public void mainWindowActivated() {
}
public void mainWindowDeactivated() {
}
});
SparkManager.getConnection().addConnectionListener(this);
// Get command panel and add View Online/Offline, Add Contact
StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
JPanel commandPanel = statusBar.getCommandPanel();
final RolloverButton addContactButton = new RolloverButton(SparkRes.getImageIcon(SparkRes.USER1_ADD_16x16));
commandPanel.add(addContactButton);
addContactButton.setToolTipText(Res.getString("message.add.a.contact"));
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new RosterDialog().showRosterDialog();
}
});
}
/**
* Updates the users presence.
*
* @param presence the user to update.
*/
private void updateUserPresence(Presence presence) {
if (presence == null) {
return;
}
Roster roster = SparkManager.getConnection().getRoster();
final String bareJID = StringUtils.parseBareAddress(presence.getFrom());
RosterEntry entry = roster.getEntry(bareJID);
boolean isPending = entry != null && (entry.getType() == RosterPacket.ItemType.NONE || entry.getType() == RosterPacket.ItemType.FROM)
&& RosterPacket.ItemStatus.SUBSCRIPTION_PENDING == entry.getStatus();
// If online, check to see if they are in the offline group.
// If so, remove from offline group and add to all groups they
// belong to.
if (presence.getType() == Presence.Type.available && offlineGroup.getContactItemByJID(bareJID) != null) {
changeOfflineToOnline(bareJID, entry, presence);
}
else if (presence.getFrom().indexOf("workgroup.") != -1) {
changeOfflineToOnline(bareJID, entry, presence);
}
// If online, but not in offline group, update presence.
else if (presence.getType() == Presence.Type.available) {
final Iterator groupIterator = groupList.iterator();
while (groupIterator.hasNext()) {
ContactGroup group = (ContactGroup)groupIterator.next();
ContactItem item = group.getContactItemByJID(bareJID);
if (item != null) {
item.setPresence(presence);
group.fireContactGroupUpdated();
}
}
}
// If not available, move to offline group.
else if (presence.getType() == Presence.Type.unavailable && !isPending) {
presence = roster.getPresence(bareJID);
if (presence == null) {
moveToOfflineGroup(bareJID);
}
}
}
private void moveToOfflineGroup(final String bareJID) {
final Iterator groupIterator = new ArrayList(groupList).iterator();
while (groupIterator.hasNext()) {
final ContactGroup group = (ContactGroup)groupIterator.next();
final ContactItem item = group.getContactItemByJID(bareJID);
if (item != null) {
item.showUserGoingOfflineOnline();
item.setIcon(SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON));
group.fireContactGroupUpdated();
int numberOfMillisecondsInTheFuture = 3000;
Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Roster roster = SparkManager.getConnection().getRoster();
Presence userPresence = roster.getPresence(bareJID);
if (userPresence != null) {
return;
}
item.setPresence(null);
// Check for ContactItemHandler.
group.removeContactItem(item);
checkGroup(group);
if (offlineGroup.getContactItemByJID(item.getFullJID()) == null) {
offlineGroup.addContactItem(item);
offlineGroup.fireContactGroupUpdated();
}
}
}, timeToRun);
}
}
}
private void changeOfflineToOnline(String bareJID, final RosterEntry entry, Presence presence) {
// Move out of offline group. Add to all groups.
ContactItem offlineItem = offlineGroup.getContactItemByJID(bareJID);
if (offlineItem == null) {
return;
}
offlineGroup.removeContactItem(offlineItem);
// Add To all groups it belongs to.
boolean isFiled = false;
for (RosterGroup rosterGroup : entry.getGroups()) {
isFiled = true;
ContactGroup contactGroup = getContactGroup(rosterGroup.getName());
if (contactGroup != null) {
String name = entry.getName();
if (name == null) {
name = entry.getUser();
}
ContactItem contactItem = null;
if (contactGroup.getContactItemByJID(entry.getUser()) == null) {
contactItem = new ContactItem(name, entry.getUser());
contactGroup.addContactItem(contactItem);
}
else if (contactGroup.getContactItemByJID(entry.getUser()) != null) {
// If the user is in their, but without a nice presence.
contactItem = contactGroup.getContactItemByJID(entry.getUser());
}
contactItem.setPresence(presence);
contactItem.setAvailable(true);
toggleGroupVisibility(contactGroup.getGroupName(), true);
contactItem.showUserComingOnline();
contactGroup.fireContactGroupUpdated();
int numberOfMillisecondsInTheFuture = 5000;
Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture);
Timer timer = new Timer();
final ContactItem staticItem = contactItem;
final ContactGroup staticGroup = contactGroup;
timer.schedule(new TimerTask() {
public void run() {
staticItem.updatePresenceIcon(staticItem.getPresence());
staticGroup.fireContactGroupUpdated();
}
}, timeToRun);
}
}
if (!isFiled) {
String name = entry.getName();
if (name == null) {
name = entry.getUser();
}
ContactItem contactItem = new ContactItem(name, entry.getUser());
unfiledGroup.addContactItem(contactItem);
contactItem.setPresence(presence);
contactItem.setAvailable(true);
unfiledGroup.setVisible(true);
unfiledGroup.fireContactGroupUpdated();
}
}
private void buildContactList() {
XMPPConnection con = SparkManager.getConnection();
final Roster roster = con.getRoster();
roster.addRosterListener(this);
for (RosterGroup group : roster.getGroups()) {
ContactGroup contactGroup = addContactGroup(group.getName());
for (RosterEntry entry : group.getEntries()) {
String name = entry.getName();
if (name == null) {
name = entry.getUser();
}
ContactItem contactItem = new ContactItem(name, entry.getUser());
contactItem.setPresence(null);
if ((entry.getType() == RosterPacket.ItemType.NONE || entry.getType() == RosterPacket.ItemType.FROM)
&& RosterPacket.ItemStatus.SUBSCRIPTION_PENDING == entry.getStatus()) {
// Add to contact group.
contactGroup.addContactItem(contactItem);
contactGroup.setVisible(true);
}
else {
if (offlineGroup.getContactItemByJID(entry.getUser()) == null) {
offlineGroup.addContactItem(contactItem);
}
}
}
}
// Add Unfiled Group
// addContactGroup(unfiledGroup);
for (RosterEntry entry : roster.getUnfiledEntries()) {
String name = entry.getName();
if (name == null) {
name = entry.getUser();
}
ContactItem contactItem = new ContactItem(name, entry.getUser());
offlineGroup.addContactItem(contactItem);
}
unfiledGroup.setVisible(false);
}
/**
* Called when NEW entries are added.
*
* @param addresses the address added.
*/
public void entriesAdded(final Collection addresses) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Roster roster = SparkManager.getConnection().getRoster();
Iterator jids = addresses.iterator();
while (jids.hasNext()) {
String jid = (String)jids.next();
RosterEntry entry = roster.getEntry(jid);
addUser(entry);
}
}
});
}
private void addUser(RosterEntry entry) {
String name = entry.getName();
if (!ModelUtil.hasLength(name)) {
name = entry.getUser();
}
String nickname = entry.getName();
if (!ModelUtil.hasLength(nickname)) {
nickname = entry.getUser();
}
ContactItem newContactItem = new ContactItem(nickname, entry.getUser());
// Update users icon
Presence presence = SparkManager.getConnection().getRoster().getPresence(entry.getUser());
newContactItem.setPresence(presence);
if (entry != null && (entry.getType() == RosterPacket.ItemType.NONE || entry.getType() == RosterPacket.ItemType.FROM)) {
// Ignore, since the new user is pending to be added.
for (RosterGroup group : entry.getGroups()) {
ContactGroup contactGroup = getContactGroup(group.getName());
if (contactGroup == null) {
contactGroup = addContactGroup(group.getName());
}
contactGroup.addContactItem(newContactItem);
}
return;
}
else {
offlineGroup.addContactItem(newContactItem);
}
if (presence != null) {
updateUserPresence(presence);
}
}
private ContactItem addNewContactItem(String groupName, String nickname, String jid) {
// Create User Node
ContactGroup contactGroup = getContactGroup(groupName);
ContactItem contactItem = new ContactItem(nickname, jid);
contactGroup.addContactItem(contactItem);
contactGroup.setVisible(true);
validateTree();
return contactItem;
}
/**
* Handle when the Roster changes based on subscription notices.
*
* @param addresses
*/
public void entriesUpdated(final Collection addresses) {
handleEntriesUpdated(addresses);
}
/**
* Called when users are removed from the roster.
*
* @param addresses the addresses removed from the roster.
*/
public void entriesDeleted(final Collection addresses) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Iterator jids = addresses.iterator();
while (jids.hasNext()) {
String jid = (String)jids.next();
removeContactItem(jid);
}
}
});
}
private synchronized void handleEntriesUpdated(final Collection addresses) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Roster roster = SparkManager.getConnection().getRoster();
Iterator jids = addresses.iterator();
while (jids.hasNext()) {
String jid = (String)jids.next();
RosterEntry rosterEntry = roster.getEntry(jid);
if (rosterEntry != null) {
// Check for new Roster Groups and add them if they do not exist.
boolean isUnfiled = true;
for (RosterGroup group : rosterEntry.getGroups()) {
isUnfiled = false;
// Handle if this is a new Entry in a new Group.
if (getContactGroup(group.getName()) == null) {
// Create group.
ContactGroup contactGroup = addContactGroup(group.getName());
contactGroup.setVisible(false);
contactGroup = getContactGroup(group.getName());
String name = rosterEntry.getName();
if (name == null) {
name = rosterEntry.getUser();
}
ContactItem contactItem = new ContactItem(name, rosterEntry.getUser());
contactGroup.addContactItem(contactItem);
Presence presence = roster.getPresence(jid);
contactItem.setPresence(presence);
if (presence != null) {
contactGroup.setVisible(true);
}
}
else {
ContactGroup contactGroup = getContactGroup(group.getName());
ContactItem item = offlineGroup.getContactItemByJID(jid);
if (item == null) {
item = contactGroup.getContactItemByJID(jid);
}
// Check to see if this entry is new to a pre-existing group.
if (item == null) {
String name = rosterEntry.getName();
if (name == null) {
name = rosterEntry.getUser();
}
item = new ContactItem(name, rosterEntry.getUser());
Presence presence = roster.getPresence(jid);
item.setPresence(presence);
if (presence != null) {
contactGroup.addContactItem(item);
contactGroup.fireContactGroupUpdated();
}
else {
offlineGroup.addContactItem(item);
offlineGroup.fireContactGroupUpdated();
}
}
// If not, just update their presence.
else {
Presence presence = roster.getPresence(jid);
item.setPresence(presence);
updateUserPresence(presence);
contactGroup.fireContactGroupUpdated();
}
}
}
// Now check to see if groups have been modified or removed. This is used
// to check if Contact Groups have been renamed or removed.
final Set<String> groupSet = new HashSet<String>();
jids = addresses.iterator();
while (jids.hasNext()) {
jid = (String)jids.next();
rosterEntry = roster.getEntry(jid);
for (RosterGroup g : rosterEntry.getGroups()) {
groupSet.add(g.getName());
}
for (ContactGroup group : new ArrayList<ContactGroup>(getContactGroups())) {
if (group.getContactItemByJID(jid) != null && group != unfiledGroup && group != offlineGroup) {
if (!groupSet.contains(group.getGroupName())) {
removeContactGroup(group);
}
}
}
}
if (!isUnfiled) {
return;
}
ContactItem unfiledItem = unfiledGroup.getContactItemByJID(jid);
if (unfiledItem != null) {
}
else {
ContactItem offlineItem = offlineGroup.getContactItemByJID(jid);
if (offlineItem != null) {
if ((rosterEntry.getType() == RosterPacket.ItemType.NONE || rosterEntry.getType() == RosterPacket.ItemType.FROM)
&& RosterPacket.ItemStatus.SUBSCRIPTION_PENDING == rosterEntry.getStatus()) {
// Remove from offlineItem and add to unfiledItem.
offlineGroup.removeContactItem(offlineItem);
unfiledGroup.addContactItem(offlineItem);
unfiledGroup.fireContactGroupUpdated();
unfiledGroup.setVisible(true);
}
}
}
}
}
}
});
}
public void presenceChanged(final String user) {
}
/**
* Retrieve the ContactItem by it's jid.
*
* @param jid the JID of the user.
* @return the "first" contact item found.
*/
public ContactItem getContactItemByJID(String jid) {
for (ContactGroup group : getContactGroups()) {
ContactItem item = group.getContactItemByJID(StringUtils.parseBareAddress(jid));
if (item != null) {
return item;
}
}
return null;
}
/**
* Returns a Collection of ContactItems in a ContactList.
*
* @param jid the users JID.
* @return a Collection of <code>ContactItem</code> items.
*/
public Collection<ContactItem> getContactItemsByJID(String jid) {
final List<ContactItem> list = new ArrayList<ContactItem>();
for (ContactGroup group : getContactGroups()) {
ContactItem item = group.getContactItemByJID(StringUtils.parseBareAddress(jid));
if (item != null) {
list.add(item);
}
}
return list;
}
/**
* Set an Icon for all ContactItems that match the given jid.
*
* @param jid the users jid.
* @param icon the icon to use.
*/
public void setIconFor(String jid, Icon icon) {
for (ContactGroup group : getContactGroups()) {
ContactItem item = group.getContactItemByJID(StringUtils.parseBareAddress(jid));
if (item != null) {
item.setIcon(icon);
group.fireContactGroupUpdated();
}
}
}
/**
* Sets the default settings for a ContactItem.
*
* @param jid the users jid.
*/
public void useDefaults(String jid) {
for (ContactGroup group : getContactGroups()) {
ContactItem item = group.getContactItemByJID(StringUtils.parseBareAddress(jid));
if (item != null) {
item.updatePresenceIcon(item.getPresence());
group.fireContactGroupUpdated();
}
}
}
/**
* Retrieve the ContactItem by their nickname.
*
* @param nickname the users nickname in the contact list.
* @return the "first" contact item found.
*/
public ContactItem getContactItemByNickname(String nickname) {
Iterator contactGroups = getContactGroups().iterator();
while (contactGroups.hasNext()) {
ContactGroup contactGroup = (ContactGroup)contactGroups.next();
ContactItem item = contactGroup.getContactItemByNickname(nickname);
if (item != null) {
return item;
}
}
return null;
}
private void addContactGroup(ContactGroup group) {
groupList.add(group);
try {
mainPanel.add(group, groupList.size() - 1);
}
catch (Exception e) {
System.out.println("Unable to add Contact Group" + group.getGroupName());
Log.error(e);
}
group.addContactGroupListener(this);
fireContactGroupAdded(group);
// Check state
String prop = props.getProperty(group.getGroupName());
if (prop != null) {
boolean isCollapsed = Boolean.valueOf(prop).booleanValue();
group.setCollapsed(isCollapsed);
}
}
private ContactGroup addContactGroup(String groupName) {
StringTokenizer tkn = new StringTokenizer(groupName, "::");
ContactGroup rootGroup = null;
ContactGroup lastGroup = null;
StringBuffer buf = new StringBuffer();
boolean groupAdded = false;
while (tkn.hasMoreTokens()) {
String group = tkn.nextToken();
buf.append(group);
if (tkn.hasMoreTokens()) {
buf.append("::");
}
String name = buf.toString();
if (name.endsWith("::")) {
name = name.substring(0, name.length() - 2);
}
ContactGroup newContactGroup = getContactGroup(name);
if (newContactGroup == null) {
newContactGroup = new ContactGroup(group);
String realGroupName = buf.toString();
if (realGroupName.endsWith("::")) {
realGroupName = realGroupName.substring(0, realGroupName.length() - 2);
}
newContactGroup.setGroupName(realGroupName);
}
else {
if (newContactGroup != offlineGroup && newContactGroup != unfiledGroup) {
rootGroup = newContactGroup;
continue;
}
}
if (lastGroup != null) {
lastGroup.addContactGroup(newContactGroup);
groupList.add(newContactGroup);
}
else if (rootGroup != null) {
rootGroup.addContactGroup(newContactGroup);
groupList.add(newContactGroup);
}
else {
rootGroup = newContactGroup;
}
lastGroup = newContactGroup;
newContactGroup.addContactGroupListener(this);
if (sharedGroups != null) {
boolean isSharedGroup = sharedGroups.contains(newContactGroup.getGroupName());
newContactGroup.setSharedGroup(isSharedGroup);
}
fireContactGroupAdded(newContactGroup);
// Check state
String prop = props.getProperty(newContactGroup.getGroupName());
if (prop != null) {
boolean isCollapsed = Boolean.valueOf(prop).booleanValue();
newContactGroup.setCollapsed(isCollapsed);
}
groupAdded = true;
}
if (!groupAdded) {
return getContactGroup(groupName);
}
final List tempList = new ArrayList();
final Component[] comps = mainPanel.getComponents();
for (int i = 0; i < comps.length; i++) {
Component c = comps[i];
if (comps[i] instanceof ContactGroup && c != offlineGroup) {
tempList.add(c);
}
}
tempList.add(rootGroup);
groupList.add(rootGroup);
Collections.sort(tempList, groupComparator);
int loc = tempList.indexOf(rootGroup);
try {
if (rootGroup == offlineGroup) {
mainPanel.add(rootGroup, tempList.size() - 1);
}
else {
mainPanel.add(rootGroup, loc);
}
}
catch (Exception e) {
System.out.println("Unable to add Contact Group" + rootGroup.getGroupName());
Log.error(e);
}
return getContactGroup(groupName);
}
private void removeContactGroup(ContactGroup contactGroup) {
contactGroup.removeContactGroupListener(this);
groupList.remove(contactGroup);
mainPanel.remove(contactGroup);
ContactGroup parent = getParentGroup(contactGroup.getGroupName());
if (parent != null) {
parent.removeContactGroup(contactGroup);
}
treeScroller.validate();
mainPanel.invalidate();
mainPanel.repaint();
fireContactGroupRemoved(contactGroup);
}
public ContactGroup getContactGroup(String groupName) {
ContactGroup grp = null;
for (ContactGroup contactGroup : groupList) {
if (contactGroup.getGroupName().equals(groupName)) {
grp = contactGroup;
break;
}
else {
grp = getSubContactGroup(contactGroup, groupName);
if (grp != null) {
break;
}
}
}
return grp;
}
public ContactGroup getParentGroup(String groupName) {
// Check if there is even a parent group
if (!groupName.contains("::")) {
return null;
}
final ContactGroup group = getContactGroup(groupName);
if (group == null) {
return null;
}
// Otherwise, find parent
int index = groupName.lastIndexOf("::");
String parentGroupName = groupName.substring(0, index);
return getContactGroup(parentGroupName);
}
private ContactGroup getSubContactGroup(ContactGroup group, String groupName) {
final Iterator contactGroups = group.getContactGroups().iterator();
ContactGroup grp = null;
while (contactGroups.hasNext()) {
ContactGroup contactGroup = (ContactGroup)contactGroups.next();
if (contactGroup.getGroupName().equals(groupName)) {
grp = contactGroup;
break;
}
else if (contactGroup.getContactGroups().size() > 0) {
grp = getSubContactGroup(contactGroup, groupName);
if (grp != null) {
break;
}
}
}
return grp;
}
public void toggleGroupVisibility(String groupName, boolean visible) {
StringTokenizer tkn = new StringTokenizer(groupName, "::");
while (tkn.hasMoreTokens()) {
String group = tkn.nextToken();
ContactGroup contactGroup = getContactGroup(group);
if (contactGroup != null) {
contactGroup.setVisible(visible);
}
}
ContactGroup group = getContactGroup(groupName);
if (group != null) {
group.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addingGroupButton) {
new RosterDialog().showRosterDialog();
}
else if (e.getSource() == chatMenu) {
if (activeItem != null) {
SparkManager.getChatManager().activateChat(activeItem.getContactJID(), activeItem.getNickname());
}
}
else if (e.getSource() == addContactMenu) {
RosterDialog rosterDialog = new RosterDialog();
if (activeGroup != null) {
rosterDialog.setDefaultGroup(activeGroup);
}
rosterDialog.showRosterDialog();
}
else if (e.getSource() == removeContactFromGroupMenu) {
if (activeItem != null) {
removeContactFromGroup(activeItem);
}
}
else if (e.getSource() == renameMenu) {
if (activeItem == null) {
return;
}
String oldNickname = activeItem.getNickname();
String newNickname = JOptionPane.showInputDialog(this, Res.getString("label.rename.to") + ":", oldNickname);
if (ModelUtil.hasLength(newNickname)) {
String address = activeItem.getFullJID();
ContactGroup contactGroup = getContactGroup(activeItem.getGroupName());
ContactItem contactItem = contactGroup.getContactItemByNickname(activeItem.getNickname());
contactItem.setNickname(newNickname);
final Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(address);
entry.setName(newNickname);
final Iterator contactGroups = groupList.iterator();
String user = StringUtils.parseBareAddress(address);
while (contactGroups.hasNext()) {
ContactGroup cg = (ContactGroup)contactGroups.next();
ContactItem ci = cg.getContactItemByJID(user);
if (ci != null) {
ci.setNickname(newNickname);
}
}
}
}
}
/**
* Removes a contact item from the group.
*
* @param item the ContactItem to remove.
*/
private void removeContactFromGroup(ContactItem item) {
String groupName = item.getGroupName();
ContactGroup contactGroup = getContactGroup(groupName);
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(item.getFullJID());
if (entry != null && contactGroup != offlineGroup) {
try {
RosterGroup rosterGroup = roster.getGroup(groupName);
if (rosterGroup != null) {
RosterEntry rosterEntry = rosterGroup.getEntry(entry.getUser());
if (rosterEntry != null) {
rosterGroup.removeEntry(rosterEntry);
}
}
contactGroup.removeContactItem(contactGroup.getContactItemByJID(item.getFullJID()));
checkGroup(contactGroup);
}
catch (Exception e) {
Log.error("Error removing user from contact list.", e);
}
}
}
private void removeContactFromRoster(ContactItem item) {
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(item.getFullJID());
if (entry != null) {
try {
roster.removeEntry(entry);
}
catch (XMPPException e) {
Log.warning("Unable to remove roster entry.", e);
}
}
}
private void removeContactItem(String jid) {
Iterator groups = new ArrayList(getContactGroups()).iterator();
while (groups.hasNext()) {
ContactGroup group = (ContactGroup)groups.next();
ContactItem item = group.getContactItemByJID(jid);
if (item != null) {
group.removeContactItem(item);
checkGroup(group);
}
}
}
public void contactItemClicked(ContactItem item) {
activeItem = item;
clearSelectionList(item);
}
public void contactItemDoubleClicked(ContactItem item) {
activeItem = item;
ChatManager chatManager = SparkManager.getChatManager();
boolean handled = chatManager.fireContactItemDoubleClicked(item);
if (!handled) {
chatManager.activateChat(item.getContactJID(), item.getNickname());
}
clearSelectionList(item);
}
public void contactGroupPopup(MouseEvent e, final ContactGroup group) {
// Do nothing with offline group
if (group == offlineGroup || group == unfiledGroup) {
return;
}
final JPopupMenu popup = new JPopupMenu();
popup.add(addContactMenu);
popup.add(addContactGroupMenu);
popup.addSeparator();
fireContextMenuListenerPopup(popup, group);
JMenuItem delete = new JMenuItem(Res.getString("menuitem.delete"));
JMenuItem rename = new JMenuItem(Res.getString("menuitem.rename"));
if (!group.isSharedGroup()) {
popup.addSeparator();
popup.add(delete);
popup.add(rename);
}
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ok = JOptionPane.showConfirmDialog(group, Res.getString("message.delete.confirmation", group.getGroupName()), Res.getString("title.confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ok == JOptionPane.YES_OPTION) {
String groupName = group.getGroupName();
Roster roster = SparkManager.getConnection().getRoster();
RosterGroup rosterGroup = roster.getGroup(groupName);
if (rosterGroup != null) {
for (RosterEntry entry : rosterGroup.getEntries()) {
try {
rosterGroup.removeEntry(entry);
}
catch (XMPPException e1) {
Log.error("Error removing entry", e1);
}
}
}
// Remove from UI
removeContactGroup(group);
invalidate();
repaint();
}
}
});
rename.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newName = JOptionPane.showInputDialog(group, Res.getString("label.rename.to") + ":", Res.getString("title.rename.roster.group"), JOptionPane.QUESTION_MESSAGE);
if (!ModelUtil.hasLength(newName)) {
return;
}
String groupName = group.getGroupName();
Roster roster = SparkManager.getConnection().getRoster();
RosterGroup rosterGroup = roster.getGroup(groupName);
if (rosterGroup != null) {
removeContactGroup(group);
rosterGroup.setName(newName);
}
}
});
// popup.add(inviteFirstAcceptor);
popup.show(group, e.getX(), e.getY());
activeGroup = group;
}
/**
* Shows popup for right-clicking of ContactItem.
*
* @param e the MouseEvent
* @param item the ContactItem
*/
public void showPopup(MouseEvent e, final ContactItem item) {
if (item.getFullJID() == null) {
return;
}
activeItem = item;
final JPopupMenu popup = new JPopupMenu();
// Add Start Chat Menu
popup.add(chatMenu);
// Add Send File Action
Action sendAction = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
SparkManager.getTransferManager().sendFileTo(item);
}
};
sendAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.DOCUMENT_16x16));
sendAction.putValue(Action.NAME, Res.getString("menuitem.send.a.file"));
if (item.getPresence() != null) {
popup.add(sendAction);
}
popup.addSeparator();
String groupName = item.getGroupName();
ContactGroup contactGroup = getContactGroup(groupName);
// Only show "Remove Contact From Group" if the user belongs to more than one group.
if (!contactGroup.isSharedGroup() && !contactGroup.isOfflineGroup() && contactGroup != unfiledGroup) {
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(item.getFullJID());
if (entry != null) {
int groupCount = entry.getGroups().size();
if (groupCount > 1) {
popup.add(removeContactFromGroupMenu);
}
}
}
// Define remove entry action
Action removeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
removeContactFromRoster(item);
}
};
removeAction.putValue(Action.NAME, Res.getString("menuitem.remove.from.roster"));
removeAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_CIRCLE_DELETE));
// Check if user is in shared group.
boolean isInSharedGroup = false;
Iterator contactGroups = new ArrayList(getContactGroups()).iterator();
while (contactGroups.hasNext()) {
ContactGroup cGroup = (ContactGroup)contactGroups.next();
if (cGroup.isSharedGroup()) {
ContactItem it = cGroup.getContactItemByJID(item.getFullJID());
if (it != null) {
isInSharedGroup = true;
}
}
}
if (!contactGroup.isSharedGroup() && !isInSharedGroup) {
popup.add(removeAction);
}
popup.add(renameMenu);
Action viewProfile = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
VCardManager vcardSupport = SparkManager.getVCardManager();
String jid = item.getFullJID();
vcardSupport.viewProfile(jid, SparkManager.getWorkspace());
}
};
viewProfile.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_PROFILE_IMAGE));
viewProfile.putValue(Action.NAME, Res.getString("menuitem.view.profile"));
popup.add(viewProfile);
popup.addSeparator();
Action lastActivityAction = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
try {
LastActivity activity = LastActivity.getLastActivity(SparkManager.getConnection(), item.getFullJID());
long idleTime = (activity.getIdleTime() * 1000);
String time = ModelUtil.getTimeFromLong(idleTime);
JOptionPane.showMessageDialog(getGUI(), Res.getString("message.idle.for", time), Res.getString("title.last.activity"), JOptionPane.INFORMATION_MESSAGE);
}
catch (XMPPException e1) {
}
}
};
lastActivityAction.putValue(Action.NAME, Res.getString("menuitem.view.last.activity"));
lastActivityAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_USER1_STOPWATCH));
if (contactGroup == offlineGroup) {
popup.add(lastActivityAction);
}
Action subscribeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
String jid = item.getFullJID();
Presence response = new Presence(Presence.Type.subscribe);
response.setTo(jid);
SparkManager.getConnection().sendPacket(response);
}
};
subscribeAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_USER1_INFORMATION));
subscribeAction.putValue(Action.NAME, Res.getString("menuitem.subscribe.to"));
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(item.getFullJID());
if (entry != null && entry.getType() == RosterPacket.ItemType.FROM) {
popup.add(subscribeAction);
}
// Fire Context Menu Listener
fireContextMenuListenerPopup(popup, item);
ContactGroup group = getContactGroup(item.getGroupName());
popup.show(group.getList(), e.getX(), e.getY());
}
public void showPopup(MouseEvent e, final Collection items) {
ContactGroup group = null;
Iterator contactItems = items.iterator();
while (contactItems.hasNext()) {
ContactItem item = (ContactItem)contactItems.next();
group = getContactGroup(item.getGroupName());
break;
}
final JPopupMenu popup = new JPopupMenu();
final JMenuItem sendMessagesMenu = new JMenuItem(Res.getString("menuitem.send.a.message"), SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE));
fireContextMenuListenerPopup(popup, items);
popup.add(sendMessagesMenu);
sendMessagesMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendMessages(items);
}
});
popup.show(group.getList(), e.getX(), e.getY());
}
private void clearSelectionList(ContactItem item) {
// Check for null. In certain cases the event triggering the model might
// not find the selected object.
if (item == null) {
return;
}
final ContactGroup owner = getContactGroup(item.getGroupName());
Iterator groups = new ArrayList(groupList).iterator();
while (groups.hasNext()) {
ContactGroup contactGroup = (ContactGroup)groups.next();
if (owner != contactGroup) {
contactGroup.clearSelection();
}
}
}
private void sendMessages(Collection items) {
InputDialog dialog = new InputDialog();
final String messageText = dialog.getInput(Res.getString("title.broadcast.message"), Res.getString("message.enter.broadcast.message"), SparkRes.getImageIcon(SparkRes.BLANK_IMAGE), SparkManager.getMainWindow());
if (ModelUtil.hasLength(messageText)) {
Iterator contacts = items.iterator();
while (contacts.hasNext()) {
ContactItem item = (ContactItem)contacts.next();
final ContactGroup contactGroup = getContactGroup(item.getGroupName());
contactGroup.clearSelection();
if (item.isAvailable()) {
Message mess = new Message();
mess.setTo(item.getFullJID());
mess.setBody(messageText);
SparkManager.getConnection().sendPacket(mess);
}
}
}
}
// For plugin use only
public void initialize() {
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
// Add Contact List
addContactListToWorkspace();
// Hide top toolbar
SparkManager.getMainWindow().getTopToolBar().setVisible(false);
SwingWorker worker = new SwingWorker() {
public Object construct() {
// Retrieve shared group list.
try {
sharedGroups = SharedGroupManager.getSharedGroups(SparkManager.getConnection());
}
catch (XMPPException e) {
Log.error("Unable to contact shared group info.", e);
}
return "ok";
}
public void finished() {
// Build the initial contact list.
buildContactList();
boolean show = localPreferences.isEmptyGroupsShown();
// Hide all groups initially
showEmptyGroups(show);
// Add a subscription listener.
addSubscriptionListener();
// Load all plugins
SparkManager.getWorkspace().loadPlugins();
}
};
worker.start();
}
public void addSubscriptionListener() {
// Add subscription listener
PacketFilter packetFilter = new PacketTypeFilter(Presence.class);
PacketListener subscribeListener = new PacketListener() {
public void processPacket(Packet packet) {
final Presence presence = (Presence)packet;
if (presence != null && presence.getType() == Presence.Type.subscribe) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
subscriptionRequest(presence.getFrom());
}
});
}
else if (presence != null && presence.getType() == Presence.Type.unsubscribe) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(presence.getFrom());
if (entry != null) {
try {
removeContactItem(presence.getFrom());
roster.removeEntry(entry);
}
catch (XMPPException e) {
Presence unsub = new Presence(Presence.Type.unsubscribed);
unsub.setTo(presence.getFrom());
SparkManager.getConnection().sendPacket(unsub);
Log.error(e);
}
}
}
});
}
else if (presence != null && presence.getType() == Presence.Type.subscribe) {
// Find Contact in Contact List
String jid = StringUtils.parseBareAddress(presence.getFrom());
ContactItem item = getContactItemByJID(jid);
// If item is not in the Contact List, add them.
if (item == null) {
final Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(jid);
if (entry != null) {
String nickname = entry.getName();
if (nickname == null) {
nickname = entry.getUser();
}
item = new ContactItem(nickname, jid);
offlineGroup.addContactItem(item);
offlineGroup.fireContactGroupUpdated();
}
}
}
else if (presence != null && presence.getType() == Presence.Type.unsubscribed) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(presence.getFrom());
if (entry != null) {
try {
removeContactItem(presence.getFrom());
roster.removeEntry(entry);
}
catch (XMPPException e) {
Log.error(e);
}
}
String jid = StringUtils.parseBareAddress(presence.getFrom());
removeContactItem(jid);
}
});
}
else {
initialPresences.add(presence);
int numberOfMillisecondsInTheFuture = 500;
presenceTimer.schedule(new TimerTask() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final Iterator users = new ArrayList(initialPresences).iterator();
while (users.hasNext()) {
Presence userToUpdate = (Presence)users.next();
initialPresences.remove(userToUpdate);
updateUserPresence(userToUpdate);
}
}
});
}
}, numberOfMillisecondsInTheFuture);
}
}
};
SparkManager.getConnection().addPacketListener(subscribeListener, packetFilter);
}
public void shutdown() {
saveState();
}
public boolean canShutDown() {
return true;
}
private void addContactListToWorkspace() {
Workspace workspace = SparkManager.getWorkspace();
workspace.getWorkspacePane().addTab(Res.getString("tab.contacts"), SparkRes.getImageIcon(SparkRes.SMALL_ALL_CHATS_IMAGE), this); //NOTRANS
// Add To Contacts Menu
final JMenu contactsMenu = SparkManager.getMainWindow().getMenuByName(Res.getString("menuitem.contacts"));
JMenuItem addContactsMenu = new JMenuItem("", SparkRes.getImageIcon(SparkRes.USER1_ADD_16x16));
ResourceUtils.resButton(addContactsMenu, Res.getString("menuitem.add.contact"));
ResourceUtils.resButton(addContactGroupMenu, Res.getString("menuitem.add.contact.group"));
contactsMenu.add(addContactsMenu);
contactsMenu.add(addContactGroupMenu);
addContactsMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new RosterDialog().showRosterDialog();
}
});
addContactGroupMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String groupName = JOptionPane.showInputDialog(getGUI(), Res.getString("message.name.of.group") + ":", Res.getString("title.add.new.group"), JOptionPane.QUESTION_MESSAGE);
if (ModelUtil.hasLength(groupName)) {
ContactGroup contactGroup = getContactGroup(groupName);
if (contactGroup == null) {
contactGroup = addContactGroup(groupName);
contactGroup.setVisible(true);
validateTree();
repaint();
}
}
}
});
// Add Toggle Contacts Menu
ResourceUtils.resButton(showHideMenu, Res.getString("menuitem.show.empty.groups"));
contactsMenu.add(showHideMenu);
showHideMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showEmptyGroups(showHideMenu.isSelected());
}
});
// Initialize vcard support
SparkManager.getVCardManager();
}
private void showEmptyGroups(boolean show) {
Iterator contactGroups = getContactGroups().iterator();
while (contactGroups.hasNext()) {
ContactGroup group = (ContactGroup)contactGroups.next();
if (show) {
group.setVisible(true);
}
else {
// Never hide offline group.
if (group != offlineGroup) {
group.setVisible(group.hasAvailableContacts());
}
}
}
localPreferences.setEmptyGroupsShown(show);
showHideMenu.setSelected(show);
}
/**
* Sorts ContactGroups
*/
final Comparator groupComparator = new Comparator() {
public int compare(Object contactGroupOne, Object contactGroup2) {
final ContactGroup group1 = (ContactGroup)contactGroupOne;
final ContactGroup group2 = (ContactGroup)contactGroup2;
return group1.getGroupName().toLowerCase().compareTo(group2.getGroupName().toLowerCase());
}
};
public JPanel getMainPanel() {
return mainPanel;
}
public List<ContactGroup> getContactGroups() {
return groupList;
}
private void subscriptionRequest(final String jid) {
final Roster roster = SparkManager.getConnection().getRoster();
RosterEntry entry = roster.getEntry(jid);
if (entry != null && entry.getType() == RosterPacket.ItemType.TO) {
Presence response = new Presence(Presence.Type.subscribed);
response.setTo(jid);
SparkManager.getConnection().sendPacket(response);
return;
}
String message = Res.getString("message.approve.subscription", UserManager.unescapeJID(jid));
final JPanel layoutPanel = new JPanel();
layoutPanel.setBackground(Color.white);
layoutPanel.setLayout(new GridBagLayout());
WrappedLabel messageLabel = new WrappedLabel();
messageLabel.setText(message);
layoutPanel.add(messageLabel, new GridBagConstraints(0, 0, 5, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
RolloverButton acceptButton = new RolloverButton();
ResourceUtils.resButton(acceptButton, Res.getString("button.accept"));
RolloverButton viewInfoButton = new RolloverButton();
ResourceUtils.resButton(viewInfoButton, Res.getString("button.profile"));
RolloverButton denyButton = new RolloverButton();
ResourceUtils.resButton(denyButton, Res.getString("button.deny"));
layoutPanel.add(acceptButton, new GridBagConstraints(2, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
layoutPanel.add(viewInfoButton, new GridBagConstraints(3, 1, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
layoutPanel.add(denyButton, new GridBagConstraints(4, 1, 1, 1, 0.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
acceptButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SparkManager.getWorkspace().removeAlert(layoutPanel);
Presence response = new Presence(Presence.Type.subscribed);
response.setTo(jid);
SparkManager.getConnection().sendPacket(response);
int ok = JOptionPane.showConfirmDialog(getGUI(), Res.getString("message.add.user"), Res.getString("message.add.to.roster"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (ok == JOptionPane.OK_OPTION) {
RosterDialog rosterDialog = new RosterDialog();
rosterDialog.setDefaultJID(UserManager.unescapeJID(jid));
rosterDialog.showRosterDialog();
}
}
});
denyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SparkManager.getWorkspace().removeAlert(layoutPanel);
// Send subscribed
Presence response = new Presence(Presence.Type.unsubscribe);
response.setTo(jid);
SparkManager.getConnection().sendPacket(response);
}
});
viewInfoButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SparkManager.getVCardManager().viewProfile(jid, getGUI());
}
});
// show dialog
SparkManager.getWorkspace().addAlert(layoutPanel);
SparkManager.getAlertManager().flashWindowStopOnFocus(SparkManager.getMainWindow());
}
public void addContextMenuListener(ContextMenuListener listener) {
contextListeners.add(listener);
}
public void removeContextMenuListener(ContextMenuListener listener) {
contextListeners.remove(listener);
}
public void fireContextMenuListenerPopup(JPopupMenu popup, Object object) {
Iterator listeners = new ArrayList(contextListeners).iterator();
while (listeners.hasNext()) {
ContextMenuListener listener = (ContextMenuListener)listeners.next();
listener.poppingUp(object, popup);
}
}
public JComponent getGUI() {
return this;
}
public ContactGroup getActiveGroup() {
return activeGroup;
}
public Collection getSelectedUsers() {
final List list = new ArrayList();
Iterator contactGroups = getContactGroups().iterator();
while (contactGroups.hasNext()) {
ContactGroup group = (ContactGroup)contactGroups.next();
List items = group.getSelectedContacts();
Iterator itemIterator = items.iterator();
while (itemIterator.hasNext()) {
ContactItem item = (ContactItem)itemIterator.next();
list.add(item);
}
}
return list;
}
private void checkGroup(ContactGroup group) {
if (!group.hasAvailableContacts() && group != offlineGroup && group != unfiledGroup && !showHideMenu.isSelected()) {
group.setVisible(false);
}
}
public void addFileDropListener(FileDropListener listener) {
dndListeners.add(listener);
}
public void removeFileDropListener(FileDropListener listener) {
dndListeners.remove(listener);
}
public void fireFilesDropped(Collection files, ContactItem item) {
final Iterator listeners = new ArrayList(dndListeners).iterator();
while (listeners.hasNext()) {
((FileDropListener)listeners.next()).filesDropped(files, item);
}
}
public void contactItemAdded(ContactItem item) {
fireContactItemAdded(item);
}
public void contactItemRemoved(ContactItem item) {
fireContactItemRemoved(item);
}
/*
Adding ContactListListener support.
*/
public void addContactListListener(ContactListListener listener) {
contactListListeners.add(listener);
}
public void removeContactListListener(ContactListListener listener) {
contactListListeners.remove(listener);
}
public void fireContactItemAdded(ContactItem item) {
final Iterator listeners = new ArrayList(contactListListeners).iterator();
while (listeners.hasNext()) {
((ContactListListener)listeners.next()).contactItemAdded(item);
}
}
public void fireContactItemRemoved(ContactItem item) {
final Iterator listeners = new ArrayList(contactListListeners).iterator();
while (listeners.hasNext()) {
((ContactListListener)listeners.next()).contactItemRemoved(item);
}
}
public void fireContactGroupAdded(ContactGroup group) {
final Iterator listeners = new ArrayList(contactListListeners).iterator();
while (listeners.hasNext()) {
((ContactListListener)listeners.next()).contactGroupAdded(group);
}
}
public void fireContactGroupRemoved(ContactGroup group) {
final Iterator listeners = new ArrayList(contactListListeners).iterator();
while (listeners.hasNext()) {
((ContactListListener)listeners.next()).contactGroupRemoved(group);
}
}
public void uninstall() {
// Do nothing.
}
private void saveState() {
if (props == null) {
return;
}
final Iterator contactGroups = getContactGroups().iterator();
while (contactGroups.hasNext()) {
ContactGroup group = (ContactGroup)contactGroups.next();
props.put(group.getGroupName(), Boolean.toString(group.isCollapsed()));
}
try {
props.store(new FileOutputStream(propertiesFile), "Tracks the state of groups.");
}
catch (IOException e) {
Log.error("Unable to save group properties.", e);
}
}
public void connectionClosed() {
// No reason to reconnect.
connectionClosedOnError(null);
}
private void reconnect(final String message, final boolean conflict) {
// Show MainWindow
SparkManager.getMainWindow().setVisible(true);
// Flash That Window.
SparkManager.getAlertManager().flashWindowStopOnFocus(SparkManager.getMainWindow());
if (reconnectListener == null) {
reconnectListener = new RetryPanel.ReconnectListener() {
public void reconnected() {
clientReconnected();
}
public void cancelled() {
removeAllUsers();
}
};
retryPanel.addReconnectionListener(reconnectListener);
}
workspace.changeCardLayout(RETRY_PANEL);
retryPanel.setDisconnectReason(message);
if (false) {
retryPanel.startTimer();
}
else {
retryPanel.showConflict();
}
}
private void removeAllUsers() {
// Show reconnect panel
workspace.changeCardLayout(RETRY_PANEL);
// Behind the scenes, move everyone to the offline group.
Iterator contactGroups = new ArrayList(getContactGroups()).iterator();
while (contactGroups.hasNext()) {
ContactGroup contactGroup = (ContactGroup)contactGroups.next();
Iterator contactItems = new ArrayList(contactGroup.getContactItems()).iterator();
while (contactItems.hasNext()) {
ContactItem item = (ContactItem)contactItems.next();
contactGroup.removeContactItem(item);
}
}
}
public void clientReconnected() {
XMPPConnection con = SparkManager.getConnection();
if (con.isConnected()) {
// Send Available status
final Presence presence = SparkManager.getWorkspace().getStatusBar().getPresence();
SparkManager.getSessionManager().changePresence(presence);
final Roster roster = con.getRoster();
for (RosterEntry entry : roster.getEntries()) {
updateUserPresence(roster.getPresence(entry.getUser()));
}
}
workspace.changeCardLayout(Workspace.WORKSPACE_PANE);
}
public void connectionClosedOnError(final Exception ex) {
String errorMessage = Res.getString("message.disconnected.error");
boolean conflictError = false;
if (ex != null && ex instanceof XMPPException) {
XMPPException xmppEx = (XMPPException)ex;
StreamError error = xmppEx.getStreamError();
String reason = error.getCode();
if ("conflict".equals(reason)) {
errorMessage = Res.getString("message.disconnected.conflict.error");
conflictError = true;
}
else {
errorMessage = Res.getString("message.general.error", reason);
}
}
final String message = errorMessage;
final boolean conflicted = conflictError;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
reconnect(message, conflicted);
}
});
}
public void reconnectingIn(int i) {
}
public void reconectionSuccessful() {
}
public void reconnectionFailed(Exception exception) {
}
} |
package cgeo.geocaching.connector.gc;
import java.util.regex.Pattern;
public final class GCConstants {
/** Live Map */
public final static String URL_LIVE_MAP = "http:
/** Live Map pop-up */
public final static String URL_LIVE_MAP_DETAILS = "http:
/** Caches in a tile */
public final static String URL_MAP_INFO = "http:
/** Tile itself */
public final static String URL_MAP_TILE = "http:
/**
* Patterns for parsing the result of a (detailed) search
*/
public final static Pattern PATTERN_HINT = Pattern.compile("<div id=\"div_hint\"[^>]*>(.*?)</div>");
public final static Pattern PATTERN_DESC = Pattern.compile("<span id=\"ctl00_ContentBody_LongDescription\">(.*?)</span>\\s*</div>\\s*<p>\\s*</p>\\s*<p id=\"ctl00_ContentBody_hints\">");
public final static Pattern PATTERN_SHORTDESC = Pattern.compile("<span id=\"ctl00_ContentBody_ShortDescription\">(.*?)</span>\\s*</div>");
public final static Pattern PATTERN_GEOCODE = Pattern.compile("class=\"CoordInfoCode\">(GC[0-9A-Z]+)</span>");
public final static Pattern PATTERN_CACHEID = Pattern.compile("/seek/log\\.aspx\\?ID=(\\d+)");
public final static Pattern PATTERN_GUID = Pattern.compile(Pattern.quote("&wid=") + "([0-9a-z\\-]+)" + Pattern.quote("&"));
public final static Pattern PATTERN_SIZE = Pattern.compile("<div class=\"CacheSize[^\"]*\">[^<]*<p[^>]*>[^S]*Size[^:]*:[^<]*<span[^>]*>[^<]*<img src=\"[^\"]*/icons/container/[a-z_]+\\.gif\" alt=\"\\w+: ([^\"]+)\"[^>]*>[^<]*<small>[^<]*</small>[^<]*</span>[^<]*</p>");
public final static Pattern PATTERN_LATLON = Pattern.compile("<span id=\"uxLatLon\" style=\"font-weight:bold;\"[^>]*>(.*?)</span>");
public final static Pattern PATTERN_LATLON_ORIG = Pattern.compile("\\{\"isUserDefined\":true[^}]+?\"oldLatLngDisplay\":\"([^\"]+)\"\\}");
public final static Pattern PATTERN_LOCATION = Pattern.compile(Pattern.quote("<span id=\"ctl00_ContentBody_Location\">In ") + "(?:<a href=[^>]*>)?(.*?)<");
public final static Pattern PATTERN_PERSONALNOTE = Pattern.compile("<p id=\"cache_note\"[^>]*>(.*?)</p>");
public final static Pattern PATTERN_NAME = Pattern.compile("<span id=\"ctl00_ContentBody_CacheName\">(.*?)</span>");
public final static Pattern PATTERN_DIFFICULTY = Pattern.compile("<span id=\"ctl00_ContentBody_uxLegendScale\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\"");
public final static Pattern PATTERN_TERRAIN = Pattern.compile("<span id=\"ctl00_ContentBody_Localize[\\d]+\"[^>]*>[^<]*<img src=\"[^\"]*/images/stars/stars([0-9_]+)\\.gif\"");
public final static Pattern PATTERN_OWNERREAL = Pattern.compile("<a id=\"ctl00_ContentBody_uxFindLinksHiddenByThisUser\" href=\"[^\"]*/seek/nearest\\.aspx\\?u=(.*?)\"");
public final static Pattern PATTERN_FOUND = Pattern.compile("<a id=\"ctl00_ContentBody_hlFoundItLog\"[^<]*<img src=\".*/images/stockholm/16x16/check\\.gif\"[^>]*>[^<]*</a>[^<]*</p>");
public final static Pattern PATTERN_FOUND_ALTERNATIVE = Pattern.compile("<div class=\"StatusInformationWidget FavoriteWidget\"");
public final static Pattern PATTERN_OWNER = Pattern.compile("<span class=\"minorCacheDetails\">[^<]+<a href=\"[^\"]+\">([^<]+)</a></span>");
public final static Pattern PATTERN_TYPE = Pattern.compile("<img src=\"[^\"]*/WptTypes/\\d+\\.gif\" alt=\"([^\"]+?)\" title=\"[^\"]+\" width=\"32\" height=\"32\"");
public final static Pattern PATTERN_HIDDEN = Pattern.compile("<span class=\"minorCacheDetails\">\\W*Hidden[\\s:]*([^<]+?)</span>");
public final static Pattern PATTERN_HIDDENEVENT = Pattern.compile("Event\\s*Date\\s*:\\s*([^<]+)</span>", Pattern.DOTALL);
public final static Pattern PATTERN_FAVORITE = Pattern.compile("<img src=\"/images/icons/icon_favDelete.png\" alt=\"Remove from your Favorites\" title=\"Remove from your Favorites\" />");
public final static Pattern PATTERN_FAVORITECOUNT = Pattern.compile("<a id=\"uxFavContainerLink\"[^>]+>[^<]*<div[^<]*<span class=\"favorite-value\">\\D*([0-9]+?)</span>");
public final static Pattern PATTERN_COUNTLOGS = Pattern.compile("<span id=\"ctl00_ContentBody_lblFindCounts\"><p(.+?)</p></span>");
public final static Pattern PATTERN_LOGBOOK = Pattern.compile("initalLogs = (\\{.+\\});");
/** Two groups ! */
public final static Pattern PATTERN_COUNTLOG = Pattern.compile("<img src=\"/images/icons/([a-z_]+)\\.gif\"[^>]+> (\\d*[,.]?\\d+)");
public static final Pattern PATTERN_PREMIUMMEMBERS = Pattern.compile("<p class=\"Warning NoBottomSpacing\">This is a Premium Member Only cache.</p>");
public final static Pattern PATTERN_ATTRIBUTES = Pattern.compile("<h3 class=\"WidgetHeader\">[^<]*<img[^>]+>\\W*Attributes[^<]*</h3>[^<]*<div class=\"WidgetBody\">((?:[^<]*<img src=\"[^\"]+\" alt=\"[^\"]+\"[^>]*>)+?)[^<]*<p");
/** Two groups ! */
public final static Pattern PATTERN_ATTRIBUTESINSIDE = Pattern.compile("[^<]*<img src=\"([^\"]+)\" alt=\"([^\"]+?)\"");
public final static Pattern PATTERN_SPOILERS = Pattern.compile("<p class=\"NoPrint\">\\s+((?:<a href=\"http://img\\.geocaching\\.com/cache/[^.]+\\.jpg\"[^>]+><img class=\"StatusIcon\"[^>]+><span>[^<]+</span></a><br />(?:[^<]+<br /><br />)?)+)\\s+</p>");
public final static Pattern PATTERN_SPOILERSINSIDE = Pattern.compile("<a href=\"(http://img\\.geocaching\\.com/cache/[^.]+\\.jpg)\"[^>]+><img class=\"StatusIcon\"[^>]+><span>([^<]+)</span></a><br />(?:([^<]+)<br /><br />)?");
public final static Pattern PATTERN_INVENTORY = Pattern.compile("<span id=\"ctl00_ContentBody_uxTravelBugList_uxInventoryLabel\">\\W*Inventory[^<]*</span>[^<]*</h3>[^<]*<div class=\"WidgetBody\">([^<]*<ul>(([^<]*<li>[^<]*<a href=\"[^\"]+\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>[^<]+<\\/span>[^<]*<\\/a>[^<]*<\\/li>)+)[^<]*<\\/ul>)?");
public final static Pattern PATTERN_INVENTORYINSIDE = Pattern.compile("[^<]*<li>[^<]*<a href=\"[a-z0-9\\-\\_\\.\\?\\/\\:\\@]*\\/track\\/details\\.aspx\\?guid=([0-9a-z\\-]+)[^\"]*\"[^>]*>[^<]*<img src=\"[^\"]+\"[^>]*>[^<]*<span>([^<]+)<\\/span>[^<]*<\\/a>[^<]*<\\/li>");
public final static Pattern PATTERN_WATCHLIST = Pattern.compile("icon_stop_watchlist.gif");
// Info box top-right
public static final Pattern PATTERN_LOGIN_NAME = Pattern.compile("\"SignedInProfileLink\">([^<]+)</a>");
public static final Pattern PATTERN_MEMBER_STATUS = Pattern.compile("<span id=\"ctl00_litPMLevel\">([^<]+)</span>");
/** Use replaceAll("[,.]","") on the resulting string before converting to an int */
public static final Pattern PATTERN_CACHES_FOUND = Pattern.compile("title=\"Caches Found\"[\\s\\w=\"/.]*/>\\s*([\\d,.]+)");
public static final Pattern PATTERN_AVATAR_IMAGE_PROFILE_PAGE = Pattern.compile("<img src=\"(http://img.geocaching.com/user/avatar/[0-9a-f-]+\\.jpg)\"[^>]*\\salt=\"Avatar\"");
public static final Pattern PATTERN_LOGIN_NAME_LOGIN_PAGE = Pattern.compile("<h4>Success:</h4> <p>You are logged in as[^<]*<strong><span id=\"ctl00_ContentBody_lbUsername\"[^>]*>([^<]+)[^<]*</span>");
public static final Pattern PATTERN_CUSTOMDATE = Pattern.compile("<option selected=\"selected\" value=\"([ /Mdy-]+)\">");
/**
* Patterns for parsing trackables
*/
public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>");
public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item.[^<]*</span>");
public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("<h2[^>]*>(?:[^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_ORIGIN = Pattern.compile("<dt>\\W*Origin:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugOrigin\">([^<]+)<\\/span>[^<]*</dd>");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_SPOTTEDCACHE = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" title=\"[^\"]*\" href=\"[^\"]*/seek/cache_details.aspx\\?guid=([a-z0-9\\-]+)\">In ([^<]+)</a>[^<]*</dd>");
/** Two groups ! */
public final static Pattern PATTERN_TRACKABLE_SPOTTEDUSER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_SPOTTEDUNKNOWN = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_SPOTTEDOWNER = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>");
public final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>", Pattern.DOTALL);
/** Four groups */
public final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">");
public final static Pattern PATTERN_TRACKABLE_ICON = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_TRACKABLE_TYPE = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_TRACKABLE_DISTANCE = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)");
public final static Pattern PATTERN_TRACKABLE_LOG = Pattern.compile("<tr class=\"Data.+?src=\"/images/icons/([^.]+)\\.gif[^>]+> ([^<]+)</td>.+?guid.+?>([^<]+)</a>.+?(?:guid=([^\"]+)\">(<span class=\"Strike\">)?([^<]+)</.+?)?<td colspan=\"4\">(.+?)(?:<ul.+?ul>)?\\s*</td>\\s*</tr>");
public final static Pattern PATTERN_TRACKABLE_LOG_IMAGES = Pattern.compile(".+?<li><a href=\"([^\"]+)\".+?LogImgTitle.+?>([^<]+)</");
/**
* Patterns for parsing the result of a search (next)
*/
public final static Pattern PATTERN_SEARCH_TYPE = Pattern.compile("<td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=[^\"]+\"[^>]+>[^<]*<img src=\"[^\"]*/images/wpttypes/[^.]+\\.gif\" alt=\"([^\"]+)\" title=\"[^\"]+\"[^>]*>[^<]*</a>");
public final static Pattern PATTERN_SEARCH_GUIDANDDISABLED = Pattern.compile("<img src=\"[^\"]*/images/wpttypes/[^>]*>[^<]*</a></td><td class=\"Merge\">[^<]*<a href=\"[^\"]*/seek/cache_details\\.aspx\\?guid=([a-z0-9\\-]+)\" class=\"lnk([^\"]*)\">([^<]*<span>)?([^<]*)(</span>[^<]*)?</a>[^<]+<br />([^<]*)<span[^>]+>([^<]*)</span>([^<]*<img[^>]+>)?[^<]*<br />[^<]*</td>");
/** Two groups **/
public final static Pattern PATTERN_SEARCH_TRACKABLES = Pattern.compile("<a id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxTravelBugList\" class=\"tblist\" data-tbcount=\"([0-9]+)\" data-id=\"[^\"]*\"[^>]*>(.*)</a>");
/** Second group used */
public final static Pattern PATTERN_SEARCH_TRACKABLESINSIDE = Pattern.compile("(<img src=\"[^\"]+\" alt=\"([^\"]+)\" title=\"[^\"]*\" />[^<]*)");
public final static Pattern PATTERN_SEARCH_DIRECTION = Pattern.compile("<img id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxDistanceAndHeading\" title=\"[^\"]*\" src=\"[^\"]*/seek/CacheDir\\.ashx\\?k=([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_SEARCH_GEOCODE = Pattern.compile("\\|\\W*(GC[0-9A-Z]+)[^\\|]*\\|");
public final static Pattern PATTERN_SEARCH_ID = Pattern.compile("name=\"CID\"[^v]*value=\"([0-9]+)\"");
public final static Pattern PATTERN_SEARCH_FAVORITE = Pattern.compile("<span id=\"ctl00_ContentBody_dlResults_ctl[0-9]+_uxFavoritesValue\" title=\"[^\"]*\" class=\"favorite-rank\">([0-9]+)</span>");
public final static Pattern PATTERN_SEARCH_TOTALCOUNT = Pattern.compile("<td class=\"PageBuilderWidget\"><span>Total Records[^<]*<b>(\\d+)<\\/b>");
public final static Pattern PATTERN_SEARCH_RECAPTCHA = Pattern.compile("<script[^>]*src=\"[^\"]*/recaptcha/api/challenge\\?k=([^\"]+)\"[^>]*>");
public final static Pattern PATTERN_SEARCH_RECAPTCHACHALLENGE = Pattern.compile("challenge : '([^']+)'");
/**
* Patterns for waypoints
*/
public final static Pattern PATTERN_WPTYPE = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg");
public final static Pattern PATTERN_WPPREFIXORLOOKUPORLATLON = Pattern.compile(">([^<]*<[^>]+>)?([^<]+)(<[^>]+>[^<]*)?<\\/td>");
public final static Pattern PATTERN_WPNAME = Pattern.compile(">[^<]*<a[^>]+>([^<]*)<\\/a>");
public final static Pattern PATTERN_WPNOTE = Pattern.compile("colspan=\"6\">(.*)<\\/td>");
/**
* Patterns for different purposes
*/
/** replace linebreak and paragraph tags */
public final static Pattern PATTERN_LINEBREAK = Pattern.compile("<(br|p)[^>]*>");
public final static Pattern PATTERN_TYPEBOX = Pattern.compile("<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$ddLogType\" id=\"ctl00_ContentBody_LogBookPanel1_ddLogType\"[^>]*>"
+ "(([^<]*<option[^>]*>[^<]+</option>)+)[^<]*</select>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_TYPE2 = Pattern.compile("<option( selected=\"selected\")? value=\"(\\d+)\">[^<]+</option>", Pattern.CASE_INSENSITIVE);
// FIXME: pattern is over specified
public final static Pattern PATTERN_TRACKABLE = Pattern.compile("<tr id=\"ctl00_ContentBody_LogBookPanel1_uxTrackables_repTravelBugs_ctl[0-9]+_row\"[^>]*>"
+ "[^<]*<td>[^<]*<a href=\"[^\"]+\">([A-Z0-9]+)</a>[^<]*</td>[^<]*<td>([^<]+)</td>[^<]*<td>"
+ "[^<]*<select name=\"ctl00\\$ContentBody\\$LogBookPanel1\\$uxTrackables\\$repTravelBugs\\$ctl([0-9]+)\\$ddlAction\"[^>]*>"
+ "([^<]*<option value=\"([0-9]+)(_[a-z]+)?\">[^<]+</option>)+"
+ "[^<]*</select>[^<]*</td>[^<]*</tr>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_MAINTENANCE = Pattern.compile("<span id=\"ctl00_ContentBody_LogBookPanel1_lbConfirm\"[^>]*>([^<]*<font[^>]*>)?([^<]+)(</font>[^<]*)?</span>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_OK1 = Pattern.compile("<h2[^>]*>[^<]*<span id=\"ctl00_ContentBody_lbHeading\"[^>]*>[^<]*</span>[^<]*</h2>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_OK2 = Pattern.compile("<div id=[\"|']ctl00_ContentBody_LogBookPanel1_ViewLogPanel[\"|']>", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_VIEWSTATEFIELDCOUNT = Pattern.compile("id=\"__VIEWSTATEFIELDCOUNT\"[^(value)]+value=\"(\\d+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_VIEWSTATES = Pattern.compile("id=\"__VIEWSTATE(\\d*)\"[^(value)]+value=\"([^\"]+)\"[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public final static Pattern PATTERN_USERTOKEN2 = Pattern.compile("userToken\\s*=\\s*'([^']+)'");
/**
* Patterns for GC and TB codes
*/
public final static Pattern PATTERN_GC_CODE = Pattern.compile("GC[0-9A-Z]+", Pattern.CASE_INSENSITIVE);
public final static Pattern PATTERN_TB_CODE = Pattern.compile("TB[0-9A-Z]+", Pattern.CASE_INSENSITIVE);
/** Live Map since 14.02.2012 */
public final static Pattern PATTERN_USERSESSION = Pattern.compile("UserSession\\('([^']+)'");
public final static Pattern PATTERN_SESSIONTOKEN = Pattern.compile("sessionToken:'([^']+)'");
public final static String STRING_PREMIUMONLY_2 = "Sorry, the owner of this listing has made it viewable to Premium Members only.";
public final static String STRING_PREMIUMONLY_1 = "has chosen to make this cache listing visible to Premium Members only.";
public final static String STRING_UNPUBLISHED_OWNER = "Cache is Unpublished";
public final static String STRING_UNPUBLISHED_OTHER = "you cannot view this cache listing until it has been published";
public final static String STRING_UNKNOWN_ERROR = "An Error Has Occurred";
public final static String STRING_CACHEINFORMATIONTABLE = "<div id=\"ctl00_ContentBody_CacheInformationTable\" class=\"CacheInformationTable\">";
public final static String STRING_DISABLED = "<li>This cache is temporarily unavailable.";
public final static String STRING_ARCHIVED = "<li>This cache has been archived,";
public final static String STRING_CACHEDETAILS = "id=\"cacheDetails\"";
/** Number of logs to retrieve from GC.com */
public final static int NUMBER_OF_LOGS = 35;
private GCConstants() {
// this class shall not have instances
}
} |
package dr.evomodel.coalescent;
import dr.evolution.tree.*;
import dr.evolution.util.*;
import dr.inference.distribution.ParametricDistributionModel;
import dr.math.UnivariateFunction;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* Simulates a set of coalescent intervals given a demographic model.
*
* @author Alexei Drummond
* @version $Id: CoalescentSimulator.java,v 1.43 2005/10/27 10:40:48 rambaut Exp $
*/
public class CoalescentSimulator {
public static final String COALESCENT_TREE = "coalescentTree";
public static final String COALESCENT_SIMULATOR = "coalescentSimulator";
public static final String RESCALE_HEIGHT = "rescaleHeight";
public static final String ROOT_HEIGHT = "rootHeight";
public static final String CONSTRAINED_TAXA = "constrainedTaxa";
public static final String TMRCA_CONSTRAINT = "tmrca";
public static final String IS_MONOPHYLETIC = "monophyletic";
/**
* Simulates a coalescent tree from a set of subtrees.
*/
public CoalescentSimulator() {
}
/**
* Simulates a coalescent tree from a set of subtrees.
*
* @param subtrees an array of tree to be used as subtrees
* @param model the demographic model to use
* @param rootHeight an optional root height with which to scale the whole tree
* @param preserveSubtrees true of subtrees should be preserved
* @return a simulated coalescent tree
*/
public SimpleTree simulateTree(Tree[] subtrees, DemographicModel model, double rootHeight, boolean preserveSubtrees) {
SimpleNode[] roots = new SimpleNode[subtrees.length];
SimpleTree tree;
dr.evolution.util.Date mostRecent = null;
for (Tree subtree : subtrees) {
Date date = Tree.Utils.findMostRecentDate(subtree);
if ((date != null) && (mostRecent == null || date.after(mostRecent))) {
mostRecent = date;
}
}
if (mostRecent != null) {
TimeScale timeScale = new TimeScale(mostRecent.getUnits(), true, mostRecent.getAbsoluteTimeValue());
double time0 = timeScale.convertTime(mostRecent.getTimeValue(), mostRecent);
for (Tree subtree : subtrees) {
Date date = Tree.Utils.findMostRecentDate(subtree);
if (date != null) {
double diff = timeScale.convertTime(date.getTimeValue(), date) - time0;
for (int j = 0; j < subtree.getNodeCount(); j++) {
NodeRef node = subtree.getNode(j);
((SimpleTree) subtree).setNodeHeight(node, subtree.getNodeHeight(node) + diff);
}
}
}
}
for (int i = 0; i < roots.length; i++) {
roots[i] = new SimpleNode(subtrees[i], subtrees[i].getRoot());
}
// if just one taxonList then finished
if (roots.length == 1) {
tree = new SimpleTree(roots[0]);
} else {
tree = new SimpleTree(simulator.simulateCoalescent(roots, model.getDemographicFunction()));
}
if (rootHeight > 0.0) {
if (preserveSubtrees) {
limitNodes(tree, rootHeight);
} else {
attemptToScaleTree(tree, rootHeight);
}
}
return tree;
}
/**
* Simulates a coalescent tree, given a taxon list.
*
* @param taxa the set of taxa to simulate a coalescent tree between
* @param model the demographic model to use
* @return a simulated coalescent tree
*/
public SimpleTree simulateTree(TaxonList taxa, DemographicModel model) {
return simulator.simulateTree(taxa, model.getDemographicFunction());
}
/**
* Clip nodes height above limit.
*
* @param tree to clip
* @param limit height limit
*/
private static void limitNodes(MutableTree tree, double limit) {
for (int i = 0; i < tree.getInternalNodeCount(); i++) {
NodeRef n = tree.getInternalNode(i);
if (tree.getNodeHeight(n) > limit) {
tree.setNodeHeight(n, limit);
}
}
MutableTree.Utils.correctHeightsForTips(tree);
}
private static void attemptToScaleTree(MutableTree tree, double rootHeight) {
// avoid empty tree
if( tree.getRoot() == null ) return;
double scale = rootHeight / tree.getNodeHeight(tree.getRoot());
for (int i = 0; i < tree.getInternalNodeCount(); i++) {
NodeRef n = tree.getInternalNode(i);
tree.setNodeHeight(n, tree.getNodeHeight(n) * scale);
}
MutableTree.Utils.correctHeightsForTips(tree);
}
static class TaxaConstraint {
final TaxonList taxons;
final double lower;
final boolean isMonophyletic;
double upper;
TaxaConstraint(TaxonList taxons, ParametricDistributionModel p, boolean isMono) {
this.taxons = taxons;
this.isMonophyletic = isMono;
if (p != null) {
final UnivariateFunction univariateFunction = p.getProbabilityDensityFunction();
lower = univariateFunction.getLowerBound();
upper = univariateFunction.getUpperBound();
} else {
lower = 0;
upper = Double.POSITIVE_INFINITY;
}
}
TaxaConstraint(TaxonList taxons, double low, double high, boolean isMono) {
this.taxons = taxons;
this.isMonophyletic = isMono;
upper = high;
lower = low;
}
public boolean realLimits() {
return lower != 0 || upper != Double.POSITIVE_INFINITY;
}
}
static private int sizeOfIntersection(TaxonList tl1, TaxonList tl2) {
int nIn = 0;
for (int j = 0; j < tl1.getTaxonCount(); ++j) {
if (tl2.getTaxonIndex(tl1.getTaxon(j)) >= 0) {
++nIn;
}
}
return nIn;
}
static private boolean contained(TaxonList taxons, TaxonList taxons1) {
return sizeOfIntersection(taxons, taxons1) == taxons.getTaxonCount();
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return COALESCENT_TREE;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
CoalescentSimulator simulator = new CoalescentSimulator();
DemographicModel demoModel = (DemographicModel) xo.getChild(DemographicModel.class);
List<TaxonList> taxonLists = new ArrayList<TaxonList>();
List<Tree> subtrees = new ArrayList<Tree>();
double rootHeight = -1;
if (xo.hasAttribute(ROOT_HEIGHT)) {
rootHeight = xo.getDoubleAttribute(ROOT_HEIGHT);
}
if (xo.hasAttribute(RESCALE_HEIGHT)) {
rootHeight = xo.getDoubleAttribute(RESCALE_HEIGHT);
}
// should have one child that is node
for (int i = 0; i < xo.getChildCount(); i++) {
final Object child = xo.getChild(i);
// AER - swapped the order of these round because Trees are TaxonLists...
if (child instanceof Tree) {
subtrees.add((Tree) child);
} else if (child instanceof TaxonList) {
taxonLists.add((TaxonList) child);
} else if (xo.getChildName(i).equals(CONSTRAINED_TAXA)) {
rootHeight = -1; // ignore it? should we errror?
XMLObject constrainedTaxa = (XMLObject) child;
// all taxa
final TaxonList taxa = (TaxonList) constrainedTaxa.getChild(TaxonList.class);
List<TaxaConstraint> constraints = new ArrayList<TaxaConstraint>();
final String setsNotCompatibleMessage = "taxa sets not compatible";
// pick up all constraints. order in partial order, where taxa_1 @in taxa_2 implies
// taxa_1 is before taxa_2.
for (int nc = 0; nc < constrainedTaxa.getChildCount(); ++nc) {
final Object object = constrainedTaxa.getChild(nc);
if (object instanceof XMLObject) {
final XMLObject constraint = (XMLObject) object;
if (constraint.getName().equals(TMRCA_CONSTRAINT)) {
TaxonList taxaSubSet = (TaxonList) constraint.getChild(TaxonList.class);
ParametricDistributionModel dist =
(ParametricDistributionModel) constraint.getChild(ParametricDistributionModel.class);
boolean isMono = true;
if (constraint.hasAttribute(IS_MONOPHYLETIC)) {
isMono = constraint.getBooleanAttribute(IS_MONOPHYLETIC);
}
final TaxaConstraint taxaConstraint = new TaxaConstraint(taxaSubSet, dist, isMono);
int insertPoint;
for (insertPoint = 0; insertPoint < constraints.size(); ++insertPoint) {
// if new <= constraints[insertPoint] insert before insertPoint
final TaxaConstraint iConstraint = constraints.get(insertPoint);
if (iConstraint.isMonophyletic) {
if (!taxaConstraint.isMonophyletic) {
continue;
}
final TaxonList taxonsip = iConstraint.taxons;
final int nIn = sizeOfIntersection(taxonsip, taxaSubSet);
if (nIn == taxaSubSet.getTaxonCount()) {
break;
}
if (nIn > 0 && nIn != taxonsip.getTaxonCount()) {
throw new XMLParseException(setsNotCompatibleMessage);
}
} else {
// reached non mono area
if (!taxaConstraint.isMonophyletic) {
if (iConstraint.upper >= taxaConstraint.upper) {
break;
}
} else {
break;
}
}
}
constraints.add(insertPoint, taxaConstraint);
}
}
}
final int nConstraints = constraints.size();
if (nConstraints == 0) {
taxonLists.add(taxa);
} else {
for (int nc = 0; nc < nConstraints; ++nc) {
TaxaConstraint cnc = constraints.get(nc);
if (!cnc.isMonophyletic) {
for (int nc1 = nc - 1; nc1 >= 0; --nc1) {
TaxaConstraint cnc1 = constraints.get(nc1);
int x = sizeOfIntersection(cnc.taxons, cnc1.taxons);
if (x > 0) {
Taxa combinedTaxa = new Taxa(cnc.taxons);
combinedTaxa.addTaxa(cnc1.taxons);
cnc = new TaxaConstraint(combinedTaxa, cnc.lower, cnc.upper, cnc.isMonophyletic);
constraints.set(nc, cnc);
}
}
}
}
// determine upper bound for each set.
double[] upper = new double[nConstraints];
for (int nc = nConstraints - 1; nc >= 0; --nc) {
final TaxaConstraint cnc = constraints.get(nc);
if (cnc.realLimits()) {
upper[nc] = cnc.upper;
} else {
upper[nc] = Double.POSITIVE_INFINITY;
}
}
for (int nc = nConstraints - 1; nc >= 0; --nc) {
final TaxaConstraint cnc = constraints.get(nc);
if (upper[nc] < Double.POSITIVE_INFINITY) {
for (int nc1 = nc - 1; nc1 >= 0; --nc1) {
final TaxaConstraint cnc1 = constraints.get(nc1);
if (contained(cnc1.taxons, cnc.taxons)) {
upper[nc1] = Math.min(upper[nc1], upper[nc]);
if (cnc1.realLimits() && cnc1.lower > upper[nc1]) {
throw new XMLParseException(setsNotCompatibleMessage);
}
break;
}
}
}
}
// collect subtrees here
List<Tree> st = new ArrayList<Tree>();
for (int nc = 0; nc < constraints.size(); ++nc) {
final TaxaConstraint nxt = constraints.get(nc);
// collect all previously built subtrees which are a subset of taxa set to be added
List<Tree> subs = new ArrayList<Tree>();
Taxa newTaxons = new Taxa(nxt.taxons);
for (int k = 0; k < st.size(); ++k) {
final Tree stk = st.get(k);
int x = sizeOfIntersection(stk, nxt.taxons);
if (x == st.get(k).getTaxonCount()) {
final Tree tree = st.remove(k);
--k;
subs.add(tree);
newTaxons.removeTaxa(tree);
}
}
SimpleTree tree = simulator.simulateTree(newTaxons, demoModel);
final double lower = nxt.realLimits() ? nxt.lower : 0;
if (upper[nc] < Double.MAX_VALUE) {
attemptToScaleTree(tree, (lower + upper[nc]) / 2);
}
if (subs.size() > 0) {
if (tree.getTaxonCount() > 0) subs.add(tree);
double h = -1;
if (upper[nc] < Double.MAX_VALUE) {
for (Tree t : subs) {
h = Math.max(h, t.getNodeHeight(t.getRoot()));
}
h = (h + upper[nc]) / 2;
}
tree = simulator.simulateTree(subs.toArray(new Tree[subs.size()]), demoModel, h, true);
}
st.add(tree);
}
// add a taxon list for remaining taxa
final Taxa list = new Taxa();
for (int j = 0; j < taxa.getTaxonCount(); ++j) {
Taxon taxonj = taxa.getTaxon(j);
for (Tree aSt : st) {
if (aSt.getTaxonIndex(taxonj) >= 0) {
taxonj = null;
break;
}
}
if (taxonj != null) {
list.addTaxon(taxonj);
}
}
if (list.getTaxonCount() > 0) {
taxonLists.add(list);
}
if (st.size() > 1) {
final Tree t = simulator.simulateTree(st.toArray(new Tree[st.size()]), demoModel, -1, false);
subtrees.add(t);
} else {
subtrees.add(st.get(0));
}
}
}
}
if (taxonLists.size() == 0) {
if (subtrees.size() == 1) {
return subtrees.get(0);
}
throw new XMLParseException("Expected at least one taxonList or two subtrees in "
+ getParserName() + " element.");
}
try {
Tree[] trees = new Tree[taxonLists.size() + subtrees.size()];
// simulate each taxonList separately
for (int i = 0; i < taxonLists.size(); i++) {
trees[i] = simulator.simulateTree(taxonLists.get(i), demoModel);
}
// add the preset trees
for (int i = 0; i < subtrees.size(); i++) {
trees[i + taxonLists.size()] = subtrees.get(i);
}
return simulator.simulateTree(trees, demoModel, rootHeight, true);
} catch (IllegalArgumentException iae) {
throw new XMLParseException(iae.getMessage());
}
} |
package cgeo.geocaching.maps.mapsforge.v6;
import cgeo.geocaching.AbstractDialogFragment;
import cgeo.geocaching.AbstractDialogFragment.TargetInfo;
import cgeo.geocaching.CacheListActivity;
import cgeo.geocaching.CachePopup;
import cgeo.geocaching.CompassActivity;
import cgeo.geocaching.EditWaypointActivity;
import cgeo.geocaching.Intents;
import cgeo.geocaching.R;
import cgeo.geocaching.SearchResult;
import cgeo.geocaching.WaypointPopup;
import cgeo.geocaching.activity.AbstractActionBarActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.connector.gc.GCMap;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.CoordinatesType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.maps.LivemapStrategy;
import cgeo.geocaching.maps.MapMode;
import cgeo.geocaching.maps.MapOptions;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.MapState;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.interfaces.OnMapDragListener;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapSource;
import cgeo.geocaching.maps.mapsforge.v6.caches.CachesBundle;
import cgeo.geocaching.maps.mapsforge.v6.caches.GeoitemRef;
import cgeo.geocaching.maps.mapsforge.v6.layers.HistoryLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.ITileLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.NavigationLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.PositionLayer;
import cgeo.geocaching.maps.mapsforge.v6.layers.TapHandlerLayer;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.maps.routing.RoutingMode;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.DisposableHandler;
import cgeo.geocaching.utils.Formatter;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.functions.Action1;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources.NotFoundException;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import butterknife.ButterKnife;
import io.reactivex.disposables.CompositeDisposable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.core.util.Parameters;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.graphics.AndroidResourceBitmap;
import org.mapsforge.map.android.input.MapZoomControls;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.layer.Layers;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.DisplayModel;
import org.mapsforge.map.rendertheme.ExternalRenderTheme;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderTheme;
import org.mapsforge.map.rendertheme.XmlRenderThemeMenuCallback;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleLayer;
import org.mapsforge.map.rendertheme.XmlRenderThemeStyleMenu;
import org.mapsforge.map.rendertheme.rule.RenderThemeHandler;
import org.xmlpull.v1.XmlPullParserException;
@SuppressLint("ClickableViewAccessibility")
public class NewMap extends AbstractActionBarActivity implements XmlRenderThemeMenuCallback, SharedPreferences.OnSharedPreferenceChangeListener {
private MfMapView mapView;
private TileCache tileCache;
private ITileLayer tileLayer;
private HistoryLayer historyLayer;
private PositionLayer positionLayer;
private NavigationLayer navigationLayer;
private CachesBundle caches;
private final MapHandlers mapHandlers = new MapHandlers(new TapHandler(this), new DisplayHandler(this), new ShowProgressHandler(this));
private XmlRenderThemeStyleMenu styleMenu;
private SharedPreferences sharedPreferences;
private DistanceView distanceView;
private ArrayList<Location> trailHistory = null;
private String targetGeocode = null;
private Geopoint lastNavTarget = null;
private final Queue<String> popupGeocodes = new ConcurrentLinkedQueue<>();
private ProgressDialog waitDialog;
private LoadDetails loadDetailsThread;
private String themeSettingsPref = "";
private final UpdateLoc geoDirUpdate = new UpdateLoc(this);
/**
* initialization with an empty subscription to make static code analysis tools more happy
*/
private final CompositeDisposable resumeDisposables = new CompositeDisposable();
private CheckBox myLocSwitch;
private MapOptions mapOptions;
private TargetView targetView;
private static boolean followMyLocation = true;
private static final String BUNDLE_MAP_STATE = "mapState";
private static final String BUNDLE_TRAIL_HISTORY = "trailHistory";
// Handler messages
// DisplayHandler
public static final int UPDATE_TITLE = 0;
public static final int INVALIDATE_MAP = 1;
// ShowProgressHandler
public static final int HIDE_PROGRESS = 0;
public static final int SHOW_PROGRESS = 1;
// LoadDetailsHandler
public static final int UPDATE_PROGRESS = 0;
public static final int FINISHED_LOADING_DETAILS = 1;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("NewMap: onCreate");
ResourceBitmapCacheMonitor.addRef();
AndroidGraphicFactory.createInstance(this.getApplication());
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
this.sharedPreferences.registerOnSharedPreferenceChangeListener(this);
Parameters.MAXIMUM_BUFFER_SIZE = 6500000;
// Get parameters from the intent
mapOptions = new MapOptions(this, getIntent().getExtras());
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
mapOptions.mapState = savedInstanceState.getParcelable(BUNDLE_MAP_STATE);
trailHistory = savedInstanceState.getParcelableArrayList(BUNDLE_TRAIL_HISTORY);
followMyLocation = mapOptions.mapState.followsMyLocation();
} else {
followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE;
}
ActivityMixin.onCreate(this, true);
// set layout
ActivityMixin.setTheme(this);
setContentView(R.layout.map_mapsforge_v6);
setTitle();
// initialize map
mapView = (MfMapView) findViewById(R.id.mfmapv5);
mapView.setClickable(true);
mapView.getMapScaleBar().setVisible(true);
mapView.setBuiltInZoomControls(true);
// create a tile cache of suitable size. always initialize it based on the smallest tile size to expect (256 for online tiles)
tileCache = AndroidUtil.createTileCache(this, "mapcache", 256, 1f, this.mapView.getModel().frameBufferModel.getOverdrawFactor());
// attach drag handler
final DragHandler dragHandler = new DragHandler(this);
mapView.setOnMapDragListener(dragHandler);
// prepare initial settings of mapView
if (mapOptions.mapState != null) {
this.mapView.getModel().mapViewPosition.setCenter(MapsforgeUtils.toLatLong(mapOptions.mapState.getCenter()));
this.mapView.setMapZoomLevel((byte) mapOptions.mapState.getZoomLevel());
this.targetGeocode = mapOptions.mapState.getTargetGeocode();
this.lastNavTarget = mapOptions.mapState.getLastNavTarget();
mapOptions.isLiveEnabled = mapOptions.mapState.isLiveEnabled();
mapOptions.isStoredEnabled = mapOptions.mapState.isStoredEnabled();
} else if (mapOptions.searchResult != null) {
final Viewport viewport = DataStore.getBounds(mapOptions.searchResult.getGeocodes());
if (viewport != null) {
postZoomToViewport(viewport);
}
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport viewport = DataStore.getBounds(mapOptions.geocode);
if (viewport != null) {
postZoomToViewport(viewport);
}
targetGeocode = mapOptions.geocode;
} else if (mapOptions.coords != null) {
postZoomToViewport(new Viewport(mapOptions.coords, 0, 0));
} else {
postZoomToViewport(new Viewport(Settings.getMapCenter().getCoords(), 0, 0));
}
prepareFilterBar();
Routing.connect();
}
private void postZoomToViewport(final Viewport viewport) {
mapView.post(new Runnable() {
@Override
public void run() {
mapView.zoomToViewport(viewport);
}
});
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
final boolean result = super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.map_activity, menu);
MapProviderFactory.addMapviewMenuItems(menu);
final MenuItem item = menu.findItem(R.id.menu_toggle_mypos);
myLocSwitch = new CheckBox(this);
myLocSwitch.setButtonDrawable(R.drawable.ic_menu_myposition);
item.setActionView(myLocSwitch);
initMyLocationSwitchButton(myLocSwitch);
return result;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
super.onPrepareOptionsMenu(menu);
for (final MapSource mapSource : MapProviderFactory.getMapSources()) {
final MenuItem menuItem = menu.findItem(mapSource.getNumericalId());
if (menuItem != null) {
menuItem.setVisible(mapSource.isAvailable());
}
}
try {
final MenuItem itemMapLive = menu.findItem(R.id.menu_map_live);
if (mapOptions.isLiveEnabled) {
itemMapLive.setTitle(res.getString(R.string.map_live_disable));
} else {
itemMapLive.setTitle(res.getString(R.string.map_live_enable));
}
itemMapLive.setVisible(mapOptions.coords == null);
final Set<String> visibleCacheGeocodes = caches.getVisibleCacheGeocodes();
menu.findItem(R.id.menu_store_caches).setVisible(false);
menu.findItem(R.id.menu_store_caches).setVisible(!caches.isDownloading() && !visibleCacheGeocodes.isEmpty());
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(false);
menu.findItem(R.id.menu_store_unsaved_caches).setVisible(!caches.isDownloading() && new SearchResult(visibleCacheGeocodes).hasUnsavedCaches());
menu.findItem(R.id.menu_mycaches_mode).setChecked(Settings.isExcludeMyCaches());
menu.findItem(R.id.menu_disabled_mode).setChecked(Settings.isExcludeDisabledCaches());
menu.findItem(R.id.menu_direction_line).setChecked(Settings.isMapDirection());
//TODO: circles menu.findItem(R.id.menu_circle_mode).setChecked(this.searchOverlay.getCircles());
menu.findItem(R.id.menu_circle_mode).setVisible(false);
menu.findItem(R.id.menu_trail_mode).setChecked(Settings.isMapTrail());
menu.findItem(R.id.menu_theme_mode).setVisible(tileLayerHasThemes());
menu.findItem(R.id.menu_theme_options).setVisible(styleMenu != null);
menu.findItem(R.id.menu_as_list).setVisible(!caches.isDownloading() && caches.getVisibleCachesCount() > 1);
menu.findItem(R.id.submenu_strategy).setVisible(mapOptions.isLiveEnabled);
switch (Settings.getLiveMapStrategy()) {
case FAST:
menu.findItem(R.id.menu_strategy_fast).setChecked(true);
break;
case AUTO:
menu.findItem(R.id.menu_strategy_auto).setChecked(true);
break;
default: // DETAILED
menu.findItem(R.id.menu_strategy_detailed).setChecked(true);
break;
}
menu.findItem(R.id.submenu_routing).setVisible(Routing.isAvailable());
switch (Settings.getRoutingMode()) {
case STRAIGHT:
menu.findItem(R.id.menu_routing_straight).setChecked(true);
break;
case WALK:
menu.findItem(R.id.menu_routing_walk).setChecked(true);
break;
case BIKE:
menu.findItem(R.id.menu_routing_bike).setChecked(true);
break;
case CAR:
menu.findItem(R.id.menu_routing_car).setChecked(true);
break;
}
menu.findItem(R.id.menu_hint).setVisible(mapOptions.mapMode == MapMode.SINGLE);
menu.findItem(R.id.menu_compass).setVisible(mapOptions.mapMode == MapMode.SINGLE);
} catch (final RuntimeException e) {
Log.e("NewMap.onPrepareOptionsMenu", e);
}
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
switch (id) {
case android.R.id.home:
ActivityMixin.navigateUp(this);
return true;
case R.id.menu_trail_mode:
Settings.setMapTrail(!Settings.isMapTrail());
historyLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_direction_line:
Settings.setMapDirection(!Settings.isMapDirection());
navigationLayer.requestRedraw();
ActivityMixin.invalidateOptionsMenu(this);
return true;
case R.id.menu_map_live:
mapOptions.isLiveEnabled = !mapOptions.isLiveEnabled;
if (mapOptions.isLiveEnabled) {
mapOptions.isStoredEnabled = true;
}
if (mapOptions.mapMode == MapMode.LIVE) {
Settings.setLiveMap(mapOptions.isLiveEnabled);
}
caches.enableStoredLayers(mapOptions.isStoredEnabled);
caches.handleLiveLayers(mapOptions.isLiveEnabled);
ActivityMixin.invalidateOptionsMenu(this);
if (mapOptions.mapMode != MapMode.SINGLE) {
mapOptions.title = StringUtils.EMPTY;
} else {
// reset target cache on single mode map
targetGeocode = mapOptions.geocode;
}
return true;
case R.id.menu_store_caches:
return storeCaches(caches.getVisibleCacheGeocodes());
case R.id.menu_store_unsaved_caches:
return storeCaches(getUnsavedGeocodes(caches.getVisibleCacheGeocodes()));
case R.id.menu_circle_mode:
// overlayCaches.switchCircles();
// mapView.repaintRequired(overlayCaches);
// ActivityMixin.invalidateOptionsMenu(activity);
return true;
case R.id.menu_mycaches_mode:
Settings.setExcludeMine(!Settings.isExcludeMyCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeMyCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_disabled_mode:
Settings.setExcludeDisabled(!Settings.isExcludeDisabledCaches());
caches.invalidate();
ActivityMixin.invalidateOptionsMenu(this);
if (!Settings.isExcludeDisabledCaches()) {
Tile.cache.clear();
}
return true;
case R.id.menu_theme_mode:
selectMapTheme();
return true;
case R.id.menu_theme_options:
final Intent intent = new Intent(this, RenderThemeSettings.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
if (styleMenu != null) {
intent.putExtra(RenderThemeSettings.RENDERTHEME_MENU, styleMenu);
}
startActivity(intent);
return true;
case R.id.menu_as_list:
CacheListActivity.startActivityMap(this, new SearchResult(caches.getVisibleCacheGeocodes()));
return true;
case R.id.menu_strategy_fast:
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.FAST);
return true;
case R.id.menu_strategy_auto:
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.AUTO);
return true;
case R.id.menu_strategy_detailed:
item.setChecked(true);
Settings.setLiveMapStrategy(LivemapStrategy.DETAILED);
return true;
case R.id.menu_routing_straight:
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.STRAIGHT);
navigationLayer.requestRedraw();
return true;
case R.id.menu_routing_walk:
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.WALK);
navigationLayer.requestRedraw();
return true;
case R.id.menu_routing_bike:
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.BIKE);
navigationLayer.requestRedraw();
return true;
case R.id.menu_routing_car:
item.setChecked(true);
Settings.setRoutingMode(RoutingMode.CAR);
navigationLayer.requestRedraw();
return true;
case R.id.menu_hint:
menuShowHint();
return true;
case R.id.menu_compass:
menuCompass();
return true;
default:
final MapSource mapSource = MapProviderFactory.getMapSource(id);
if (mapSource != null) {
item.setChecked(true);
changeMapSource(mapSource);
return true;
}
}
return false;
}
private Set<String> getUnsavedGeocodes(final Set<String> geocodes) {
final Set<String> unsavedGeocodes = new HashSet<>();
for (final String geocode : geocodes) {
if (!DataStore.isOffline(geocode, null)) {
unsavedGeocodes.add(geocode);
}
}
return unsavedGeocodes;
}
private boolean storeCaches(final Set<String> geocodes) {
if (!caches.isDownloading()) {
if (geocodes.isEmpty()) {
ActivityMixin.showToast(this, res.getString(R.string.warn_save_nothing));
return true;
}
if (Settings.getChooseList()) {
// let user select list to store cache in
new StoredList.UserInterface(this).promptForMultiListSelection(R.string.list_title, new Action1<Set<Integer>>() {
@Override
public void call(final Set<Integer> selectedListIds) {
storeCaches(geocodes, selectedListIds);
}
}, true, Collections.singleton(StoredList.TEMPORARY_LIST.id), false);
} else {
storeCaches(geocodes, Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
return true;
}
private void menuCompass() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
CompassActivity.startActivityCache(this, cache);
}
}
private void menuShowHint() {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
cache.showHintToast(this);
}
}
private void prepareFilterBar() {
// show the filter warning bar if the filter is set
if (Settings.getCacheType() != CacheType.ALL) {
final String cacheType = Settings.getCacheType().getL10n();
final TextView filterTitleView = ButterKnife.findById(this, R.id.filter_text);
filterTitleView.setText(cacheType);
findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
/**
* @param view Not used here, required by layout
*/
public void showFilterMenu(final View view) {
// do nothing, the filter bar only shows the global filter
}
private void selectMapTheme() {
final File[] themeFiles = Settings.getMapThemeFiles();
String currentTheme = StringUtils.EMPTY;
final String currentThemePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isNotEmpty(currentThemePath)) {
final File currentThemeFile = new File(currentThemePath);
currentTheme = currentThemeFile.getName();
}
final List<String> names = new ArrayList<>();
names.add(res.getString(R.string.map_theme_builtin));
int currentItem = 0;
for (final File file : themeFiles) {
if (currentTheme.equalsIgnoreCase(file.getName())) {
currentItem = names.size();
}
names.add(file.getName());
}
final int selectedItem = currentItem;
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.map_theme_select);
builder.setSingleChoiceItems(names.toArray(new String[names.size()]), selectedItem, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int newItem) {
if (newItem != selectedItem) {
// Adjust index because of <default> selection
if (newItem > 0) {
Settings.setCustomRenderThemeFile(themeFiles[newItem - 1].getPath());
} else {
Settings.setCustomRenderThemeFile(StringUtils.EMPTY);
}
setMapTheme();
}
dialog.cancel();
}
});
builder.show();
}
protected void setMapTheme() {
if (tileLayer == null || tileLayer.getTileLayer() == null) {
return;
}
if (!tileLayer.hasThemes()) {
tileLayer.getTileLayer().requestRedraw();
return;
}
final TileRendererLayer rendererLayer = (TileRendererLayer) tileLayer.getTileLayer();
final String themePath = Settings.getCustomRenderThemeFilePath();
if (StringUtils.isEmpty(themePath)) {
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} else {
try {
final XmlRenderTheme xmlRenderTheme = new ExternalRenderTheme(new File(themePath), this);
// Validate the theme file
RenderThemeHandler.getRenderTheme(AndroidGraphicFactory.INSTANCE, new DisplayModel(), xmlRenderTheme);
rendererLayer.setXmlRenderTheme(xmlRenderTheme);
} catch (final IOException e) {
Log.w("Failed to set render theme", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_file_unreadable));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
} catch (final XmlPullParserException e) {
Log.w("render theme invalid", e);
ActivityMixin.showApplicationToast(getString(R.string.err_rendertheme_invalid));
rendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
}
}
tileCache.purge();
rendererLayer.requestRedraw();
}
private void changeMapSource(@NonNull final MapSource newSource) {
final MapSource oldSource = Settings.getMapSource();
final boolean restartRequired = !MapProviderFactory.isSameActivity(oldSource, newSource);
// Update MapSource in settings
Settings.setMapSource(newSource);
if (restartRequired) {
mapRestart();
} else if (mapView != null) { // changeMapSource can be called by onCreate()
switchTileLayer(newSource);
}
}
/**
* Restart the current activity with the default map source.
*/
private void mapRestart() {
mapOptions.mapState = currentMapState();
finish();
mapOptions.startIntent(this, Settings.getMapProvider().getMapClass());
}
/**
* Get the current map state from the map view if it exists or from the mapStateIntent field otherwise.
*
* @return the current map state as an array of int, or null if no map state is available
*/
private MapState currentMapState() {
if (mapView == null) {
return null;
}
final Geopoint mapCenter = mapView.getViewport().getCenter();
return new MapState(mapCenter.getCoords(), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void switchTileLayer(final MapSource newSource) {
final ITileLayer oldLayer = this.tileLayer;
ITileLayer newLayer = null;
if (newSource instanceof MapsforgeMapSource) {
newLayer = ((MapsforgeMapSource) newSource).createTileLayer(tileCache, this.mapView.getModel().mapViewPosition);
}
// Exchange layer
if (newLayer != null) {
this.mapView.getModel().displayModel.setFixedTileSize(newLayer.getFixedTileSize());
final MapZoomControls zoomControls = mapView.getMapZoomControls();
zoomControls.setZoomLevelMax(newLayer.getZoomLevelMax());
zoomControls.setZoomLevelMin(newLayer.getZoomLevelMin());
final Layers layers = this.mapView.getLayerManager().getLayers();
int index = 0;
if (oldLayer != null) {
index = layers.indexOf(oldLayer.getTileLayer()) + 1;
}
layers.add(index, newLayer.getTileLayer());
this.tileLayer = newLayer;
this.setMapTheme();
} else {
this.tileLayer = null;
}
// Cleanup
if (oldLayer != null) {
this.mapView.getLayerManager().getLayers().remove(oldLayer.getTileLayer());
oldLayer.getTileLayer().onDestroy();
}
tileCache.purge();
}
private void resumeTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onResume();
}
}
private void pauseTileLayer() {
if (this.tileLayer != null) {
this.tileLayer.onPause();
}
}
private boolean tileLayerHasThemes() {
if (tileLayer != null) {
return tileLayer.hasThemes();
}
return false;
}
@Override
protected void onResume() {
super.onResume();
Log.d("NewMap: onResume");
resumeTileLayer();
}
@Override
protected void onStart() {
super.onStart();
Log.d("NewMap: onStart");
initializeLayers();
}
private void initializeLayers() {
switchTileLayer(Settings.getMapSource());
// History Layer
this.historyLayer = new HistoryLayer(trailHistory);
this.mapView.getLayerManager().getLayers().add(this.historyLayer);
// NavigationLayer
Geopoint navTarget = lastNavTarget;
if (navTarget == null) {
navTarget = mapOptions.coords;
if (navTarget == null && StringUtils.isNotEmpty(mapOptions.geocode)) {
final Viewport bounds = DataStore.getBounds(mapOptions.geocode);
if (bounds != null) {
navTarget = bounds.center;
}
}
}
this.navigationLayer = new NavigationLayer(navTarget);
this.mapView.getLayerManager().getLayers().add(this.navigationLayer);
// TapHandler
final TapHandlerLayer tapHandlerLayer = new TapHandlerLayer(this.mapHandlers.getTapHandler());
this.mapView.getLayerManager().getLayers().add(tapHandlerLayer);
// Caches bundle
if (mapOptions.searchResult != null) {
this.caches = new CachesBundle(mapOptions.searchResult, this.mapView, this.mapHandlers);
} else if (StringUtils.isNotEmpty(mapOptions.geocode)) {
this.caches = new CachesBundle(mapOptions.geocode, this.mapView, this.mapHandlers);
} else if (mapOptions.coords != null) {
this.caches = new CachesBundle(mapOptions.coords, mapOptions.waypointType, this.mapView, this.mapHandlers);
} else {
caches = new CachesBundle(this.mapView, this.mapHandlers);
}
// Stored enabled map
caches.enableStoredLayers(mapOptions.isStoredEnabled);
// Live enabled map
caches.handleLiveLayers(mapOptions.isLiveEnabled);
// Position layer
this.positionLayer = new PositionLayer();
this.mapView.getLayerManager().getLayers().add(positionLayer);
//Distance view
this.distanceView = new DistanceView(navTarget, (TextView) findViewById(R.id.distance));
//Target view
this.targetView = new TargetView((TextView) findViewById(R.id.target), StringUtils.EMPTY, StringUtils.EMPTY);
final Geocache target = getCurrentTargetCache();
if (target != null) {
targetView.setTarget(target.getGeocode(), target.getName());
}
this.resumeDisposables.add(this.geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR));
}
@Override
public void onPause() {
Log.d("NewMap: onPause");
savePrefs();
pauseTileLayer();
super.onPause();
}
@Override
protected void onStop() {
Log.d("NewMap: onStop");
waitDialog = null;
terminateLayers();
super.onStop();
}
private void terminateLayers() {
this.resumeDisposables.clear();
this.caches.onDestroy();
this.caches = null;
this.mapView.getLayerManager().getLayers().remove(this.positionLayer);
this.positionLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.navigationLayer);
this.navigationLayer = null;
this.mapView.getLayerManager().getLayers().remove(this.historyLayer);
this.historyLayer = null;
if (this.tileLayer != null) {
this.mapView.getLayerManager().getLayers().remove(this.tileLayer.getTileLayer());
this.tileLayer.getTileLayer().onDestroy();
this.tileLayer = null;
}
}
/**
* store caches, invoked by "store offline" menu item
*
* @param listIds the lists to store the caches in
*/
private void storeCaches(final Set<String> geocodes, final Set<Integer> listIds) {
final int count = geocodes.size();
final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(count, this);
waitDialog = new ProgressDialog(this);
waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
waitDialog.setCancelable(true);
waitDialog.setCancelMessage(loadDetailsHandler.disposeMessage());
waitDialog.setMax(count);
waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(final DialogInterface arg0) {
try {
if (loadDetailsThread != null) {
loadDetailsThread.stopIt();
}
} catch (final Exception e) {
Log.e("CGeoMap.storeCaches.onCancel", e);
}
}
});
final float etaTime = count * 7.0f / 60.0f;
final int roundedEta = Math.round(etaTime);
if (etaTime < 0.4) {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else {
waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getQuantityString(R.plurals.caches_eta_mins, roundedEta, roundedEta));
}
loadDetailsHandler.setStart();
waitDialog.show();
loadDetailsThread = new LoadDetails(loadDetailsHandler, geocodes, listIds);
loadDetailsThread.start();
}
@Override
protected void onDestroy() {
Log.d("NewMap: onDestroy");
this.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
this.tileCache.destroy();
this.mapView.getModel().mapViewPosition.destroy();
this.mapView.destroy();
ResourceBitmapCacheMonitor.release();
Routing.disconnect();
super.onDestroy();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("New map: onSaveInstanceState");
final MapState state = prepareMapState();
outState.putParcelable(BUNDLE_MAP_STATE, state);
if (historyLayer != null) {
trailHistory = historyLayer.getHistory();
outState.putParcelableArrayList(BUNDLE_TRAIL_HISTORY, trailHistory);
}
}
private MapState prepareMapState() {
return new MapState(MapsforgeUtils.toGeopoint(mapView.getModel().mapViewPosition.getCenter()), mapView.getMapZoomLevel(), followMyLocation, false, targetGeocode, lastNavTarget, mapOptions.isLiveEnabled, mapOptions.isStoredEnabled);
}
private void centerMap(final Geopoint geopoint) {
mapView.getModel().mapViewPosition.setCenter(new LatLong(geopoint.getLatitude(), geopoint.getLongitude()));
}
public Location getCoordinates() {
final LatLong center = mapView.getModel().mapViewPosition.getCenter();
final Location loc = new Location("newmap");
loc.setLatitude(center.latitude);
loc.setLongitude(center.longitude);
return loc;
}
private void initMyLocationSwitchButton(final CheckBox locSwitch) {
myLocSwitch = locSwitch;
/*
* TODO: Switch back to ImageSwitcher for animations?
* myLocSwitch.setFactory(this);
* myLocSwitch.setInAnimation(activity, android.R.anim.fade_in);
* myLocSwitch.setOutAnimation(activity, android.R.anim.fade_out);
*/
myLocSwitch.setOnClickListener(new MyLocationListener(this));
switchMyLocationButton();
}
// switch My Location button image
private void switchMyLocationButton() {
myLocSwitch.setChecked(followMyLocation);
if (followMyLocation) {
myLocationInMiddle(Sensors.getInstance().currentGeo());
}
}
public void showAddWaypoint(final LatLong tapLatLong) {
final Geocache cache = getCurrentTargetCache();
if (cache != null) {
EditWaypointActivity.startActivityAddWaypoint(this, cache, new Geopoint(tapLatLong.latitude, tapLatLong.longitude));
}
}
@Override
public Set<String> getCategories(final XmlRenderThemeStyleMenu style) {
styleMenu = style;
themeSettingsPref = style.getId();
final String id = this.sharedPreferences.getString(styleMenu.getId(), styleMenu.getDefaultValue());
final XmlRenderThemeStyleLayer baseLayer = styleMenu.getLayer(id);
if (baseLayer == null) {
Log.w("Invalid style " + id);
return null;
}
final Set<String> result = baseLayer.getCategories();
// add the categories from overlays that are enabled
for (final XmlRenderThemeStyleLayer overlay : baseLayer.getOverlays()) {
if (this.sharedPreferences.getBoolean(overlay.getId(), overlay.isEnabled())) {
result.addAll(overlay.getCategories());
}
}
return result;
}
@Override
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String s) {
if (StringUtils.equals(s, themeSettingsPref)) {
AndroidUtil.restartActivity(this);
}
}
// set my location listener
private static class MyLocationListener implements View.OnClickListener {
@NonNull
private final WeakReference<NewMap> mapRef;
MyLocationListener(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
private void onFollowMyLocationClicked() {
followMyLocation = !followMyLocation;
final NewMap map = mapRef.get();
if (map != null) {
map.switchMyLocationButton();
}
}
@Override
public void onClick(final View view) {
onFollowMyLocationClicked();
}
}
// Set center of map to my location if appropriate.
private void myLocationInMiddle(final GeoData geo) {
if (followMyLocation) {
centerMap(geo.getCoords());
}
}
private static final class DisplayHandler extends Handler {
@NonNull
private final WeakReference<NewMap> mapRef;
DisplayHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
final int what = msg.what;
switch (what) {
case UPDATE_TITLE:
map.setTitle();
map.setSubtitle();
break;
case INVALIDATE_MAP:
map.mapView.repaint();
break;
default:
break;
}
}
}
private void setTitle() {
final String title = calculateTitle();
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}
}
@NonNull
private String calculateTitle() {
if (mapOptions.isLiveEnabled) {
return res.getString(R.string.map_live);
}
if (mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return cache.getName();
}
}
return StringUtils.defaultIfEmpty(mapOptions.title, res.getString(R.string.map_map));
}
private void setSubtitle() {
final String subtitle = calculateSubtitle();
if (StringUtils.isEmpty(subtitle)) {
return;
}
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setSubtitle(subtitle);
}
}
@NonNull
private String calculateSubtitle() {
if (!mapOptions.isLiveEnabled && mapOptions.mapMode == MapMode.SINGLE) {
final Geocache cache = getSingleModeCache();
if (cache != null) {
return Formatter.formatMapSubtitle(cache);
}
}
// count caches in the sub title
final int visible = countVisibleCaches();
final int total = countTotalCaches();
final StringBuilder subtitle = new StringBuilder();
if (total != 0) {
if (visible != total && Settings.isDebug()) {
subtitle.append(visible).append('/').append(res.getQuantityString(R.plurals.cache_counts, total, total));
} else {
subtitle.append(res.getQuantityString(R.plurals.cache_counts, visible, visible));
}
}
// if (Settings.isDebug() && lastSearchResult != null && StringUtils.isNotBlank(lastSearchResult.getUrl())) {
// subtitle.append(" [").append(lastSearchResult.getUrl()).append(']');
return subtitle.toString();
}
private int countVisibleCaches() {
return caches != null ? caches.getVisibleCachesCount() : 0;
}
private int countTotalCaches() {
return caches != null ? caches.getCachesCount() : 0;
}
/**
* Updates the progress.
*/
private static final class ShowProgressHandler extends Handler {
private int counter = 0;
@NonNull
private final WeakReference<NewMap> mapRef;
ShowProgressHandler(@NonNull final NewMap map) {
this.mapRef = new WeakReference<>(map);
}
@Override
public void handleMessage(final Message msg) {
final int what = msg.what;
if (what == HIDE_PROGRESS) {
if (--counter == 0) {
showProgress(false);
}
} else if (what == SHOW_PROGRESS) {
showProgress(true);
counter++;
}
}
private void showProgress(final boolean show) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
map.setProgressBarIndeterminateVisibility(show);
}
}
private static final class LoadDetailsHandler extends DisposableHandler {
private final int detailTotal;
private int detailProgress;
private long detailProgressTime;
private final WeakReference<NewMap> mapRef;
LoadDetailsHandler(final int detailTotal, final NewMap map) {
super();
this.detailTotal = detailTotal;
this.detailProgress = 0;
this.mapRef = new WeakReference<>(map);
}
public void setStart() {
detailProgressTime = System.currentTimeMillis();
}
@Override
public void handleRegularMessage(final Message msg) {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (msg.what == UPDATE_PROGRESS) {
if (detailProgress < detailTotal) {
detailProgress++;
}
if (map.waitDialog != null) {
final int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
final int secondsRemaining;
if (detailProgress > 0) {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed / detailProgress;
} else {
secondsRemaining = (detailTotal - detailProgress) * secondsElapsed;
}
map.waitDialog.setProgress(detailProgress);
if (secondsRemaining < 40) {
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getString(R.string.caches_eta_ltm));
} else {
final int minsRemaining = secondsRemaining / 60;
map.waitDialog.setMessage(map.res.getString(R.string.caches_downloading) + " " + map.res.getQuantityString(R.plurals.caches_eta_mins, minsRemaining, minsRemaining));
}
}
} else if (msg.what == FINISHED_LOADING_DETAILS && map.waitDialog != null) {
map.waitDialog.dismiss();
map.waitDialog.setOnCancelListener(null);
}
}
@Override
public void handleDispose() {
final NewMap map = mapRef.get();
if (map == null) {
return;
}
if (map.loadDetailsThread != null) {
map.loadDetailsThread.stopIt();
}
}
}
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
@NonNull
Location currentLocation = Sensors.getInstance().currentGeo();
float currentHeading;
private long timeLastPositionOverlayCalculation = 0;
/**
* weak reference to the outer class
*/
@NonNull
private final WeakReference<NewMap> mapRef;
UpdateLoc(@NonNull final NewMap map) {
mapRef = new WeakReference<>(map);
}
@Override
public void updateGeoDir(@NonNull final GeoData geo, final float dir) {
currentLocation = geo;
currentHeading = AngleUtils.getDirectionNow(dir);
repaintPositionOverlay();
}
@NonNull
public Location getCurrentLocation() {
return currentLocation;
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final NewMap map = mapRef.get();
if (map != null) {
final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistanceOrAccuracy && NewMap.followMyLocation) {
map.centerMap(new Geopoint(currentLocation));
}
if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) {
map.historyLayer.setCoordinates(currentLocation);
map.navigationLayer.setCoordinates(currentLocation);
map.distanceView.setCoordinates(currentLocation);
map.positionLayer.setCoordinates(currentLocation);
map.positionLayer.setHeading(currentHeading);
map.positionLayer.requestRedraw();
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location", e);
}
}
}
boolean needsRepaintForHeading() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, map.positionLayer.getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistanceOrAccuracy() {
final NewMap map = mapRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.getCoordinates();
float dist = Float.MAX_VALUE;
if (lastLocation != null) {
if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) {
return true;
}
dist = currentLocation.distanceTo(lastLocation);
}
final float[] mapDimension = new float[1];
if (map.mapView.getWidth() < map.mapView.getHeight()) {
final double span = map.mapView.getLongitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude(), currentLocation.getLongitude() + span, mapDimension);
} else {
final double span = map.mapView.getLatitudeSpan() / 1e6;
Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), currentLocation.getLatitude() + span, currentLocation.getLongitude(), mapDimension);
}
return dist > (mapDimension[0] * MIN_LOCATION_DELTA);
}
}
private static class DragHandler implements OnMapDragListener {
@NonNull
private final WeakReference<NewMap> mapRef;
DragHandler(@NonNull final NewMap parent) {
mapRef = new WeakReference<>(parent);
}
@Override
public void onDrag() {
final NewMap map = mapRef.get();
if (map != null && NewMap.followMyLocation) {
NewMap.followMyLocation = false;
map.switchMyLocationButton();
}
}
}
public void showSelection(@NonNull final List<GeoitemRef> items) {
if (items.isEmpty()) {
return;
}
if (items.size() == 1) {
showPopup(items.get(0));
return;
}
try {
final ArrayList<GeoitemRef> sorted = new ArrayList<>(items);
Collections.sort(sorted, GeoitemRef.NAME_COMPARATOR);
final LayoutInflater inflater = LayoutInflater.from(this);
final ListAdapter adapter = new ArrayAdapter<GeoitemRef>(this, R.layout.cacheslist_item_select, sorted) {
@NonNull
@Override
public View getView(final int position, final View convertView, @NonNull final ViewGroup parent) {
final View view = convertView == null ? inflater.inflate(R.layout.cacheslist_item_select, parent, false) : convertView;
final TextView tv = (TextView) view.findViewById(R.id.text);
final GeoitemRef item = getItem(position);
tv.setText(item.getName());
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(item.getMarkerId(), 0, 0, 0);
final TextView infoView = (TextView) view.findViewById(R.id.info);
final StringBuilder text = new StringBuilder(item.getItemCode());
if (item.getType() == CoordinatesType.WAYPOINT && StringUtils.isNotEmpty(item.getGeocode())) {
text.append(Formatter.SEPARATOR).append(item.getGeocode());
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
text.append(Formatter.SEPARATOR).append(cache.getName());
}
}
infoView.setText(text.toString());
return view;
}
};
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.map_select_multiple_items))
.setAdapter(adapter, new SelectionClickListener(sorted))
.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
} catch (final NotFoundException e) {
Log.e("NewMap.showSelection", e);
}
}
private class SelectionClickListener implements DialogInterface.OnClickListener {
@NonNull
private final List<GeoitemRef> items;
SelectionClickListener(@NonNull final List<GeoitemRef> items) {
this.items = items;
}
@Override
public void onClick(final DialogInterface dialog, final int which) {
if (which >= 0 && which < items.size()) {
final GeoitemRef item = items.get(which);
showPopup(item);
}
}
}
private void showPopup(final GeoitemRef item) {
if (item == null || StringUtils.isEmpty(item.getGeocode())) {
return;
}
try {
if (item.getType() == CoordinatesType.CACHE) {
final Geocache cache = DataStore.loadCache(item.getGeocode(), LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null) {
final RequestDetailsThread requestDetailsThread = new RequestDetailsThread(cache, this);
requestDetailsThread.start();
return;
}
return;
}
if (item.getType() == CoordinatesType.WAYPOINT && item.getId() >= 0) {
popupGeocodes.add(item.getGeocode());
WaypointPopup.startActivityAllowTarget(this, item.getId(), item.getGeocode());
}
} catch (final NotFoundException e) {
Log.e("NewMap.showPopup", e);
}
}
@Nullable
private Geocache getSingleModeCache() {
if (StringUtils.isNotBlank(mapOptions.geocode)) {
return DataStore.loadCache(mapOptions.geocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
@Nullable
private Geocache getCurrentTargetCache() {
if (StringUtils.isNotBlank(targetGeocode)) {
return DataStore.loadCache(targetGeocode, LoadFlags.LOAD_CACHE_OR_DB);
}
return null;
}
private void savePrefs() {
Settings.setMapZoom(MapMode.SINGLE, mapView.getMapZoomLevel());
Settings.setMapCenter(new MapsforgeGeoPoint(mapView.getModel().mapViewPosition.getCenter()));
}
private static class RequestDetailsThread extends Thread {
@NonNull
private final Geocache cache;
@NonNull
private final WeakReference<NewMap> mapRef;
RequestDetailsThread(@NonNull final Geocache cache, @NonNull final NewMap map) {
this.cache = cache;
this.mapRef = new WeakReference<>(map);
}
public boolean requestRequired() {
return CacheType.UNKNOWN == cache.getType() || cache.getDifficulty() == 0;
}
@Override
public void run() {
final NewMap map = this.mapRef.get();
if (map == null) {
return;
}
if (requestRequired()) {
try {
/* final SearchResult search = */
GCMap.searchByGeocodes(Collections.singleton(cache.getGeocode()));
} catch (final Exception ex) {
Log.w("Error requesting cache popup info", ex);
ActivityMixin.showToast(map, R.string.err_request_popup_info);
}
}
map.popupGeocodes.add(cache.getGeocode());
CachePopup.startActivityAllowTarget(map, cache.getGeocode());
}
}
/**
* Thread to store the caches in the viewport. Started by Activity.
*/
private class LoadDetails extends Thread {
private final DisposableHandler handler;
private final Collection<String> geocodes;
private final Set<Integer> listIds;
LoadDetails(final DisposableHandler handler, final Collection<String> geocodes, final Set<Integer> listIds) {
this.handler = handler;
this.geocodes = geocodes;
this.listIds = listIds;
}
public void stopIt() {
handler.dispose();
}
@Override
public void run() {
if (CollectionUtils.isEmpty(geocodes)) {
return;
}
for (final String geocode : geocodes) {
try {
if (handler.isDisposed()) {
break;
}
if (!DataStore.isOffline(geocode, null)) {
Geocache.storeCache(null, geocode, listIds, false, handler);
}
} catch (final Exception e) {
Log.e("CGeoMap.LoadDetails.run", e);
} finally {
handler.sendEmptyMessage(UPDATE_PROGRESS);
}
}
// we're done, but map might even have been closed.
if (caches != null) {
caches.invalidate(geocodes);
}
invalidateOptionsMenuCompatible();
handler.sendEmptyMessage(FINISHED_LOADING_DETAILS);
}
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AbstractDialogFragment.REQUEST_CODE_TARGET_INFO) {
if (resultCode == AbstractDialogFragment.RESULT_CODE_SET_TARGET) {
final TargetInfo targetInfo = data.getExtras().getParcelable(Intents.EXTRA_TARGET_INFO);
if (targetInfo != null) {
lastNavTarget = targetInfo.coords;
if (navigationLayer != null) {
navigationLayer.setDestination(targetInfo.coords);
navigationLayer.requestRedraw();
}
if (distanceView != null) {
distanceView.setDestination(targetInfo.coords);
distanceView.setCoordinates(geoDirUpdate.getCurrentLocation());
}
if (StringUtils.isNotBlank(targetInfo.geocode)) {
targetGeocode = targetInfo.geocode;
final Geocache target = getCurrentTargetCache();
targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY);
}
}
}
final List<String> changedGeocodes = new ArrayList<>();
String geocode = popupGeocodes.poll();
while (geocode != null) {
changedGeocodes.add(geocode);
geocode = popupGeocodes.poll();
}
if (caches != null) {
caches.invalidate(changedGeocodes);
}
}
}
private static class ResourceBitmapCacheMonitor {
private static int refCount = 0;
static synchronized void addRef() {
refCount++;
Log.d("ResourceBitmapCacheMonitor.addRef");
}
static synchronized void release() {
if (refCount > 0) {
refCount
Log.d("ResourceBitmapCacheMonitor.release");
if (refCount == 0) {
Log.d("ResourceBitmapCacheMonitor.clearResourceBitmaps");
AndroidResourceBitmap.clearResourceBitmaps();
}
}
}
}
} |
package org.jivesoftware.spark.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* Utility methods frequently used by data classes and design-time
* classes.
*/
public final class ModelUtil {
private ModelUtil() {
// Prevent instantiation.
}
/**
* This is a utility method that compares two objects when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>o1</CODE> and <CODE>o2</CODE> are the same object
* according to the <CODE>==</CODE> operator, return
* <CODE>true</CODE>.
* <LI>Otherwise, if either <CODE>o1</CODE> or <CODE>o2</CODE> is
* <CODE>null</CODE>, return <CODE>false</CODE>.
* <LI>Otherwise, return <CODE>o1.equals(o2)</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areDifferent(Object, Object)} method.<P>
* <p/>
* For array types, one of the <CODE>equals</CODE> methods in
* {@link java.util.Arrays} should be used instead of this method.
* Note that arrays with more than one dimension will require some
* custom code in order to implement <CODE>equals</CODE> properly.
*/
public static final boolean areEqual(Object o1, Object o2) {
if (o1 == o2) {
return true;
}
else if (o1 == null || o2 == null) {
return false;
}
else {
return o1.equals(o2);
}
}
/**
* This is a utility method that compares two Booleans when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>b1</CODE> and <CODE>b2</CODE> are both TRUE or
* neither <CODE>b1</CODE> nor <CODE>b2</CODE> is TRUE,
* return <CODE>true</CODE>.
* <LI>Otherwise, return <CODE>false</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* areDifferent(Boolean, Boolean) method.<P>
*/
public static final boolean areBooleansEqual(Boolean b1, Boolean b2) {
// !jwetherb treat NULL the same as Boolean.FALSE
return (b1 == Boolean.TRUE && b2 == Boolean.TRUE) ||
(b1 != Boolean.TRUE && b2 != Boolean.TRUE);
}
/**
* This is a utility method that compares two objects when one or
* both of the objects might be <CODE>null</CODE>. The result
* returned by this method is determined as follows:
* <OL>
* <LI>If <CODE>o1</CODE> and <CODE>o2</CODE> are the same object
* according to the <CODE>==</CODE> operator, return
* <CODE>false</CODE>.
* <LI>Otherwise, if either <CODE>o1</CODE> or <CODE>o2</CODE> is
* <CODE>null</CODE>, return <CODE>true</CODE>.
* <LI>Otherwise, return <CODE>!o1.equals(o2)</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areEqual(Object, Object)} method.<P>
* <p/>
* For array types, one of the <CODE>equals</CODE> methods in
* {@link java.util.Arrays} should be used instead of this method.
* Note that arrays with more than one dimension will require some
* custom code in order to implement <CODE>equals</CODE> properly.
*/
public static final boolean areDifferent(Object o1, Object o2) {
return !areEqual(o1, o2);
}
/**
* This is a utility method that compares two Booleans when one or
* both of the objects might be <CODE>null</CODE> The result of
* this method is determined as follows:
* <OL>
* <LI>If <CODE>b1</CODE> and <CODE>b2</CODE> are both TRUE or
* neither <CODE>b1</CODE> nor <CODE>b2</CODE> is TRUE,
* return <CODE>false</CODE>.
* <LI>Otherwise, return <CODE>true</CODE>.
* </OL>
* <p/>
* This method produces the exact logically inverted result as the
* {@link #areBooleansEqual(Boolean, Boolean)} method.<P>
*/
public static final boolean areBooleansDifferent(Boolean b1, Boolean b2) {
return !areBooleansEqual(b1, b2);
}
/**
* Returns <CODE>true</CODE> if the specified array is not null
* and contains a non-null element. Returns <CODE>false</CODE>
* if the array is null or if all the array elements are null.
*/
public static final boolean hasNonNullElement(Object[] array) {
if (array != null) {
final int n = array.length;
for (int i = 0; i < n; i++) {
if (array[i] != null) {
return true;
}
}
}
return false;
}
/**
* Returns a single string that is the concatenation of all the
* strings in the specified string array. A single space is
* put between each string array element. Null array elements
* are skipped. If the array itself is null, the empty string
* is returned. This method is guaranteed to return a non-null
* value, if no expections are thrown.
*/
public static final String concat(String[] strs) {
return concat(strs, " "); //NOTRANS
}
/**
* Returns a single string that is the concatenation of all the
* strings in the specified string array. The strings are separated
* by the specified delimiter. Null array elements are skipped. If
* the array itself is null, the empty string is returned. This
* method is guaranteed to return a non-null value, if no expections
* are thrown.
*/
public static final String concat(String[] strs, String delim) {
if (strs != null) {
final StringBuffer buf = new StringBuffer();
final int n = strs.length;
for (int i = 0; i < n; i++) {
final String str = strs[i];
if (str != null) {
buf.append(str).append(delim);
}
}
final int length = buf.length();
if (length > 0) {
// Trim trailing space.
buf.setLength(length - 1);
}
return buf.toString();
}
else {
return ""; // NOTRANS
}
}
/**
* Returns <CODE>true</CODE> if the specified {@link String} is not
* <CODE>null</CODE> and has a length greater than zero. This is
* a very frequently occurring check.
*/
public static final boolean hasLength(String s) {
return (s != null && s.length() > 0);
}
/**
* Returns <CODE>null</CODE> if the specified string is empty or
* <CODE>null</CODE>. Otherwise the string itself is returned.
*/
public static final String nullifyIfEmpty(String s) {
return ModelUtil.hasLength(s) ? s : null;
}
/**
* Returns <CODE>null</CODE> if the specified object is null
* or if its <CODE>toString()</CODE> representation is empty.
* Otherwise, the <CODE>toString()</CODE> representation of the
* object itself is returned.
*/
public static final String nullifyingToString(Object o) {
return o != null ? nullifyIfEmpty(o.toString()) : null;
}
/**
* Determines if a string has been changed.
*
* @param oldString is the initial value of the String
* @param newString is the new value of the String
* @return true If both oldString and newString are null or if they are
* both not null and equal to each other. Otherwise returns false.
*/
public static boolean hasStringChanged(String oldString, String newString) {
if (oldString == null && newString == null) {
return false;
}
else if ((oldString == null && newString != null)
|| (oldString != null && newString == null)) {
return true;
}
else {
return !oldString.equals(newString);
}
}
/**
* Returns a formatted String from time.
*
* @param diff the amount of elapsed time.
* @return the formatte String.
*/
public static String getTimeFromLong(long diff) {
final String HOURS = "h";
final String MINUTES = "min";
final String SECONDS = "sec";
final long MS_IN_A_DAY = 1000 * 60 * 60 * 24;
final long MS_IN_AN_HOUR = 1000 * 60 * 60;
final long MS_IN_A_MINUTE = 1000 * 60;
final long MS_IN_A_SECOND = 1000;
Date currentTime = new Date();
long numDays = diff / MS_IN_A_DAY;
diff = diff % MS_IN_A_DAY;
long numHours = diff / MS_IN_AN_HOUR;
diff = diff % MS_IN_AN_HOUR;
long numMinutes = diff / MS_IN_A_MINUTE;
diff = diff % MS_IN_A_MINUTE;
long numSeconds = diff / MS_IN_A_SECOND;
diff = diff % MS_IN_A_SECOND;
long numMilliseconds = diff;
StringBuffer buf = new StringBuffer();
if(numDays > 0){
buf.append(numDays + " d, ");
}
if (numHours > 0) {
buf.append(numHours + " " + HOURS + ", ");
}
if (numMinutes > 0) {
buf.append(numMinutes + " " + MINUTES);
}
//buf.append(numSeconds + " " + SECONDS);
String result = buf.toString();
if (numMinutes < 1) {
result = "< 1 minute";
}
return result;
}
/**
* Build a List of all elements in an Iterator.
*/
public static List iteratorAsList(Iterator i) {
ArrayList list = new ArrayList(10);
while (i.hasNext()) {
list.add(i.next());
}
return list;
}
/**
* Creates an Iterator that is the reverse of a ListIterator.
*/
public static Iterator reverseListIterator(ListIterator i) {
return new ReverseListIterator(i);
}
}
/**
* An Iterator that is the reverse of a ListIterator.
*/
class ReverseListIterator implements Iterator {
private ListIterator _i;
ReverseListIterator(ListIterator i) {
_i = i;
while (_i.hasNext()) _i.next();
}
public boolean hasNext() {
return _i.hasPrevious();
}
public Object next() {
return _i.previous();
}
public void remove() {
_i.remove();
}
} |
package org.jaxen.function;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import org.jaxen.BaseXPath;
import org.jaxen.FunctionCallException;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.dom.DOMXPath;
import org.w3c.dom.Document;
/**
* @author Elliotte Rusty Harold
*
*/
public class SubstringTest extends TestCase {
private Document doc;
public void setUp() throws ParserConfigurationException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
doc.appendChild(doc.createElement("root"));
}
public SubstringTest(String name) {
super(name);
}
public void testSubstringOfNumber() throws JaxenException
{
XPath xpath = new DOMXPath( "substring(1234, 3)" );
String result = (String) xpath.evaluate( doc );
assertEquals("34", result);
}
public void testSubstringOfNumber2() throws JaxenException
{
XPath xpath = new DOMXPath( "substring(1234, 2, 3)" );
String result = (String) xpath.evaluate( doc );
assertEquals("234", result);
}
// Unusual tests from XPath spec
public void testUnusualSubstring1() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 1.5, 2.6)" );
String result = (String) xpath.evaluate( doc );
assertEquals("234", result);
}
public void testUnusualSubstring2() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 0, 3)" );
String result = (String) xpath.evaluate( doc );
assertEquals("12", result);
}
public void testUnusualSubstring3() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 0 div 0, 3)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testUnusualSubstring4() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 1, 0 div 0)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testUnusualSubstring5() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', -42, 1 div 0)" );
String result = (String) xpath.evaluate( doc );
assertEquals("12345", result);
}
public void testUnusualSubstring6() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', -1 div 0, 1 div 0)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testSubstringOfNaN() throws JaxenException
{
XPath xpath = new DOMXPath( "substring(0 div 0, 2)" );
String result = (String) xpath.evaluate( doc );
assertEquals("aN", result);
}
public void testSubstringOfEmptyString() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('', 2)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testSubstringWithNegativeLength() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 2, -3)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testSubstringWithExcessiveLength() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 2, 32)" );
String result = (String) xpath.evaluate( doc );
assertEquals("2345", result);
}
public void testSubstringWithNegativeLength2() throws JaxenException
{
XPath xpath = new DOMXPath( "substring('12345', 2, -1)" );
String result = (String) xpath.evaluate( doc );
assertEquals("", result);
}
public void testSubstringFunctionRequiresAtLeastTwoArguments()
throws JaxenException {
BaseXPath xpath = new DOMXPath("substring('a')");
try {
xpath.selectNodes(doc);
fail("Allowed substring function with one argument");
}
catch (FunctionCallException ex) {
assertNotNull(ex.getMessage());
}
}
public void testSubstringFunctionRequiresAtMostThreeArguments()
throws JaxenException {
BaseXPath xpath = new DOMXPath("substring-after('a', 1, 1, 4)");
try {
xpath.selectNodes(doc);
fail("Allowed substring function with four arguments");
}
catch (FunctionCallException ex) {
assertNotNull(ex.getMessage());
}
}
} |
package imj3.draft.processing;
import static imj3.tools.AwtImage2D.awtRead;
import static imj3.tools.CommonSwingTools.limitHeight;
import static imj3.tools.CommonSwingTools.setModel;
import static net.sourceforge.aprog.swing.SwingTools.horizontalBox;
import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit;
import static net.sourceforge.aprog.swing.SwingTools.scrollable;
import static net.sourceforge.aprog.swing.SwingTools.verticalBox;
import static net.sourceforge.aprog.tools.Tools.append;
import static net.sourceforge.aprog.tools.Tools.array;
import static net.sourceforge.aprog.tools.Tools.baseName;
import static net.sourceforge.aprog.tools.Tools.join;
import imj2.tools.Canvas;
import imj3.draft.segmentation.ImageComponent;
import imj3.tools.CommonSwingTools.NestedList;
import imj3.tools.CommonSwingTools.PropertyGetter;
import imj3.tools.CommonSwingTools.PropertySetter;
import imj3.tools.CommonSwingTools.StringGetter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.prefs.Preferences;
import javax.swing.Box;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.IllegalInstantiationException;
/**
* @author codistmonk (creation 2015-02-13)
*/
public final class VisualAnalysis {
private VisualAnalysis() {
throw new IllegalInstantiationException();
}
static final Preferences preferences = Preferences.userNodeForPackage(VisualAnalysis.class);
public static final String IMAGE_FILE_PATH = "image.file.path";
/**
* @param commandLineArguments
* <br>Unused
*/
public static final void main(final String[] commandLineArguments) {
SwingTools.useSystemLookAndFeel();
final Context context = new Context();
SwingUtilities.invokeLater(new Runnable() {
@Override
public final void run() {
SwingTools.show(new MainPanel(context), VisualAnalysis.class.getSimpleName(), false);
context.setImageFile(new File(preferences.get(IMAGE_FILE_PATH, "")));
}
});
}
public static final Component label(final String text, final Component... components) {
return limitHeight(horizontalBox(append(array(new JLabel(text), Box.createGlue()), components)));
}
public static final <C extends JComponent> C centerX(final C component) {
component.setAlignmentX(Component.CENTER_ALIGNMENT);
return component;
}
public static final JTextField textView(final String text) {
final JTextField result = new JTextField(text);
result.setEditable(false);
return result;
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class MainPanel extends JPanel {
private final JComboBox<String> imageSelector;
private final JCheckBox imageVisibilitySelector;
private final JComboBox<String> groundTruthSelector;
private final JCheckBox groundTruthVisibilitySelector;
private final JComboBox<String> experimentSelector;
private final JTextField trainingTimeView;
private final JTextField classificationTimeView;
private final JCheckBox classificationVisibilitySelector;
private final JTextField scoreView;
private final JTree tree;
private final JSplitPane mainSplitPane;
public MainPanel(final Context context) {
super(new BorderLayout());
this.imageSelector = new JComboBox<>(array("-", "Open..."));
this.imageVisibilitySelector = new JCheckBox("", true);
this.groundTruthSelector = new JComboBox<>(array("-", "New...", "Save"));
this.groundTruthVisibilitySelector = new JCheckBox();
this.experimentSelector = new JComboBox<>(array("-", "New...", "Open...", "Save"));
this.trainingTimeView = textView("-");
this.classificationTimeView = textView("-");
this.classificationVisibilitySelector = new JCheckBox();
this.scoreView = textView("-");
this.tree = new JTree();
final int padding = this.imageVisibilitySelector.getPreferredSize().width;
this.mainSplitPane = horizontalSplit(verticalBox(
label(" Image: ", this.imageSelector, this.imageVisibilitySelector),
label(" Ground truth: ", this.groundTruthSelector, this.groundTruthVisibilitySelector),
label(" Experiment: ", this.experimentSelector, Box.createHorizontalStrut(padding)),
label(" Training (s): ", this.trainingTimeView, Box.createHorizontalStrut(padding)),
label(" Classification (s): ", this.classificationTimeView, this.classificationVisibilitySelector),
label(" F1: ", this.scoreView, Box.createHorizontalStrut(padding)),
centerX(new JButton("Confusion matrix...")),
scrollable(this.tree)), scrollable(new JLabel("Drop file here")));
setModel(this.tree, context.setExperiment(new Experiment()).getExperiment(), "Session");
this.add(this.mainSplitPane, BorderLayout.CENTER);
{
this.imageSelector.setRenderer(new DefaultListCellRenderer() {
@Override
public final Component getListCellRendererComponent(final JList<?> list,
final Object value, final int index, final boolean isSelected,
final boolean cellHasFocus) {
final Component result = super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (index < 0 || isSelected) {
this.setText(new File(this.getText()).getName());
}
return result;
}
private static final long serialVersionUID = -3014056515590258107L;
});
this.imageSelector.addActionListener(new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
final int n = MainPanel.this.getImageSelector().getItemCount();
final int selectedIndex = MainPanel.this.getImageSelector().getSelectedIndex();
if (selectedIndex < n - IMAGE_SELECTOR_RESERVED_SLOTS) {
context.setImageFile(new File(MainPanel.this.getImageSelector().getSelectedItem().toString()));
} else if (selectedIndex == n - 1) {
}
}
});
}
this.setDropTarget(new DropTarget() {
@Override
public final synchronized void drop(final DropTargetDropEvent event) {
final File file = SwingTools.getFiles(event).get(0);
if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".xml")) {
} else {
context.setImageFile(file);
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 5442000733451223725L;
});
this.setPreferredSize(new Dimension(800, 600));
context.setMainPanel(this);
}
public final JComboBox<String> getImageSelector() {
return this.imageSelector;
}
public final JTree getTree() {
return this.tree;
}
public final void setContents(final Component component) {
this.mainSplitPane.setRightComponent(scrollable(component));
}
private static final long serialVersionUID = 2173077945563031333L;
public static final int IMAGE_SELECTOR_RESERVED_SLOTS = 2;
}
/**
* @author codistmonk (creation 2015-02-13)
*/
public static final class Context implements Serializable {
private MainPanel mainPanel;
private File experimentFile = new File("experiment.xml");
private File imageFile;
private String groundTruthName = "gt";
private Experiment experiment;
private BufferedImage image;
private final Canvas groundTruth = new Canvas();
private final Canvas classification = new Canvas();
public final MainPanel getMainPanel() {
return this.mainPanel;
}
public final void setMainPanel(final MainPanel mainPanel) {
this.mainPanel = mainPanel;
}
public final File getExperimentFile() {
return this.experimentFile;
}
public final Context setExperimentFile(final File experimentFile) {
this.experimentFile = experimentFile;
return this;
}
public final String getGroundTruthName() {
return this.groundTruthName;
}
public final Context setGroundTruthName(final String groundTruthName) {
this.groundTruthName = groundTruthName;
return this;
}
public final Experiment getExperiment() {
return this.experiment;
}
public final Context setExperiment(final Experiment experiment) {
this.experiment = experiment;
return this;
}
public final BufferedImage getImage() {
return this.image;
}
public final Canvas getGroundTruth() {
return this.groundTruth;
}
public final Canvas getClassification() {
return this.classification;
}
public final String getExperimentName() {
return baseName(this.getExperimentFile().getName());
}
public final String getGroundTruthPath() {
return baseName(this.imageFile.getPath()) + "_groundtruth_" + this.getGroundTruthName() + "_" + this.getExperimentName() + ".png";
}
public final String getClassificationPath() {
return baseName(this.imageFile.getPath()) + "_classification_" + this.getGroundTruthName() + "_" + this.getExperimentName() + ".png";
}
public final void refreshGroundTruthAndClassification(final Refresh refresh) {
final int imageWidth = this.getImage().getWidth();
final int imageHeight = this.getImage().getHeight();
this.getGroundTruth().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
this.getClassification().setFormat(imageWidth, imageHeight, BufferedImage.TYPE_INT_ARGB);
switch (refresh) {
case CLEAR:
this.getGroundTruth().clear(CLEAR);
this.getClassification().clear(CLEAR);
break;
case FROM_FILE:
{
{
final String groundTruthPath = this.getGroundTruthPath();
if (new File(groundTruthPath).isFile()) {
this.getGroundTruth().getGraphics().drawImage(awtRead(groundTruthPath), 0, 0, null);
} else {
this.getGroundTruth().clear(CLEAR);
}
}
{
final String classificationPath = this.getClassificationPath();
if (new File(classificationPath).isFile()) {
this.getClassification().getGraphics().drawImage(awtRead(classificationPath), 0, 0, null);
} else {
this.getClassification().clear(CLEAR);
}
}
break;
}
case NOP:
break;
}
}
public final void setImageFile(final File imageFile) {
if (imageFile.isFile()) {
this.image = awtRead(imageFile.getPath());
this.imageFile = imageFile;
this.refreshGroundTruthAndClassification(Refresh.FROM_FILE);
this.getMainPanel().setContents(new ImageComponent(this.getImage()));
final JComboBox<String> imageSelector = this.getMainPanel().getImageSelector();
final DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) imageSelector.getModel();
model.insertElementAt(imageFile.getPath(), 0);
for (int i = model.getSize() - MainPanel.IMAGE_SELECTOR_RESERVED_SLOTS - 1; 0 < i; --i) {
if (model.getElementAt(i).equals(imageFile.getPath())) {
model.removeElementAt(i);
}
}
imageSelector.setSelectedIndex(0);
preferences.put(IMAGE_FILE_PATH, imageFile.getPath());
}
}
private static final long serialVersionUID = -2487965125442868238L;
public static final Color CLEAR = new Color(0, true);
/**
* @author codistmonk (creation 2015-02-17)
*/
public static enum Refresh {
NOP, CLEAR, FROM_FILE;
}
}
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class Experiment implements Serializable {
private final List<ClassDescription> classDescriptions = new ArrayList<>();
private final List<TrainingField> trainingFields = new ArrayList<>();
@Override
public final String toString() {
return "Experiment";
}
@NestedList(name="classes", element="class", elementClass=ClassDescription.class)
public final List<ClassDescription> getClassDescriptions() {
return this.classDescriptions;
}
@NestedList(name="training", element="training field", elementClass=TrainingField.class)
public final List<TrainingField> getTrainingFields() {
return this.trainingFields;
}
private static final long serialVersionUID = -4539259556658072410L;
/**
* @author codistmonk (creation 2015-02-16)
*/
public static final class ClassDescription implements Serializable {
private String name = "class";
private int label = 0xFF000000;
@StringGetter
@PropertyGetter("name")
public final String getName() {
return this.name;
}
@PropertySetter("name")
public final ClassDescription setName(final String name) {
this.name = name;
return this;
}
public final int getLabel() {
return this.label;
}
public final ClassDescription setLabel(final int label) {
this.label = label;
return this;
}
@PropertyGetter("label")
public final String getLabelAsString() {
return "#" + Integer.toHexString(this.getLabel()).toUpperCase(Locale.ENGLISH);
}
@PropertySetter("label")
public final ClassDescription setLabel(final String labelAsString) {
return this.setLabel((int) Long.parseLong(labelAsString.substring(1), 16));
}
private static final long serialVersionUID = 4974707407567297906L;
}
/**
* @author codistmonk (creation 2015-02-17)
*/
public static final class TrainingField implements Serializable {
private String imagePath = "";
private final Rectangle bounds = new Rectangle();
@PropertyGetter("image")
public final String getImagePath() {
return this.imagePath;
}
@PropertySetter("image")
public final TrainingField setImagePath(final String imagePath) {
this.imagePath = imagePath;
return this;
}
public final Rectangle getBounds() {
return this.bounds;
}
@PropertyGetter("bounds")
public final String getBoundsAsString() {
return join(",", this.getBounds().x, this.getBounds().y, this.getBounds().width, this.getBounds().height);
}
@PropertySetter("bounds")
public final TrainingField setBounds(final String boundsAsString) {
final int[] bounds = Arrays.stream(boundsAsString.split(",")).mapToInt(Integer::parseInt).toArray();
this.getBounds().setBounds(bounds[0], bounds[1], bounds[2], bounds[3]);
return this;
}
@Override
public final String toString() {
return new File(this.getImagePath()).getName() + "[" + this.getBoundsAsString() + "]";
}
private static final long serialVersionUID = 847822079141878928L;
}
}
} |
package edu.ucdenver.ccp.util.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
import edu.ucdenver.ccp.util.string.StringUtil;
public class FileArchiveUtil {
private static final String gz_suffix = ".gz";
private static final String tgz_suffix = ".tgz";
private static final String zip_suffix = ".zip";
private static final String bzip_suffix = ".bz2";
private static final String z_suffix = ".z";
private static final String tar_suffix = ".tar";
public static InputStream getInputStream(File file) throws FileNotFoundException, IOException,
IllegalArgumentException {
if (isGzipFile(file)) {
return getGzipInputStream(file);
} else if (isZipFile(file)) {
return getZipInputStream(file);
} else if (isUnsupportedZipFormatFile(file)) {
throw new IllegalArgumentException(String.format(
"Method for reading compressed format is not supported for file: %s", file.getAbsolutePath()));
} else {
return new FileInputStream(file);
}
}
/**
* Returns a ZipInputStream for a .zip input file
*
* @param file
* @return
* @throws FileNotFoundException
*/
private static ZipInputStream getZipInputStream(File file) throws FileNotFoundException {
return new ZipInputStream(new BufferedInputStream(new CheckedInputStream(new FileInputStream(file),
new Adler32())));
}
/**
* Returns a GZIPInputStream for a .gz file
*
* @param file
* @return
* @throws IOException
* @throws FileNotFoundException
*/
private static InputStream getGzipInputStream(File file) throws IOException, FileNotFoundException {
return new GZIPInputStream(new FileInputStream(file));
}
private static boolean isUnsupportedZipFormatFile(File file) {
return isBZipFile(file) || isUnixCompressFile(file);
}
private static boolean hasCaseInsensitiveSuffix(File file, String fileSuffix) {
return file.getName().endsWith(fileSuffix.toLowerCase()) || file.getName().endsWith(fileSuffix.toUpperCase());
}
private static boolean isGzipFile(File file) {
return hasCaseInsensitiveSuffix(file, gz_suffix) || hasCaseInsensitiveSuffix(file, tgz_suffix);
}
private static boolean isZipFile(File file) {
return hasCaseInsensitiveSuffix(file, zip_suffix);
}
private static boolean isBZipFile(File file) {
return hasCaseInsensitiveSuffix(file, bzip_suffix);
}
private static boolean isUnixCompressFile(File file) {
return hasCaseInsensitiveSuffix(file, z_suffix);
}
private static boolean isTarFile(File file) {
return hasCaseInsensitiveSuffix(file, tar_suffix) || hasCaseInsensitiveSuffix(file, tgz_suffix);
}
public static void unpackTarFile(File tarFile, File outputDirectory) throws FileNotFoundException,
IllegalArgumentException, IOException {
FileUtil.validateDirectory(outputDirectory);
if (!isTarFile(tarFile)) {
throw new IllegalArgumentException(String.format("Cannot unpack. Input file is not a tarball: %s", tarFile
.getAbsolutePath()));
}
TarInputStream tis = null;
try {
tis = new TarInputStream(getInputStream(tarFile));
TarEntry tarEntry;
while ((tarEntry = tis.getNextEntry()) != null) {
copyTarEntryToFileSystem(tis, tarEntry, outputDirectory);
}
} finally {
IOUtils.closeQuietly(tis);
}
}
/**
* Copies the current TarEntry to the file system. If it is a directory, a directory is created,
* otherwise a file is created.
*
* @param outputDirectory
* @param tis
* @param tarEntry
* @throws FileNotFoundException
* @throws IOException
*/
private static void copyTarEntryToFileSystem(TarInputStream tis, TarEntry tarEntry, File outputDirectory)
throws FileNotFoundException, IOException {
File outputPath = new File(outputDirectory.getAbsolutePath() + File.separator + tarEntry.getName());
if (tarEntry.isDirectory()) {
FileUtil.mkdir(outputPath);
} else {
copyTarEntryToFile(tis, outputPath);
}
}
/**
* Copies the current TarEntry to the specified output file
*
* @param tis
* @param outputFile
* @throws FileNotFoundException
* @throws IOException
*/
private static void copyTarEntryToFile(TarInputStream tis, File outputFile) throws FileNotFoundException,
IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outputFile);
tis.copyEntryContents(fos);
} finally {
IOUtils.closeQuietly(fos);
}
}
public static void unzip(File zippedFile, File outputDirectory) throws IOException {
InputStream is = null;
try {
if (isZipFile(zippedFile)) {
is = getZipInputStream(zippedFile);
unzip((ZipInputStream) is, outputDirectory);
} else if (isGzipFile(zippedFile)) {
is = getGzipInputStream(zippedFile);
unzip((GZIPInputStream) is, getUnzippedFileName(zippedFile.getName()), outputDirectory);
} else {
throw new IllegalArgumentException(String.format("Unable to unzip file: %s", zippedFile
.getAbsolutePath()));
}
} finally {
IOUtils.closeQuietly(is);
}
}
/**
* Takes as input a file name e.g. myFile.txt.gz and outputs myFile.txt. Handles both .gz and
* .tgz suffixes.
*
* @param name
* @return
*/
private static String getUnzippedFileName(String filename) {
if (filename.endsWith(gz_suffix.toLowerCase())) {
return StringUtil.removeSuffix(filename, gz_suffix.toLowerCase());
} else if (filename.endsWith(gz_suffix.toUpperCase())) {
return StringUtil.removeSuffix(filename, gz_suffix.toUpperCase());
} else if (filename.endsWith(tgz_suffix.toLowerCase())) {
return StringUtil.replaceSuffix(filename, tgz_suffix.toLowerCase(), tar_suffix.toLowerCase());
} else if (filename.endsWith(tgz_suffix.toUpperCase())) {
return StringUtil.replaceSuffix(filename, tgz_suffix.toUpperCase(), tar_suffix.toUpperCase());
} else {
throw new IllegalArgumentException(String.format(
"Only works for .gz and .tgz filenames. Input filename was: %s", filename));
}
}
public static void unzip(GZIPInputStream gzipInputStream, String outputFileName, File outputDirectory)
throws IOException {
File outputFile = new File(outputDirectory.getAbsolutePath() + File.separator + outputFileName);
FileUtil.copy(gzipInputStream, outputFile);
}
/**
* Unzips the input ZipInputStream to the specified directory
*
* @param zis
* @param outputDirectory
* @throws IOException
*/
public static void unzip(ZipInputStream zis, File outputDirectory) throws IOException {
ZipEntry zipEntry = null;
while ((zipEntry = zis.getNextEntry()) != null) {
copyZipEntryToFileSystem(zis, zipEntry, outputDirectory);
}
}
/**
* Copies the contents of the current ZipEntry to the file system. If the ZipEntry is a
* directory, then a directory is created, otherwise a file is created.
*
* @param zis
* @param zipEntry
* @param outputDirectory
* @throws FileNotFoundException
* @throws IOException
*/
private static void copyZipEntryToFileSystem(ZipInputStream zis, ZipEntry zipEntry, File outputDirectory)
throws FileNotFoundException, IOException {
File outputPathFile = new File(outputDirectory.getAbsolutePath() + File.separator + zipEntry.getName());
if (zipEntry.isDirectory()) {
FileUtil.mkdir(outputPathFile);
} else {
copyZipEntryToFile(zis, outputPathFile);
}
}
/**
* Creates a new file on the file system containing the contents of the current ZipEntry TODO:
* Use CheckSums?
*
* @param zis
* @param zipEntry
* @param outputDirectory
* @throws IOException
*/
private static void copyZipEntryToFile(ZipInputStream zis, File unzippedFile)
throws IOException {
FileUtil.copy(zis, unzippedFile);
}
} |
package org.modmine.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebResults;
import org.intermine.api.util.NameUtil;
import org.intermine.bio.web.model.GenomicRegion;
import org.intermine.bio.web.struts.GFF3ExportForm;
import org.intermine.bio.web.struts.SequenceExportForm;
import org.intermine.metadata.Model;
import org.intermine.model.bio.Submission;
import org.intermine.objectstore.ObjectStore;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.OuterJoinStatus;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.bag.BagHelper;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.export.http.TableExporterFactory;
import org.intermine.web.logic.export.http.TableHttpExporter;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.ForwardParameters;
import org.intermine.web.struts.InterMineAction;
import org.intermine.web.struts.TableExportForm;
import org.modmine.web.model.SpanQueryResultRow;
import org.modmine.web.model.SpanUploadConstraint;
/**
* Generate queries for overlaps of submission features and overlaps with gene flanking regions.
*
* @author Richard Smith
*/
public class FeaturesAction extends InterMineAction
{
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(FeaturesAction.class);
/**
* Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ObjectStore os = im.getObjectStore();
Model model = im.getModel();
String type = request.getParameter("type");
String featureType = request.getParameter("feature");
String action = request.getParameter("action");
String dccId = null;
String sourceFile = null;
String experimentName = null;
final Map<String, LinkedList<String>> gffFields = new HashMap<String, LinkedList<String>>();
populateGFFRelationships(gffFields);
boolean doGzip = false;
if (request.getParameter("gzip") != null
&& request.getParameter("gzip").equalsIgnoreCase("true")) {
doGzip = true;
}
Set<Integer> taxIds = new HashSet<Integer>();
PathQuery q = new PathQuery(model);
boolean hasPrimer = false;
if ("experiment".equals(type)) {
experimentName = request.getParameter("experiment");
DisplayExperiment exp = MetadataCache.getExperimentByName(os, experimentName);
Set<String> organisms = exp.getOrganisms();
taxIds = getTaxonIds(organisms);
if (featureType.equalsIgnoreCase("all")) {
// fixed query for the moment
String project = request.getParameter("project");
String rootChoice = getRootFeature(project);
List<String> gffFeatures = new LinkedList<String>(gffFields.get(project));
for (String f : gffFeatures) {
q.addView(f + ".primaryIdentifier");
q.addView(f + ".score");
}
q.addConstraint(Constraints.eq(rootChoice + ".submissions.experiment.name",
experimentName));
} else {
List<String> expSubsIds = exp.getSubmissionsDccId();
Set<String> allUnlocated = new HashSet<String>();
String ef = getFactors(exp);
if (ef.contains("primer")) {
hasPrimer = true;
}
String description = "All " + featureType + " features generated by experiment '"
+ exp.getName() + "' in " + StringUtil.prettyList(exp.getOrganisms())
+ " (" + exp.getPi() + ")." + ef;
q.setDescription(description);
for (String subId : expSubsIds) {
if (MetadataCache.getUnlocatedFeatureTypes(os).containsKey(subId))
{
allUnlocated.addAll(
MetadataCache.getUnlocatedFeatureTypes(os).get(subId));
}
}
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
if ("results".equals(action)) {
// we don't want this field on exports
q.addView(featureType + ".scoreProtocol.name");
q.setOuterJoinStatus(featureType + ".scoreProtocol",
OuterJoinStatus.OUTER);
}
q.addConstraint(Constraints.eq(featureType + ".submissions.experiment.name",
experimentName));
if (allUnlocated.contains(featureType)) {
q.addView(featureType + ".submissions.DCCid");
addEFactorToQuery(q, featureType, hasPrimer);
} else {
addLocationToQuery(q, featureType);
addEFactorToQuery(q, featureType, hasPrimer);
}
}
} else if ("submission".equals(type)) {
dccId = request.getParameter("submission");
sourceFile = request.getParameter("file").replace(" ", "+");
Submission sub = MetadataCache.getSubmissionByDccId(os, dccId);
List<String> unlocFeatures =
MetadataCache.getUnlocatedFeatureTypes(os).get(dccId);
Integer organism = sub.getOrganism().getTaxonId();
taxIds.add(organism);
if (featureType.equalsIgnoreCase("all")) {
String project = request.getParameter("project");
String rootChoice = getRootFeature(project);
List<String> gffFeatures = new LinkedList<String>(gffFields.get(project));
for (String f : gffFeatures) {
q.addView(f + ".primaryIdentifier");
q.addView(f + ".score");
}
q.addConstraint(Constraints.eq(rootChoice + ".submissions.DCCid", dccId));
} else {
// to build the query description
String experimentType = "";
if (!StringUtils.isBlank(sub.getExperimentType())) {
experimentType = StringUtil.indefiniteArticle(sub.getExperimentType())
+ " " + sub.getExperimentType() + " experiment in";
}
String efSub = "";
if (SubmissionHelper.getExperimentalFactorString(sub).length() > 1) {
efSub = " using " + SubmissionHelper.getExperimentalFactorString(sub);
if (efSub.contains("primer")) {
hasPrimer = true;
efSub = "";
}
}
String description = "All " + featureType
+ " features generated by submission " + dccId
+ ", " + experimentType + " "
+ sub.getOrganism().getShortName() + efSub
+ " (" + sub.getProject().getSurnamePI() + ").";
q.setDescription(description);
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
if ("results".equals(action)) {
q.addView(featureType + ".scoreProtocol.name");
q.setOuterJoinStatus(featureType + ".scoreProtocol",
OuterJoinStatus.OUTER);
}
q.addConstraint(Constraints.eq(featureType + ".submissions.DCCid", dccId));
if (unlocFeatures == null || !unlocFeatures.contains(featureType)) {
addLocationToQuery(q, featureType);
addEFactorToQuery(q, featureType, hasPrimer);
} else {
q.addView(featureType + ".submissions.DCCid");
addEFactorToQuery(q, featureType, hasPrimer);
}
// source file
if (sourceFile != null) {
LOG.info("TOPATHQFF: " + sourceFile);
q.addConstraint(Constraints.eq(featureType + ".sourceFile", sourceFile));
}
}
} else if ("subEL".equals(type)) {
// For the expression levels
dccId = request.getParameter("submission");
q.addConstraint(Constraints.type("Submission.features", featureType));
String path = "Submission.features.expressionLevels";
q.addView(path + ".name");
q.addView(path + ".value");
q.addView(path + ".readCount");
q.addView(path + ".dcpm");
q.addView(path + ".dcpmBases");
q.addView(path + ".transcribed");
q.addView(path + ".predictionStatus");
q.addConstraint(Constraints.eq("Submission.DCCid", dccId));
} else if ("expEL".equals(type)) {
String eName = request.getParameter("experiment");
q.addConstraint(Constraints.type("Experiment.submissions.features", featureType));
String path = "Experiment.submissions.features.expressionLevels";
q.addView(path + ".name");
q.addView(path + ".value");
q.addView(path + ".readCount");
q.addView(path + ".dcpm");
q.addView(path + ".dcpmBases");
q.addView(path + ".transcribed");
q.addView(path + ".predictionStatus");
q.addConstraint(Constraints.eq("Experiment.name", eName));
} else if ("span".equals(type)) {
@SuppressWarnings("unchecked")
Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>> spanOverlapFullResultMap =
(Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>>) request
.getSession().getAttribute("spanOverlapFullResultMap");
@SuppressWarnings("unchecked")
Map<SpanUploadConstraint, String> spanConstraintMap =
(HashMap<SpanUploadConstraint, String>) request
.getSession().getAttribute("spanConstraintMap");
String spanUUIDString = request.getParameter("spanUUIDString");
String criteria = request.getParameter("criteria");
// Use feature pids as the value in lookup constraint
Set<Integer> value =
getSpanOverlapFeatures(spanUUIDString, criteria, spanOverlapFullResultMap);
// Create a path query
String path = "SequenceFeature";
q.addView(path + ".primaryIdentifier");
q.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier");
q.addView(path + ".chromosomeLocation.start");
q.addView(path + ".chromosomeLocation.end");
q.addView(path + ".submissions.DCCid");
q.addView(path + ".submissions.title");
q.addView(path + ".organism.name");
// q.addConstraint(Constraints.lookup(path, value, null));
q.addConstraint(Constraints.inIds(path, value));
String organism = getSpanOrganism(spanUUIDString, spanConstraintMap);
Set<String> organisms = new HashSet<String>();
organisms.add(organism);
taxIds = getTaxonIds(organisms);
}
if ("results".equals(action)) {
String qid = SessionMethods.startQueryWithTimeout(request, false, q);
Thread.sleep(200);
return new ForwardParameters(mapping.findForward("waiting"))
.addParameter("qid", qid)
.forward();
} else if ("export".equals(action)) {
String format = request.getParameter("format");
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
PagedTable pt = new PagedTable(executor.execute(q));
if (pt.getWebTable() instanceof WebResults) {
((WebResults) pt.getWebTable()).goFaster();
}
WebConfig webConfig = SessionMethods.getWebConfig(request);
TableExporterFactory factory = new TableExporterFactory(webConfig);
TableHttpExporter exporter = factory.getExporter(format);
if (exporter == null) {
throw new RuntimeException("unknown export format: " + format);
}
TableExportForm exportForm = new TableExportForm();
// Ref to StandardHttpExporter
exportForm.setIncludeHeaders(true);
if ("gff3".equals(format)) {
boolean makeUcscCompatible = readUcscParameter(request);
exportForm = new GFF3ExportForm();
exportForm.setDoGzip(doGzip);
((GFF3ExportForm) exportForm).setMakeUcscCompatible(makeUcscCompatible);
((GFF3ExportForm) exportForm).setOrganisms(taxIds);
}
if ("sequence".equals(format)) {
exportForm = new SequenceExportForm();
exportForm.setDoGzip(doGzip);
}
exporter.export(pt, request, response, exportForm);
// If null is returned then no forwarding is performed and
// to the output is not flushed any jsp output, so user
// will get only required export data
return null;
} else if ("list".equals(action)) {
// need to select just id of featureType to create list
//q.clearView();
q.addView(featureType + ".id");
dccId = request.getParameter("submission");
q.addConstraint(Constraints.eq(featureType + ".submissions.DCCid", dccId));
sourceFile = request.getParameter("file").replace(" ", "+");
if (sourceFile != null) {
q.addConstraint(Constraints.eq(featureType + ".sourceFile", sourceFile));
}
Profile profile = SessionMethods.getProfile(session);
//BagQueryRunner bagQueryRunner = im.getBagQueryRunner();
String bagName = (dccId != null ? "submission_" + dccId : experimentName)
+ "_" + featureType + "_features";
bagName = NameUtil.generateNewName(profile.getSavedBags().keySet(), bagName);
BagHelper.createBagFromPathQuery(q, bagName, q.getDescription(), featureType, profile,
im);
ForwardParameters forwardParameters =
new ForwardParameters(mapping.findForward("bagDetails"));
return forwardParameters.addParameter("bagName", bagName).forward();
}
return null;
}
/**
* @param project
* @return
*/
private String getRootFeature(String project) {
String rootChoice = null;
if (project.equalsIgnoreCase("Waterston")) {
rootChoice = "Transcript";
} else {
rootChoice = "Gene";
}
return rootChoice;
}
private boolean readUcscParameter(HttpServletRequest request) {
String ucscParameter = request.getParameter("UCSC");
if (ucscParameter != null) {
return true;
}
return false;
}
private Map<String, LinkedList<String>>
populateGFFRelationships(Map<String, LinkedList<String>> m) {
final LinkedList<String> gffPiano = new LinkedList<String>();
gffPiano.add("Gene");
gffPiano.add("Gene.UTRs");
gffPiano.add("Gene.transcripts");
// gffPiano.add("Gene.transcripts.mRNA");
final LinkedList<String> gffCelniker = new LinkedList<String>();
gffCelniker.add("Gene.transcripts.CDSs");
// gffCelniker.add("Gene.UTRs.transcripts.PolyASites");
gffCelniker.add("Gene.transcripts.startCodon");
gffCelniker.add("Gene.transcripts.stopCodon");
gffCelniker.add("Gene.transcripts.CDSs");
gffCelniker.add("Gene.transcripts.fivePrimeUTR");
gffCelniker.add("Gene.transcripts.threePrimeUTR");
final LinkedList<String> gffWaterston = new LinkedList<String>();
gffWaterston.add("Transcript.TSSs");
gffWaterston.add("Transcript.SL1AcceptorSites");
gffWaterston.add("Transcript.SL2AcceptorSites");
gffWaterston.add("Transcript.transcriptionEndSites");
gffWaterston.add("Transcript.polyASites");
gffWaterston.add("Transcript.introns");
gffWaterston.add("Transcript.exons");
m.put("Piano", gffPiano);
m.put("Celniker", gffCelniker);
m.put("Waterston", gffWaterston);
return m;
}
/**
* @param q
* @param featureType
* @param hasPrimer
*/
private void addEFactorToQuery(PathQuery q, String featureType,
boolean hasPrimer) {
if (!hasPrimer) {
q.addView(featureType + ".submissions.experimentalFactors.type");
q.addView(featureType + ".submissions.experimentalFactors.name");
q.setOuterJoinStatus(featureType + ".submissions.experimentalFactors",
OuterJoinStatus.OUTER);
}
}
/**
* @param q
* @param featureType the feature type
*/
private void addLocationToQuery(PathQuery q, String featureType) {
q.addView(featureType + ".chromosome.primaryIdentifier");
q.addView(featureType + ".chromosomeLocation.start");
q.addView(featureType + ".chromosomeLocation.end");
q.addView(featureType + ".chromosomeLocation.strand");
q.addView(featureType + ".submissions.DCCid");
q.addOrderBy(featureType + ".chromosome.primaryIdentifier", OrderDirection.ASC);
q.addOrderBy(featureType + ".chromosomeLocation.start", OrderDirection.ASC);
}
private String getFactors(DisplayExperiment exp) {
String ef = "";
if (exp.getFactorTypes().size() == 1) {
ef = "Experimental factor is the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used.";
}
if (exp.getFactorTypes().size() > 1) {
ef = "Experimental factors are the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used.";
}
return ef;
}
private Set<Integer> getTaxonIds(Set<String> organisms) {
Set<Integer> taxIds = new HashSet<Integer>();
for (String name : organisms) {
if (name.equalsIgnoreCase("D. melanogaster")) {
taxIds.add(7227);
}
if (name.equalsIgnoreCase("C. elegans")) {
taxIds.add(6239);
}
}
return taxIds;
}
/**
* To export all overlap features
* @param spanUUIDString
* @param criteria could be "all" or a span string
* @param request HttpServletRequest
* @return comma separated feature pids as a string
*/
private Set<Integer> getSpanOverlapFeatures(String spanUUIDString, String criteria,
Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>> spanOverlapFullResultMap) {
Set<Integer> featureSet = new HashSet<Integer>();
Map<GenomicRegion, List<SpanQueryResultRow>> featureMap = spanOverlapFullResultMap
.get(spanUUIDString);
if ("all".equals(criteria)) {
for (List<SpanQueryResultRow> l : featureMap.values()) {
if (l != null) {
for (SpanQueryResultRow r : l) {
featureSet.add(r.getFeatureId());
}
}
}
} else {
GenomicRegion spanToExport = new GenomicRegion();
String[] temp = criteria.split(":");
spanToExport.setChr(temp[0]);
temp = temp[1].split("\\.\\.");
spanToExport.setStart(Integer.parseInt(temp[0]));
spanToExport.setEnd(Integer.parseInt(temp[1]));
for (SpanQueryResultRow r : featureMap.get(spanToExport)) {
featureSet.add(r.getFeatureId());
}
}
return featureSet;
}
private String getSpanOrganism(String spanUUIDString,
Map<SpanUploadConstraint, String> spanConstraintMap) {
for (Entry<SpanUploadConstraint, String> e : spanConstraintMap.entrySet()) {
if (e.getValue().equals(spanUUIDString)) {
return e.getKey().getSpanOrgName();
}
}
return null;
}
} |
package org.unitime.timetable.model;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.unitime.commons.Debug;
import org.unitime.commons.hibernate.util.HibernateUtil;
import org.unitime.timetable.defaults.ApplicationProperty;
import org.unitime.timetable.model.base.BaseSession;
import org.unitime.timetable.model.dao.ExamDAO;
import org.unitime.timetable.model.dao.SessionDAO;
import org.unitime.timetable.onlinesectioning.OnlineSectioningLog;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer;
import org.unitime.timetable.onlinesectioning.updates.ReloadOfferingAction;
import org.unitime.timetable.security.Qualifiable;
import org.unitime.timetable.security.UserContext;
import org.unitime.timetable.solver.service.SolverServerService;
import org.unitime.timetable.spring.SpringApplicationContextHolder;
import org.unitime.timetable.util.DateUtils;
import org.unitime.timetable.util.ReferenceList;
/**
* @hibernate.class table="SESSIONS" schema = "TIMETABLE"
*
* @author Tomas Muller, Stephanie Schluttenhofer, Zuzana Mullerova
*/
public class Session extends BaseSession implements Comparable, Qualifiable {
public static final int sHolidayTypeNone = 0;
public static final int sHolidayTypeHoliday = 1;
public static final int sHolidayTypeBreak = 2;
public static String[] sHolidayTypeNames = new String[] { "No Holiday",
"Holiday", "(Spring/October/Thanksgiving) Break" };
public static String[] sHolidayTypeColors = new String[] {
"rgb(240,240,240)", "rgb(200,30,20)", "rgb(240,50,240)" };
private static final long serialVersionUID = 3691040980400813366L;
/*
* @return all sessions
*/
public static TreeSet<Session> getAllSessions() throws HibernateException {
TreeSet<Session> ret = new TreeSet<Session>();
for (Session session: SessionDAO.getInstance().findAll()) {
if (session.getStatusType() != null && !session.getStatusType().isTestSession())
ret.add(session);
}
return ret;
}
/**
* @param id
* @return
* @throws HibernateException
*/
public static Session getSessionById(Long id) throws HibernateException {
return (new SessionDAO()).get(id);
}
private static void deleteObjects(org.hibernate.Session hibSession, String objectName, Iterator idIterator) {
StringBuffer ids = new StringBuffer();
int idx = 0;
while (idIterator.hasNext()) {
ids.append(idIterator.next()); idx++;
if (idx==100) {
hibSession.createQuery("delete "+objectName+" as x where x.uniqueId in ("+ids+")").executeUpdate();
ids = new StringBuffer();
idx = 0;
} else if (idIterator.hasNext()) {
ids.append(",");
}
}
if (idx>0)
hibSession.createQuery("delete "+objectName+" as x where x.uniqueId in ("+ids+")").executeUpdate();
}
/**
* @param id
* @throws HibernateException
*/
public static void deleteSessionById(Long id) throws HibernateException {
org.hibernate.Session hibSession = new SessionDAO().getSession();
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
for (Iterator i=hibSession.createQuery("from Location where session.uniqueId = :sessionId").setLong("sessionId", id).iterate();i.hasNext();) {
Location loc = (Location)i.next();
loc.getFeatures().clear();
loc.getRoomGroups().clear();
hibSession.update(loc);
}
/*
for (Iterator i=hibSession.createQuery("from Exam where session.uniqueId=:sessionId").setLong("sessionId", id).iterate();i.hasNext();) {
Exam x = (Exam)i.next();
for (Iterator j=x.getConflicts().iterator();j.hasNext();) {
ExamConflict conf = (ExamConflict)j.next();
hibSession.delete(conf);
j.remove();
}
hibSession.update(x);
}
*/
hibSession.flush();
hibSession.createQuery(
"delete DistributionPref p where p.owner in (select s from Session s where s.uniqueId=:sessionId)").
setLong("sessionId", id).
executeUpdate();
hibSession.createQuery(
"delete InstructionalOffering o where o.session.uniqueId=:sessionId").
setLong("sessionId", id).
executeUpdate();
hibSession.createQuery(
"delete Department d where d.session.uniqueId=:sessionId").
setLong("sessionId", id).
executeUpdate();
hibSession.createQuery(
"delete Session s where s.uniqueId=:sessionId").
setLong("sessionId", id).
executeUpdate();
String[] a = { "DistributionPref", "RoomPref", "RoomGroupPref", "RoomFeaturePref", "BuildingPref", "TimePref", "DatePatternPref", "ExamPeriodPref" };
for (String str : a) {
hibSession.createQuery(
"delete " + str + " p where owner not in (from PreferenceGroup)").
executeUpdate();
}
deleteObjects(
hibSession,
"ExamConflict",
hibSession.createQuery("select x.uniqueId from ExamConflict x where x.exams is empty").iterate()
);
tx.commit();
} catch (HibernateException e) {
try {
if (tx!=null && tx.isActive()) tx.rollback();
} catch (Exception e1) { }
throw e;
}
HibernateUtil.clearCache();
}
public void saveOrUpdate() throws HibernateException {
(new SessionDAO()).saveOrUpdate(this);
}
public String getAcademicYearTerm() {
return (getAcademicYear() + getAcademicTerm());
}
/**
* @return Returns the term.
*/
public String getTermLabel() {
return this.getAcademicTerm();
}
/**
* @return Returns the label.
*/
public String getLabel() {
return getAcademicTerm() + " " + getAcademicYear() + " (" + getAcademicInitiative() + ")";
}
public String getReference() {
return getAcademicTerm() + getAcademicYear() + getAcademicInitiative();
}
public String toString() {
return this.getLabel();
}
/**
* @return Returns the year the session begins.
*/
public int getSessionStartYear() {
if (getSessionBeginDateTime()!=null) {
Calendar c = Calendar.getInstance(Locale.US);
c.setTime(getSessionBeginDateTime());
return c.get(Calendar.YEAR);
}
return Integer.parseInt(this.getAcademicYear());
}
/**
* @return Returns the year.
*/
public static int getYear(String acadYrTerm) {
return Integer.parseInt(acadYrTerm.substring(0, 4));
}
/**
* @param bldgUniqueId
* @return
*/
public Building building(String bldgUniqueId) {
// TODO make faster
for (Iterator it = this.getBuildings().iterator(); it.hasNext();) {
Building bldg = (Building) it.next();
if (bldg.getExternalUniqueId().equals(bldgUniqueId)) {
return bldg;
}
}
return null;
}
public String academicInitiativeDisplayString() {
return this.getAcademicInitiative();
}
public String statusDisplayString() {
return getStatusType().getLabel();
}
/**
* @return Returns the sessionStatusMap.
*/
public static ReferenceList getSessionStatusList(boolean includeTestSessions) {
ReferenceList ref = new ReferenceList();
ref.addAll(DepartmentStatusType.findAllForSession(includeTestSessions));
return ref;
}
public static Session getSessionUsingInitiativeYearTerm(
String academicInitiative, String academicYear, String academicTerm) {
Session s = null;
StringBuffer queryString = new StringBuffer();
SessionDAO sdao = new SessionDAO();
queryString.append(" from Session as s where s.academicInitiative = '"
+ academicInitiative + "' ");
queryString.append(" and s.academicYear = '" + academicYear + "' ");
queryString.append(" and s.academicTerm = '" + academicTerm + "' ");
Query q = sdao.getQuery(queryString.toString());
if (q.list().size() == 1) {
s = (Session) q.list().iterator().next();
}
return (s);
}
public Session getLastLikeSession() {
String lastYr = new Integer(this.getSessionStartYear() - 1).toString();
return getSessionUsingInitiativeYearTerm(this.getAcademicInitiative(),
lastYr, getAcademicTerm());
}
public Session getNextLikeSession() {
String nextYr = new Integer(this.getSessionStartYear() + 1).toString();
return getSessionUsingInitiativeYearTerm(this.getAcademicInitiative(),
nextYr, getAcademicTerm());
}
public String loadInstrAndCrsOffering() throws Exception {
return ("done");
}
public Long getSessionId() {
return (this.getUniqueId());
}
public void setSessionId(Long sessionId) {
this.setUniqueId(sessionId);
}
public String htmlLabel() {
return (this.getLabel());
}
public Date earliestSessionRelatedDate(){
return(getEventBeginDate()!=null&&getEventBeginDate().before(getSessionBeginDateTime())?getEventBeginDate():getSessionBeginDateTime());
}
public Date latestSessionRelatedDate(){
return(getEventEndDate()!=null&&getEventEndDate().after(getSessionEndDateTime())?getEventEndDate():getSessionEndDateTime());
}
public int getStartMonth() {
return DateUtils.getStartMonth(
earliestSessionRelatedDate(),
getSessionStartYear(),
ApplicationProperty.SessionNrExcessDays.intValue());
}
public int getEndMonth() {
return DateUtils.getEndMonth(
latestSessionRelatedDate(), getSessionStartYear(),
ApplicationProperty.SessionNrExcessDays.intValue());
}
public int getPatternStartMonth() {
return getStartMonth() - ApplicationProperty.DatePatternNrExessMonth.intValue();
}
public int getPatternEndMonth() {
return getEndMonth() + ApplicationProperty.DatePatternNrExessMonth.intValue();
}
public int getDayOfYear(int day, int month) {
return DateUtils.getDayOfYear(day, month, getSessionStartYear());
}
public int getHoliday(int day, int month) {
return getHoliday(day, month, getSessionStartYear(), getStartMonth(), getHolidays());
}
public static int getHoliday(int day, int month, int year, int startMonth, String holidays) {
try {
if (holidays == null)
return sHolidayTypeNone;
int idx = DateUtils.getDayOfYear(day, month, year)
- DateUtils.getDayOfYear(1, startMonth, year);
if (idx < 0 || idx >= holidays.length())
return sHolidayTypeNone;
return (int) (holidays.charAt(idx) - '0');
} catch (IndexOutOfBoundsException e) {
return sHolidayTypeNone;
}
}
public String getHolidaysHtml() {
return getHolidaysHtml(true);
}
public String getHolidaysHtml(boolean editable) {
return getHolidaysHtml(getSessionBeginDateTime(), getSessionEndDateTime(), getClassesEndDateTime(), getExamBeginDate(), getEventBeginDate(), getEventEndDate(), getSessionStartYear(), getHolidays(), editable, EventDateMapping.getMapping(getUniqueId()));
}
public static String getHolidaysHtml(
Date sessionBeginTime,
Date sessionEndTime,
Date classesEndTime,
Date examBeginTime,
Date eventBeginTime,
Date eventEndTime,
int acadYear,
String holidays,
boolean editable,
EventDateMapping.Class2EventDateMap class2eventDateMap) {
StringBuffer prefTable = new StringBuffer();
StringBuffer prefNames = new StringBuffer();
StringBuffer prefColors = new StringBuffer();
for (int i = 0; i < sHolidayTypeNames.length; i++) {
prefTable.append((i == 0 ? "" : ",") + "'" + i + "'");
prefNames.append((i == 0 ? "" : ",") + "'" + sHolidayTypeNames[i]
+ "'");
prefColors.append((i == 0 ? "" : ",") + "'" + sHolidayTypeColors[i]
+ "'");
}
StringBuffer holidayArray = new StringBuffer();
StringBuffer borderArray = new StringBuffer();
StringBuffer colorArray = new StringBuffer();
Calendar sessionBeginDate = Calendar.getInstance(Locale.US);
sessionBeginDate.setTime(sessionBeginTime);
Calendar sessionEndDate = Calendar.getInstance(Locale.US);
sessionEndDate.setTime(sessionEndTime);
Calendar classesEndDate = Calendar.getInstance(Locale.US);
classesEndDate.setTime(classesEndTime);
Calendar examBeginDate = Calendar.getInstance(Locale.US);
if (examBeginTime!=null) examBeginDate.setTime(examBeginTime);
Calendar eventBeginDate = Calendar.getInstance(Locale.US);
if (eventBeginTime!=null) eventBeginDate.setTime(eventBeginTime);
Calendar eventEndDate = Calendar.getInstance(Locale.US);
if (eventEndTime!=null) eventEndDate.setTime(eventEndTime);
int startMonth = DateUtils.getStartMonth(eventBeginTime!=null&&eventBeginTime.before(sessionBeginTime)?eventBeginTime:sessionBeginTime, acadYear, ApplicationProperty.SessionNrExcessDays.intValue());
int endMonth = DateUtils.getEndMonth(eventEndTime!=null&&eventEndTime.after(sessionEndTime)?eventEndTime:sessionEndTime, acadYear, ApplicationProperty.SessionNrExcessDays.intValue());
for (int m = startMonth; m <= endMonth; m++) {
int yr = DateUtils.calculateActualYear(m, acadYear);
if (m != startMonth) {
holidayArray.append(",");
borderArray.append(",");
colorArray.append(",");
}
holidayArray.append("[");
borderArray.append("[");
colorArray.append("[");
int daysOfMonth = DateUtils.getNrDaysOfMonth(m, acadYear);
for (int d = 1; d <= daysOfMonth; d++) {
if (d > 1) {
holidayArray.append(",");
borderArray.append(",");
colorArray.append(",");
}
holidayArray.append("'" + getHoliday(d, m, acadYear, startMonth, holidays) + "'");
String color = "null";
if (class2eventDateMap != null) {
if (class2eventDateMap.hasClassDate(DateUtils.getDate(d, m, acadYear))) {
color = "'#c0c'";
} else if (class2eventDateMap.hasEventDate(DateUtils.getDate(d, m, acadYear))) {
color = "'#0cc'";
}
}
colorArray.append(color);
if (d == sessionBeginDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == sessionBeginDate.get(Calendar.MONTH)
&& yr == sessionBeginDate.get(Calendar.YEAR))
borderArray.append("'#660000 2px solid'");
else if (d == sessionEndDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == sessionEndDate.get(Calendar.MONTH)
&& yr == sessionEndDate.get(Calendar.YEAR))
borderArray.append("'#333399 2px solid'");
else if (d == classesEndDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == classesEndDate.get(Calendar.MONTH)
&& yr == classesEndDate.get(Calendar.YEAR))
borderArray.append("'#339933 2px solid'");
else if (d == examBeginDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == examBeginDate.get(Calendar.MONTH)
&& yr == examBeginDate.get(Calendar.YEAR))
borderArray.append("'#999933 2px solid'");
else if (d == eventBeginDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == eventBeginDate.get(Calendar.MONTH)
&& yr == eventBeginDate.get(Calendar.YEAR))
borderArray.append("'yellow 2px solid'");
else if (d == eventEndDate.get(Calendar.DAY_OF_MONTH)
&& (m%12) == eventEndDate.get(Calendar.MONTH)
&& yr == eventEndDate.get(Calendar.YEAR))
borderArray.append("'red 2px solid'");
else
borderArray.append("null");
}
holidayArray.append("]");
borderArray.append("]");
colorArray.append("]");
}
StringBuffer table = new StringBuffer();
table
.append("<script language='JavaScript' type='text/javascript' src='scripts/datepatt.js'></script>");
table.append("<script language='JavaScript'>");
table.append("calGenerate2(" + acadYear + "," + startMonth + ","
+ endMonth + "," + "[" + holidayArray + "]," + "[" + prefTable
+ "]," + "[" + prefNames + "]," + "[" + prefColors + "]," + "'"
+ sHolidayTypeNone + "'," + "[" + borderArray + "],[" + colorArray + "]," + editable
+ "," + editable + ");");
table.append("</script>");
return table.toString();
}
public void setHolidays(String holidays) {
super.setHolidays(holidays);
}
public void setHolidays(HttpServletRequest request) {
int startMonth = getStartMonth();
int endMonth = getEndMonth();
Calendar startCal = Calendar.getInstance();
startCal.setTime(earliestSessionRelatedDate());
int startYear = getSessionStartYear();
StringBuffer sb = new StringBuffer();
for (int m = startMonth; m <= endMonth; m++) {
int year = DateUtils.calculateActualYear(m, startYear);
int daysOfMonth = DateUtils.getNrDaysOfMonth(m, startYear);
for (int d = 1; d <= daysOfMonth; d++) {
String holiday = request.getParameter("cal_val_" + year + "_"
+ ((12 + m) % 12) + "_" + d);
sb.append(holiday == null ? String.valueOf(sHolidayTypeNone)
: holiday);
}
}
setHolidays(sb.toString());
}
public int compareTo(Object o) {
if (o == null || !(o instanceof Session)) return -1;
Session s = (Session) o;
int cmp = getAcademicInitiative().compareTo(s.getAcademicInitiative());
if (cmp!=0) return cmp;
cmp = getSessionBeginDateTime().compareTo(s.getSessionBeginDateTime());
if (cmp!=0) return cmp;
return (getUniqueId() == null ? new Long(-1) : getUniqueId()).compareTo(s.getUniqueId() == null ? -1 : s.getUniqueId());
}
public DatePattern getDefaultDatePatternNotNull() {
DatePattern dp = super.getDefaultDatePattern();
if (dp == null) {
dp = DatePattern.findByName(this, "Full Term");
}
return dp;
}
public int getNrWeeks() {
Calendar sessionBeginDate = Calendar.getInstance(Locale.US);
sessionBeginDate.setTime(getSessionBeginDateTime());
Calendar sessionEndDate = Calendar.getInstance(Locale.US);
sessionEndDate.setTime(getSessionEndDateTime());
int beginDay = getDayOfYear(
sessionBeginDate.get(Calendar.DAY_OF_MONTH), sessionBeginDate
.get(Calendar.MONTH))
- getDayOfYear(1, getStartMonth());
int endDay = getDayOfYear(sessionEndDate.get(Calendar.DAY_OF_MONTH),
sessionEndDate.get(Calendar.MONTH))
- getDayOfYear(1, getStartMonth());
int nrDays = 0;
for (int i = beginDay; i <= endDay; i++) {
if (getHolidays() == null || i >= getHolidays().length()
|| (getHolidays().charAt(i) - '0') == sHolidayTypeNone)
nrDays++;
}
nrDays -= 7;
return (6 + nrDays) / 7;
}
public int getExamBeginOffset() {
return (int)Math.round((getSessionBeginDateTime().getTime() - getExamBeginDate().getTime()) / 86.4e6);
}
public String getBorder(int day, int month) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(getSessionBeginDateTime());
if (day==cal.get(Calendar.DAY_OF_MONTH) && ((12+month)%12)==cal.get(Calendar.MONTH))
return "'blue 2px solid'";
cal.setTime(getClassesEndDateTime());
if (day==cal.get(Calendar.DAY_OF_MONTH) && ((12+month)%12)==cal.get(Calendar.MONTH))
return "'blue 2px solid'";
if (getExamBeginDate()!=null) {
cal.setTime(getExamBeginDate());
if (day==cal.get(Calendar.DAY_OF_MONTH) && ((12+month)%12)==cal.get(Calendar.MONTH))
return "'green 2px solid'";
}
int holiday = getHoliday(day, month);
if (holiday!=Session.sHolidayTypeNone)
return "'"+Session.sHolidayTypeColors[holiday]+" 2px solid'";
return "null";
}
public String getColorArray() {
EventDateMapping.Class2EventDateMap class2EventDateMap = EventDateMapping.getMapping(getUniqueId());
int startMonth = getSession().getPatternStartMonth();
int endMonth = getSession().getPatternEndMonth();
int year = getSession().getSessionStartYear();
StringBuffer sb = new StringBuffer("[");
for (int m=startMonth;m<=endMonth;m++) {
if (m!=startMonth) sb.append(",");
sb.append("[");
int daysOfMonth = DateUtils.getNrDaysOfMonth(m, year);
for (int d=1;d<=daysOfMonth;d++) {
if (d>1) sb.append(",");
String color = "null";
if (class2EventDateMap != null) {
if (class2EventDateMap.hasClassDate(DateUtils.getDate(d, m, year))) {
color = "'#c0c'";
} else if (class2EventDateMap.hasEventDate(DateUtils.getDate(d, m, year))) {
color = "'#0cc'";
}
}
sb.append(color);
}
sb.append("]");
}
sb.append("]");
return sb.toString();
}
/** Return distance of the given date outside the session start/end date (in milliseconds) */
public long getDistance(Date date) {
if (date.compareTo(getEventBeginDate())<0) //before session
return getEventBeginDate().getTime() - date.getTime();
if (date.compareTo(getEventEndDate())>0) //after session
return date.getTime() - getEventEndDate().getTime();
return 0; //inside session
}
public boolean hasStudentSchedule() {
return hasStudentSchedule(getUniqueId());
}
public static boolean hasStudentSchedule(Long sessionId) {
return ((Number)new ExamDAO().getSession().
createQuery("select count(x) from StudentClassEnrollment x " +
"where x.student.session.uniqueId=:sessionId").
setLong("sessionId",sessionId).uniqueResult()).longValue()>0;
}
private OnlineSectioningServer getInstance() {
if (getUniqueId() == null) return null;
return ((SolverServerService)SpringApplicationContextHolder.getBean("solverServerService")).getOnlineStudentSchedulingContainer().getSolver(getUniqueId().toString());
}
public Collection<Long> getLockedOfferings() {
if (!getStatusType().canLockOfferings()) return null;
OnlineSectioningServer server = getInstance();
return (server == null || !server.isReady() ? null : server.getLockedOfferings());
}
public boolean isOfferingLocked(Long offeringId) {
if (!getStatusType().canLockOfferings()) return false;
OnlineSectioningServer server = getInstance();
return server != null && server.isOfferingLocked(offeringId);
}
public void lockOffering(Long offeringId) {
if (getStatusType().canLockOfferings()) {
OnlineSectioningServer server = getInstance();
if (server != null) server.lockOffering(offeringId);
}
}
public void unlockOffering(InstructionalOffering offering, UserContext user) {
OnlineSectioningServer server = getInstance();
if (server != null) {
server.execute(server.createAction(ReloadOfferingAction.class).forOfferings(offering.getUniqueId()),
(user == null ? null :
OnlineSectioningLog.Entity.newBuilder().setExternalId(user.getExternalUserId()).setName(user.getName()).setType(OnlineSectioningLog.Entity.EntityType.MANAGER).build()
));
server.unlockOffering(offering.getUniqueId());
}
try {
SessionFactory hibSessionFactory = SessionDAO.getInstance().getSession().getSessionFactory();
hibSessionFactory.getCache().evictEntity(InstructionalOffering.class, offering.getUniqueId());
for (CourseOffering course: offering.getCourseOfferings())
hibSessionFactory.getCache().evictEntity(CourseOffering.class, course.getUniqueId());
for (InstrOfferingConfig config: offering.getInstrOfferingConfigs())
for (SchedulingSubpart subpart: config.getSchedulingSubparts())
for (Class_ clazz: subpart.getClasses())
hibSessionFactory.getCache().evictEntity(Class_.class, clazz.getUniqueId());
} catch (Exception e) {
Debug.error("Failed to evict cache: " + e.getMessage());
}
}
@Override
public Session getSession() { return this; }
@Override
public Serializable getQualifierId() {
return getUniqueId();
}
@Override
public String getQualifierType() {
return getClass().getSimpleName();
}
@Override
public String getQualifierReference() {
return getReference();
}
@Override
public String getQualifierLabel() {
return getLabel();
}
@Override
public Department getDepartment() { return null; }
} |
public class Main {
public static void main(String[] args) {
//Graphe G = new Graphe("./src/petitGraphe.clq");
Graphe G = new Graphe("./src/C125.9.clq");
if(G.isClique())
System.out.println("G est une clique");
else System.out.println("G n'est pas une clique");
// System.out.println("La clique max de G est de taille : " + G.cliqueMax());
System.out.println("Sommet avec le moins d'arcs : " + (G.getWithLessArcs()+1));
Graphe aux = Graphe.getClique(G);
if(aux.isClique())
System.out.println("Aux est une clique (" + aux.getNbSommets() + ")");
else System.out.println("Aux n'est pas une clique");
/*
// System.out.println(G1);
System.out.println(G1);
if(G1.isClique())
System.out.println("G1 est une clique");
else System.out.println("G1 n'est pas une clique");
System.out.print("La clique max de G1 est de taille : " + G1.cliqueMax());
*/
}
} |
import puzzle.Board;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
public class Main{
public static void main(String args[]){
System.out.println("Matt Dumford - mdumfo2@uic.edu\n15-Puzzle Solver\n");
Board board = null;
// read from file version
// try{
// board = getPuzzleFromFile(args[0]);
// catch(ArrayIndexOutOfBoundsException e){
// System.err.println("Please specify a file with the puzzle.");
// System.exit(1);
// catch(IOException e){
// e.printStackTrace();
// args version
try{
board = getPuzzleFromArgs(args);
}
catch(ArrayIndexOutOfBoundsException e){
System.err.println("Not enough arguments");
System.exit(1);
}
try{
System.out.println("Breadth First Search:");
Board breadthSolution = breadthFirstSearch(board);
printSolutionUgly(board, breadthSolution);
}
catch(OutOfMemoryError e){
System.out.println("Out of Memory!");
}
try{
System.out.println("\n\nIterative Depth First Search:");
Board depthSolution = iterativeDepthFirstSearch(board);
printSolutionUgly(board, depthSolution);
}
catch(OutOfMemoryError e){
System.out.println("Out of Memory!");
}
}
public static Board getPuzzleFromArgs(String args[]){
int[][] matrix = new int[4][4];
int k = 0;
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
String s = args[k];
if(s.equals("_"))
matrix[i][j] = 0;
else
matrix[i][j] = Integer.parseInt(s);
k++;
}
}
return new Board(matrix);
}
public static Board getPuzzleFromFile(String filePath) throws IOException{
Scanner sc = new Scanner(new File(filePath));
sc.useDelimiter("[\n,]");
int[][] matrix = new int[4][4];
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
if(sc.hasNext()){
String s = sc.next();
if(s.equals("_"))
matrix[i][j] = 0;
else
matrix[i][j] = Integer.parseInt(s);
}
}
}
sc.close();
return new Board(matrix);
}
public static void printSolutionPretty(Board board, Board solution){
System.out.println(board);
for(Board.Direction d: solution.getSolutionPath()){
board = board.move(d);
System.out.println(d);
System.out.println(board);
}
}
public static void printSolutionUgly(Board board, Board solution){
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
System.out.print(board.getBoard()[i][j] + " ");
System.out.println();
for(Board.Direction d: solution.getSolutionPath()){
board = board.move(d);
for(int i=0; i<4; i++)
for(int j=0; j<4; j++)
System.out.print(board.getBoard()[i][j] + " ");
System.out.println();
}
}
public static Board breadthFirstSearch(Board board){
LinkedList<Board> queue = new LinkedList<Board>();
LinkedList<Board> checked = new LinkedList<Board>();
queue.add(board);
while(queue.size()>0){
Board currentBoard = queue.remove();
if(currentBoard.isSolved()){
return currentBoard;
}
checked.add(board);
Board.Direction[] moves = currentBoard.moveableDirections();
for(Board.Direction d: moves){
Board newBoard = currentBoard.move(d);
boolean found = false;
for(Board b: checked){
if(b.equals(newBoard)){
found = true;
break;
}
}
if(!found)
queue.add(newBoard);
}
}
return null; //should never get here
}
public static Board iterativeDepthFirstSearch(Board board){
int depth = 0;
while(true){
LinkedList<Board> stack = new LinkedList<Board>();
LinkedList<Board> checked = new LinkedList<Board>();
stack.push(board);
while(stack.size()>0){
Board currentBoard = stack.pop();
if(currentBoard.isSolved())
return currentBoard;
checked.push(currentBoard);
Board.Direction[] moves = currentBoard.moveableDirections();
for(Board.Direction d: moves){
Board newBoard = currentBoard.move(d);
boolean found = false;
for(Board b: checked){
if(b.equals(newBoard)){
found = true;
break;
}
}
if(!found && newBoard.getSolutionPath().size() < depth){
stack.push(newBoard);
}
}
}
depth++;
}
}
public Board aStar1(Board board){
ArrayList<Board> fringe = new ArrayList<Board>();
fringe.add(board);
while(fringe.size() > 0){
int min = fringe.get(0).getHueristic1();
int minPos = 0;
for(int i=0; i<fringe.size(); i++){
if(fringe.get(i).getHueristic1() < min){
min = fringe.get(i).getHueristic1();
minPos = i;
}
}
Board expand = fringe.remove(minPos);
if(expand.isSolved())
return expand;
for(Board.Direction d: expand.moveableDirections()){
fringe.add(expand.move(d));
}
}
return null; // should never get here
}
public Board aStar2(Board board){
ArrayList<Board> fringe = new ArrayList<Board>();
fringe.add(board);
while(fringe.size() > 0){
int min = fringe.get(0).getHueristic2();
int minPos = 0;
for(int i=0; i<fringe.size(); i++){
if(fringe.get(i).getHueristic2() < min){
min = fringe.get(i).getHueristic2();
minPos = i;
}
}
Board expand = fringe.remove(minPos);
if(expand.isSolved())
return expand;
for(Board.Direction d: expand.moveableDirections()){
fringe.add(expand.move(d));
}
}
return null; // should never get here
}
} |
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import com.itextpdf.text.DocumentException;
public class Main
{
public static String getResource(String res) {
URL url = Main.class.getResource(res);
return (null == url) ? res : url.toString();
}
public static Engine getEngine(String command) {
if( command.equals("add-verification-pages"))
return new AddVerificationPages();
else if( command.equals("find-texts"))
return new FindTexts();
else if( command.equals("extract-texts"))
return new ExtractTexts();
else if( command.equals("normalize"))
return new Normalize();
else if( command.equals("remove-javascript"))
return new RemoveJavaScript();
else if( command.equals("select-and-clip"))
return new SelectAndClip();
else if( command.equals("remove-scrive-elements"))
return new RemoveScriveElements();
System.err.println("Error: Uknown command: " + command);
return null;
}
public byte[] execute(String command, byte[] spec, byte[] pdf)
throws IOException, DocumentException
{
Engine engine = getEngine(command);
if (null == engine)
return null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
engine.Init(new ByteArrayInputStream(spec));
engine.execute(new ByteArrayInputStream(pdf), out);
return out.toByteArray();
}
public static void main(String[] args)
{
//do not show tray icon nor windows, popups, anything
System.setProperty("java.awt.headless", "true");
com.itextpdf.text.pdf.PdfReader.unethicalreading = true;
if( args.length < 2) {
System.err.println("Usage:");
System.err.println(" java -jar scrivepdftools.jar httpserver -p [IP:]port");
System.err.println("");
System.err.println(" java -jar scrivepdftools.jar add-verification-pages config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar find-texts config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar extract-texts config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar normalize config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar select-and-clip config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar remove-scrive-elements config.json [config2.json] [config3.json] ...");
System.err.println(" java -jar scrivepdftools.jar remove-javascript config.json [config2.json] [config3.json] ...");
System.err.println("");
System.err.println("scrivepdftools uses the following products:");
System.err.println(" iText by Bruno Lowagie, iText Group NV ");
System.err.println(" snakeyaml");
}
else if (args[0].equals("httpserver")) {
if (!args[1].equals("-p")) {
System.err.println("Usage:");
System.err.println(" java -jar scrivepdftools.jar httpserver -p [IP:]port");
} else {
final int i = args[2].lastIndexOf(":", args[2].length());
final String ip = ( i < 0 ) ? null : args[2].substring(0, i);
final String port = args[2].substring(i + 1);
try {
WebServer.start(args[0], ip, Integer.valueOf(port));
} catch (NumberFormatException e) {
System.err.println("Error: Invalid port number: " + port);
System.err.println("Usage:");
System.err.println(" java -jar scrivepdftools.jar httpserver -p [IP:]port");
} catch (SocketException e) {
System.err.println("Error: Invalid IP address: " + ip);
e.printStackTrace(System.err);
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
} else {
try {
Engine engine = getEngine(args[0]);
if (null != engine) {
for (int i = 1; i < args.length; i++) {
engine.execute(args[i]);
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
} |
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
// this is where it all begins
// hello everybody
System.out.println("hello");
}
} |
package ameba.http.session;
import ameba.core.Requests;
import ameba.util.Times;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import javax.annotation.Priority;
import javax.inject.Singleton;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.*;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.NewCookie;
import java.lang.invoke.MethodHandle;
import java.net.URI;
import java.util.UUID;
/**
* @author icode
*/
@PreMatching
@Priority(Priorities.AUTHENTICATION - 500)
@Singleton
public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__";
static String DEFAULT_SESSION_ID_COOKIE_KEY = "s";
static long SESSION_TIMEOUT = Times.parseDuration("2h") * 1000;
static int COOKIE_MAX_AGE = NewCookie.DEFAULT_MAX_AGE;
static MethodHandle METHOD_HANDLE;
@Override
@SuppressWarnings("unchecked")
public void filter(ContainerRequestContext requestContext) {
Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY);
boolean isNew = false;
if (cookie == null) {
isNew = true;
cookie = newCookie(requestContext);
}
AbstractSession session;
String host = Requests.getRemoteRealAddr();
if (host == null || host.equals("unknown")) {
host = Requests.getRemoteAddr();
}
String sessionId = cookie.getValue();
if (METHOD_HANDLE != null) {
try {
session = (AbstractSession) METHOD_HANDLE.invoke(sessionId, host, SESSION_TIMEOUT, isNew);
} catch (Throwable throwable) {
throw new SessionExcption("new session instance error");
}
} else {
session = new CacheSession(sessionId, host, SESSION_TIMEOUT, isNew);
}
if (!session.isNew() && session.isInvalid()) {
cookie = newCookie(requestContext);
session.setId(cookie.getValue());
}
Session.sessionThreadLocal.set(session);
}
protected String newSessionId() {
return Hashing.sha1()
.hashString(
UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime(),
Charsets.UTF_8
)
.toString();
}
private NewCookie newCookie(ContainerRequestContext requestContext) {
// URI uri = requestContext.getUriInfo().getBaseUri();
// String domain = uri.getHost();
// // localhost domain must be null
// if (domain.equalsIgnoreCase("localhost")) {
// domain = null;
NewCookie cookie = new NewCookie(
DEFAULT_SESSION_ID_COOKIE_KEY,
newSessionId(),
"/",
null,
Cookie.DEFAULT_VERSION,
null,
COOKIE_MAX_AGE,
null,
requestContext.getSecurityContext().isSecure(),
true);
requestContext.setProperty(SET_COOKIE_KEY, cookie);
return cookie;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
Session.flush();
NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY);
if (cookie != null)
responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString());
Session.sessionThreadLocal.remove();
}
} |
package black.door.intertalk;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.apache.commons.validator.routines.EmailValidator;
import javaslang.control.Try;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.IOException;
import static java.util.Objects.requireNonNull;
@JsonSerialize(using = ToStringSerializer.class)
@JsonDeserialize(using = MailAddress.MailAddressDeserializer.class)
public class MailAddress implements Comparable{
final String local;
final String domain;
public MailAddress(String local, String domain) throws AddressException {
this.local = requireNonNull(local).toLowerCase();
this.domain = requireNonNull(domain).toLowerCase();
String addr = local + '@' + domain;
if(Validate(addr)) {
new InternetAddress(local + '@' + domain, true);
}
}
public static Try<MailAddress> parse(String addr){
requireNonNull(addr);
int index = addr.lastIndexOf('@');
return Try.of(() -> new MailAddress(addr.substring(0, index), addr.substring(index+1, addr.length())));
}
public static boolean Validate(String addr) {
boolean result = true;
boolean local = true;
try {
InternetAddress email = new InternetAddress(addr);
email.validate();
EmailValidator.getInstance(local).isValid(addr);
// if (email.toString().contains("localhost")) result = false;
// if (email.toString().contains("127.0.0.1")) result = false;
} catch (AddressException ex) {
result = false;
}
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MailAddress)) return false;
MailAddress that = (MailAddress) o;
if (!local.equalsIgnoreCase(that.local)) return false;
return domain.equalsIgnoreCase(that.domain);
}
@Override
public int hashCode() {
int result = local.hashCode();
result = 31 * result + domain.hashCode();
return result;
}
@Override
public String toString() {
return local + '@' + domain;
}
@Override
public int compareTo(Object o) {
return this.toString().compareTo(String.valueOf(o));
}
public static class MailAddressDeserializer extends StdDeserializer<MailAddress>{
protected MailAddressDeserializer() {
super(MailAddress.class);
}
@Override
public MailAddress deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return parse(p.getText()).get();
}
}
} |
package br.com.caelum.brutal.auth;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.caelum.brutal.dao.UserDAO;
import br.com.caelum.brutal.model.User;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.ComponentFactory;
@Component
public class Access implements ComponentFactory<User> {
public static final String BRUTAL_SESSION = "brutal_session";
private User user;
private final HttpServletResponse response;
private final HttpServletRequest request;
private final UserDAO users;
public Access(HttpServletResponse response, HttpServletRequest request, UserDAO users) {
this.response = response;
this.request = request;
this.users = users;
}
public User login(User user) {
user.setSessionKey();
Cookie cookie = new Cookie(BRUTAL_SESSION, user.getSessionKey());
cookie.setPath("/");
response.addCookie(cookie);
this.user = user;
return user;
}
@Override
public User getInstance() {
return user;
}
@PostConstruct
public void tryToAutoLogin() {
String key = extractKeyFromCookies();
this.user = users.findBySessionKey(key);
}
private String extractKeyFromCookies() {
Cookie[] cookiesArray = request.getCookies();
if (cookiesArray != null) {
List<Cookie> cookies = Arrays.asList(cookiesArray);
for (Cookie cookie : cookies) {
if (cookie.getName().equals(BRUTAL_SESSION)) {
return cookie.getValue();
}
}
}
return null;
}
public void logout() {
Cookie cookie = new Cookie(BRUTAL_SESSION, "");
cookie.setMaxAge(-1);
response.addCookie(cookie);
user.resetSession();
this.user = null;
}
} |
package ch.poole.openinghoursparser;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Translation support for {@link OpeningHoursParser}
* @author JOSM team, Simon Legner
*/
public class I18n {
private static ResourceBundle messages;
static {
setLocale(Locale.ROOT);
}
/**
* Private constructor to stop instantiation
*/
private I18n() {
// private
}
/**
* Sets the locale used for translations.
* @param locale the locale
* @see ResourceBundle#getBundle(java.lang.String, java.util.Locale)
*/
public static synchronized void setLocale(Locale locale) {
messages = ResourceBundle.getBundle("ch.poole.openinghoursparser.Messages", locale);
}
/**
* Returns the translation for the given translation {@code key} and the supplied {@code arguments}.
* @param key the translation key to {@linkplain ResourceBundle#getString fetch} the translation
* @param arguments the translation arguments which are used {@linkplain MessageFormat#format for formatting}
* @return the translated string
*/
public static String tr(String key, Object... arguments) {
return MessageFormat.format(messages.getString(key), arguments);
}
} |
package com.alexrnl.commons.time;
import java.sql.Date;
import java.util.Calendar;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.alexrnl.commons.CommonsConstants;
import com.alexrnl.commons.utils.object.AutoCompare;
import com.alexrnl.commons.utils.object.AutoHashCode;
import com.alexrnl.commons.utils.object.Field;
/**
* Extension of {@link Time} which handles seconds.<br />
*
* @author Alex
*/
public class TimeSec extends Time implements Cloneable {
/** Logger */
private static Logger lg = Logger.getLogger(TimeSec.class.getName());
/** Serial version UID */
private static final long serialVersionUID = -5220683648807102121L;
/** The number of seconds */
private final int seconds;
/**
* Constructor #1.<br />
* Default constructor, set time to midnight.
*/
public TimeSec () {
this(0);
}
/**
* Constructor #2.<br />
* The number of minutes and seconds will be set to 0.
* @param hours
* the number of hours.
*/
public TimeSec (final int hours) {
this(hours, 0);
}
/**
* Constructor #3.<br />
* The number of seconds will be set to 0.
* @param hours
* the number of hours.
* @param minutes
* the number of minutes.
*/
public TimeSec (final int hours, final int minutes) {
this(hours, minutes, 0);
}
/**
* Constructor #4.<br />
* @param hours
* the number of hours.
* @param minutes
* the number of minutes.
* @param seconds
* the number of seconds.
*/
public TimeSec (final int hours, final int minutes, final int seconds) {
super(hours, minutes + seconds / CommonsConstants.SECONDS_PER_MINUTES);
this.seconds = seconds % CommonsConstants.SECONDS_PER_MINUTES;
}
/**
* Constructor #5.<br />
* @param timeStamp
* the number of seconds since January 1st, 1970.
*/
public TimeSec (final long timeStamp) {
this(new Date(timeStamp));
}
/**
* Constructor #6.<br />
* Build the time from the date.
* @param date
* the date to use.
*/
public TimeSec (final Date date) {
super(date);
final Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTime(date);
seconds = cal.get(Calendar.SECOND);
}
/**
* Constructor #7.<br />
* Build the object from the {@link Time} given.
* @param time
* the time.
*/
public TimeSec (final Time time) {
this(time, 0);
}
/**
* Constructor #8.<br />
* Build the object from the {@link Time} and seconds given.
* @param time
* the time.
* @param seconds
* the number of seconds.
*/
public TimeSec (final Time time, final int seconds) {
this(time.getHours(), time.getMinutes(), seconds);
}
/**
* Constructor #9.<br />
* Build the object from the {@link Time} and seconds given.
* @param time
* the time.
*/
public TimeSec (final TimeSec time) {
this(time.getHours(), time.getMinutes(), time.getSeconds());
}
/**
* Build a time based on a string.<br />
* The time format must be hours minutes (in that order) separated using any
* non-numerical character.<br />
* @param time
* the time set.
* @return the time matching the string.
*/
public static TimeSec get (final String time) {
if (lg.isLoggable(Level.FINE)) {
lg.fine("Parsing time " + time);
}
final String[] hm = time.split(CommonsConstants.NON_DECIMAL_CHARACTER);
Integer hours = null;
Integer minutes = null;
Integer seconds = null;
for (final String s : hm) {
if (s.isEmpty()) {
continue;
}
if (hours == null) {
hours = Integer.parseInt(s);
continue;
}
if (minutes == null) {
minutes = Integer.parseInt(s);
continue;
}
seconds = Integer.parseInt(s);
break;
}
return new TimeSec(hours == null ? 0 : hours, minutes == null ? 0 : minutes,
seconds == null ? 0 : seconds);
}
/**
* Return the current time.
* @return a {@link Time} object matching the current time.
*/
public static TimeSec getCurrent () {
return new TimeSec(System.currentTimeMillis());
}
/**
* Return the attribute seconds.
* @return the attribute seconds.
*/
@Field
public int getSeconds () {
return seconds;
}
/**
* Return a Time object build from this TimeSec properties.
* @return the new Time object.
*/
public Time getTime () {
return new Time(getHours(), getMinutes());
}
/**
* Add the amount of time specified to the current time.<br />
* There is no maximum, so you may reach 25:48:02.
* @param time
* the time to add.
* @return the new time.
*/
public TimeSec add (final TimeSec time) {
return new TimeSec(getHours() + time.getHours(), getMinutes() + time.getMinutes(),
getSeconds() + time.getSeconds());
}
/**
* Subtract the amount of time specified to the current time.<br />
* There is no minimum, so you may reach -2:48:28.
* @param time
* the time to subtract.
* @return the new time.
*/
public TimeSec sub (final TimeSec time) {
return new TimeSec(getHours() - time.getHours(), getMinutes() - time.getMinutes(),
getSeconds() - time.getSeconds());
}
/*
* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo (final Time o) {
if (o == null) {
return 1;
}
final int parentComparison = super.compareTo(o);
if (parentComparison != 0 || !(o instanceof TimeSec)) {
return parentComparison;
}
final TimeSec timeSec = (TimeSec) o;
if (seconds > timeSec.seconds) {
return 1;
} else if (seconds < timeSec.seconds) {
return -1;
}
assert equals(timeSec);
return 0;
}
/**
* Check if the current time is after the specified time.<br />
* @param time
* the time used for reference.
* @return <code>true</code> if this time is after the reference time provided.
* @see #compareTo(Time)
*/
@Override
public boolean after (final Time time) {
return compareTo(time) > 0;
}
/**
* Check if the current time is before the specified time.<br />
* @param time
* the time used for reference.
* @return <code>true</code> if this time is before the reference time provided.
* @see #compareTo(Time)
*/
@Override
public boolean before (final Time time) {
return compareTo(time) < 0;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString () {
String s = Integer.toString(seconds);
if (s.length() < 2) {
s = Integer.valueOf(0) + s;
}
return super.toString() + CommonsConstants.TIME_SEPARATOR + s;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode () {
return AutoHashCode.getInstance().hashCode(this);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals (final Object obj) {
if (!(obj instanceof Time)) {
return false;
}
return AutoCompare.getInstance().compare(this, (Time) obj);
}
/*
* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public TimeSec clone () throws CloneNotSupportedException {
return new TimeSec(this);
}
} |
/**
* Created Dec 20, 2007
*/
package com.crawljax.util;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;
import com.crawljax.core.TagAttribute;
import com.crawljax.core.TagElement;
import com.crawljax.core.configuration.CrawljaxConfiguration;
import com.crawljax.core.configuration.CrawljaxConfigurationReader;
/**
* @author mesbah
* @version $Id$
*/
public final class PropertyHelper {
private static final Logger LOGGER = Logger.getLogger(PropertyHelper.class.getName());
private static CrawljaxConfigurationReader crawljaxConfiguration;
private static String projectRelativePath = "project.path.relative";
private static String projectRelativePathValue = "";
private static String outputFolderName = "output.path";
private static String outputFolder = "";
private static String siteUrl = "site.url";
private static String baseUrl = "site.base.url";
private static String crawlDepth = "crawl.depth";
private static String crawlMaxStates = "crawl.max.states";
private static String crawlMaxTime = "crawl.max.runtime";
private static String crawlThrehold = "crawl.threshold";
private static String robotEvents = "robot.events";
private static String crawlTags = "crawl.tags";
private static String crawlExludeTags = "crawl.tags.exclude";
private static String crawlFilterAttributes = "crawl.filter.attributes";
private static String crawlNumberOfThreads = "crawl.numberOfThreads";
private static String hibernateProperties = "hibernate.properties";
private static String hibernatePropertiesValue = "hibernate.properties";
private static String crawlFormRandomInput = "crawl.forms.randominput";
private static int crawlFormRandomInputValue = 1;
private static String formProperties = "forms.properties";
private static int crawlManualEnterFormValue = 1;
private static String formPropertiesValue = "forms.properties";
private static String browser = "browser";
private static String crawlWaitReload = "crawl.wait.reload";
private static String crawlWaitEvent = "crawl.wait.event";
private static Configuration config;
private static String hibernateSchema = "hibernate.hbm2ddl.auto";
private static String hibernateSchemaValue;
private static String useDatabase = "database.use";
private static int useDatabaseValue = 0;
// if each candidate clickable should be clicked only once
private static String clickOnce = "click.once";
private static int clickOnceValue = 1;
private static int testInvariantsWhileCrawlingValue = 1;
/* event handlers */
private static String detectEventHandlers = "eventHandlers.detect";
private static int detectEventHandlersValue = 1;
private static String siteUrlValue;
private static String baseUrlValue;
private static int crawlDepthValue;
private static List<String> robotEventsValues;
private static List<String> crawlTagsValues;
private static List<String> crawlFilterAttributesValues;
private static List<TagElement> crawlTagElements = new ArrayList<TagElement>();
private static List<TagElement> crawlExcludeTagElements = new ArrayList<TagElement>();
private static List<String> atusaPluginsValues;
private static int crawlMaxStatesValue = 0;
private static int crawlMaxTimeValue = 0;
private static String proxyEnabled = "proxy.enabled";
private static int proxyEnabledValue = 0;
private static int domTidyValue = 0;
private static int crawNumberOfThreadsValue = 1;
private static String maxHistorySizeText = "history.maxsize";
private static int maxHistorySize;
private static String propertiesFileName;
/**
* default is IE.
*/
private static String browserValue = "ie";
private static int crawlWaitReloadValue;
private static int crawlWaitEventValue;
private PropertyHelper() {
}
/**
* @param propertiesFile
* thie properties file.
* @throws ConfigurationException
* if configuration fails.
*/
public static void init(String propertiesFile) throws ConfigurationException {
PropertyHelper.propertiesFileName = propertiesFile;
crawljaxConfiguration = null;
init(new PropertiesConfiguration(propertiesFile));
}
/**
* Initialize property helper with a CrawljaxConfiguration instance.
*
* @param crawljaxConfiguration
* The CrawljaxConfiguration instance.
* @throws ConfigurationException
* On error.
*/
public static void init(CrawljaxConfiguration crawljaxConfiguration)
throws ConfigurationException {
PropertyHelper.crawljaxConfiguration =
new CrawljaxConfigurationReader(crawljaxConfiguration);
if (PropertyHelper.crawljaxConfiguration.getConfiguration() == null) {
throw new ConfigurationException("Configuration cannot be null!");
}
init(PropertyHelper.crawljaxConfiguration.getConfiguration());
}
private static void init(Configuration configuration) throws ConfigurationException {
config = configuration;
/* reset crawltagelements */
crawlTagElements = new ArrayList<TagElement>();
if (config.containsKey(outputFolderName)) {
outputFolder = getProperty(outputFolderName);
}
projectRelativePathValue = getProperty(projectRelativePath);
siteUrlValue = getProperty(siteUrl);
baseUrlValue = getProperty(baseUrl);
crawlDepthValue = getPropertyAsInt(crawlDepth);
crawNumberOfThreadsValue = getPropertyAsInt(crawlNumberOfThreads);
// crawlThreholdValue = getPropertyAsDouble(crawlThrehold);
robotEventsValues = getPropertyAsList(robotEvents);
crawlTagsValues = getPropertyAsList(crawlTags);
crawlFilterAttributesValues = getPropertyAsList(crawlFilterAttributes);
browserValue = getProperty(browser);
crawlWaitReloadValue = getPropertyAsInt(crawlWaitReload);
crawlWaitEventValue = getPropertyAsInt(crawlWaitEvent);
crawlMaxStatesValue = getPropertyAsInt(crawlMaxStates);
crawlMaxTimeValue = getPropertyAsInt(crawlMaxTime);
// crawlManualEnterFormValue =
// getPropertyAsInt(crawlManualEnterForm);
formPropertiesValue = getProperty(formProperties);
if (config.containsKey(crawlFormRandomInput)) {
crawlFormRandomInputValue = getPropertyAsInt(crawlFormRandomInput);
}
hibernatePropertiesValue = getProperty(hibernateProperties);
useDatabaseValue = getPropertyAsInt(useDatabase);
if (config.containsKey(clickOnce)) {
clickOnceValue = getPropertyAsInt(clickOnce);
}
setTagElements();
setTagExcludeElements();
if (config.containsKey(proxyEnabled)) {
proxyEnabledValue = getPropertyAsInt(proxyEnabled);
}
if (config.containsKey(maxHistorySizeText)) {
maxHistorySize = getPropertyAsInt(maxHistorySizeText);
}
hibernateSchemaValue = getProperty(hibernateSchema);
if (!checkProperties()) {
LOGGER.error("Check the properties!");
throw new ConfigurationException("Check the properties!");
}
}
private static void setTagElements() {
for (String text : getPropertyAsList(crawlTags)) {
TagElement tagElement = parseTagElements(text);
if (tagElement != null) {
crawlTagElements.add(tagElement);
}
}
}
private static void setTagExcludeElements() {
for (String text : getPropertyAsList(crawlExludeTags)) {
TagElement tagElement = parseTagElements(text);
if (tagElement != null) {
crawlExcludeTagElements.add(tagElement);
}
}
}
/**
* @param property
* the property.
* @return the value as string.
*/
public static String getProperty(String property) {
return config.getString(property);
}
/**
* Check all the properties.
*
* @return true if all properties are set.
*/
private static boolean checkProperties() {
if (isEmpty(siteUrlValue)) {
LOGGER.error("Property " + siteUrl + " is not set.");
return false;
}
/*
* if (isEmpty(genFilepathValue)) { LOGGER.error("Property " + genFilepath +
* " is not set."); return false; }
*/
if (isEmpty("" + crawlDepthValue)) {
LOGGER.error("Property " + crawlDepth + " is not set.");
return false;
}
/*
* if (isEmpty("" + crawlThreholdValue)) { LOGGER.error("Property " + crawlThrehold +
* " is not set."); return false; }
*/
if (isEmpty(browserValue) && getCrawljaxConfiguration() == null) {
LOGGER.error("Property " + browser + " is not set.");
return false;
}
if (isEmpty("" + crawlWaitReloadValue)) {
LOGGER.error("Property " + crawlWaitReload + " is not set.");
return false;
}
if (isEmpty("" + crawlWaitEventValue)) {
LOGGER.error("Property " + crawlWaitEvent + " is not set.");
return false;
}
if (isEmpty(hibernateSchemaValue)) {
LOGGER.error("Property " + hibernateSchema + " is not set.");
return false;
}
return true;
}
private static boolean isEmpty(String property) {
if ((property == null) || "".equals(property)) {
return true;
}
return false;
}
/**
* @param property
* name of the property.
* @return the value as an int.
*/
public static int getPropertyAsInt(String property) {
return config.getInt(property);
}
/**
* @param property
* the property.
* @return the value as a double.
*/
public static double getPropertyAsDouble(String property) {
return config.getDouble(property);
}
/**
* @param property
* the property.
* @return the values as a List.
*/
public static List<String> getPropertyAsList(String property) {
List<String> result = new ArrayList<String>();
String[] array = config.getStringArray(property);
for (int i = 0; i < array.length; i++) {
result.add(array[i]);
}
return result;
}
/**
* @return A reader for the CrawljaxConfiguration instance.
*/
public static CrawljaxConfigurationReader getCrawljaxConfiguration() {
return crawljaxConfiguration;
}
/**
* @return The project relative path.
*/
public static String getProjectRelativePathValue() {
return projectRelativePathValue;
}
/**
* @return The output folder with a trailing slash.
*/
public static String getOutputFolder() {
return Helper.addFolderSlashIfNeeded(outputFolder);
}
/**
* @return the siteUrl
*/
public static String getSiteUrl() {
return siteUrl;
}
/**
* @return the baseUrl
*/
public static String getBaseUrl() {
return baseUrl;
}
/**
* @return the crawlDepth
*/
public static String getCrawlDepth() {
return crawlDepth;
}
/**
* @return the crawlThrehold
*/
public static String getCrawlThrehold() {
return crawlThrehold;
}
/**
* @return the crawlTags
*/
public static String getCrawlTags() {
return crawlTags;
}
/**
* @return the browser
*/
public static String getBrowser() {
return browser;
}
/**
* @return the config
*/
public static Configuration getConfig() {
return config;
}
/**
* @return the siteUrlValue
*/
public static String getSiteUrlValue() {
return siteUrlValue;
}
/**
* @return the baseUrlValue
*/
public static String getBaseUrlValue() {
return baseUrlValue;
}
/**
* @return the crawlDepthValue
*/
public static int getCrawlDepthValue() {
return crawlDepthValue;
}
/**
* @return the robotEventsValues
*/
public static List<String> getRobotEventsValues() {
return robotEventsValues;
}
/**
* @return the crawlTagsValues
*/
public static List<String> getCrawlTagsValues() {
return crawlTagsValues;
}
/**
* @return the crawlFilterAttributesValues
*/
public static List<String> getCrawlFilterAttributesValues() {
return crawlFilterAttributesValues;
}
/**
* @return the browserValue
*/
public static String getBrowserValue() {
return browserValue;
}
/**
* @return the crawlWaitReloadValue
*/
public static int getCrawlWaitReloadValue() {
return crawlWaitReloadValue;
}
/**
* @return the crawlWaitEventValue
*/
public static int getCrawlWaitEventValue() {
return crawlWaitEventValue;
}
/**
* @return TODO: DOCUMENT ME!
*/
public static String getCrawlMaxStates() {
return crawlMaxStates;
}
/**
* @return TODO: DOCUMENT ME!
*/
public static String getCrawlMaxTime() {
return crawlMaxTime;
}
/**
* @return TODO: DOCUMENT ME!
*/
public static int getCrawlMaxStatesValue() {
return crawlMaxStatesValue;
}
/**
* @return the max value for crawling time.
*/
public static int getCrawlMaxTimeValue() {
return crawlMaxTimeValue;
}
/**
* Parses the tag elements.
*
* @param text
* The string containing the tag elements.
* @return The tag element.
*/
public static TagElement parseTagElements(String text) {
if (text.equals("")) {
return null;
}
TagElement tagElement = new TagElement();
Pattern pattern =
Pattern.compile("\\w+:\\{(\\w+=?(\\-*\\s*[\\w%]\\s*)+\\;?\\s?)*}"
+ "(\\[\\w+\\])?");
Pattern patternTagName = Pattern.compile("\\w+");
Pattern patternAttributes = Pattern.compile("\\{(\\w+=(\\-*\\s*[\\w%]\\s*)+\\;?\\s?)*}");
Pattern patternAttribute = Pattern.compile("(\\w+)=((\\-*\\s*[\\w%]\\s*)+)");
Pattern patternId = Pattern.compile("(\\[)(\\w+)(\\])");
Matcher matcher = pattern.matcher(text);
if (matcher.matches()) {
String substring = matcher.group();
matcher = patternTagName.matcher(substring);
if (matcher.find()) {
tagElement.setName(matcher.group().trim());
}
matcher = patternAttributes.matcher(substring);
// attributes
if (matcher.find()) {
String attributes = (matcher.group());
// parse attributes
matcher = patternAttribute.matcher(attributes);
while (matcher.find()) {
String name = matcher.group(1).trim();
String value = matcher.group(2).trim();
tagElement.getAttributes().add(new TagAttribute(name, value));
}
}
matcher = patternId.matcher(substring);
if (matcher.find()) {
String id = matcher.group(2);
tagElement.setId(id);
}
}
return tagElement;
}
/**
* @param args
* TODO: DOCUMENT ME!
*/
public static void main(String[] args) {
String text = "div:{class=expandable-hitarea}";
TagElement tagElement = parseTagElements(text);
System.out.println("tagname: " + tagElement.getName());
for (TagAttribute attr : tagElement.getAttributes()) {
System.out.println("attrName: " + attr.getName() + " value: " + attr.getValue());
}
/*
* String text =
* "a:{attr=value}, div:{class=aha; id=room}, span:{}, div:{class=expandable-hitarea}" ; try
* { PropertyHelper.init("src/test/resources/testcrawljax.properties"); } catch
* (ConfigurationException e) { System.out.println(e.getMessage()); } List<String> tList =
* getPropertyAsList(crawlTags); for (String e : tList) { System.out.println(e); TagElement
* tagElement = parseTagElements(e); System.out.println("tagname: " + tagElement.getName());
* for (TagAttribute attr : tagElement.getAttributes()) { System.out.println("attrName: " +
* attr.getName() + " value: " + attr.getValue()); } }
*/
/*
* for (String t : getPropertyAsList(crawlTags)) { TagElement tagElement =
* parseTagElements(t); if (tagElement != null) { crawlTagElements.add(tagElement); } }
*/
/*
* TagElement tagElement = parseTagElements(text); System.out.println("tagname: " +
* tagElement.getName()); for (TagAttribute attr : tagElement.getAttributes()) {
* System.out.println( "attrName: " + attr.getName() + " value: " + attr.getValue()); }
*/
}
/**
* @return TODO: DOCUMENT ME!
*/
public static List<TagElement> getCrawlTagElements() {
return crawlTagElements;
}
/**
* @return TODO: DOCUMENT ME!
*/
public static List<TagElement> getCrawlExcludeTagElements() {
return crawlExcludeTagElements;
}
/**
* @return The hibernate properties filename.
*/
public static String getHibernatePropertiesValue() {
return hibernatePropertiesValue;
}
/**
* @return the crawlManualEnterFormValue
*/
public static boolean getCrawlManualEnterFormValue() {
return crawlManualEnterFormValue == 1;
}
/**
* @return The form properties.
*/
public static String getFormPropertiesValue() {
return formPropertiesValue;
}
/**
* @return the crawlFormRandomInputValue
*/
public static boolean getCrawlFormWithRandomValues() {
return crawlFormRandomInputValue == 1;
}
/**
* @return TODO: DOCUMENT ME!
*/
public static List<String> getAtusaPluginsValues() {
return atusaPluginsValues;
}
/**
* @return Whether to use the proxy.
*/
public static boolean getProxyEnabledValue() {
return proxyEnabledValue == 1;
}
/**
* @return the useDatabaseValue
*/
public static boolean useDatabase() {
return useDatabaseValue == 1;
}
/**
* @return Whether to tidy up the dom.
*/
public static boolean getDomTidyValue() {
return domTidyValue == 1;
}
/**
* Return the max history size.
*
* @return Maximum history size.
*/
public static int getMaxHistorySize() {
return maxHistorySize;
}
/**
* Returns the hibernate schema name.
*
* @return The name.
*/
public static String getHibernateSchemaValue() {
return hibernateSchemaValue;
}
/**
* @return the testInvariantsWhileCrawlingValue
*/
public static boolean getTestInvariantsWhileCrawlingValue() {
return testInvariantsWhileCrawlingValue == 1;
}
/**
* @return the detectEventHandlers
*/
public static String getDetectEventHandlers() {
return detectEventHandlers;
}
/**
* @return the detectEventHandlersValue
*/
public static boolean getDetectEventHandlersValue() {
return detectEventHandlersValue == 1;
}
/**
* Get filename of the properties file in use.
*
* @return Filename.
*/
public static String getPropertiesFileName() {
return propertiesFileName;
}
/**
* @return the crawNumberOfThreadsValue
*/
public static int getCrawNumberOfThreadsValue() {
return crawNumberOfThreadsValue;
}
/**
* @return if each candidate clickable should be clicked only once.
*/
public static boolean getClickOnceValue() {
return clickOnceValue == 1;
}
} |
package com.grayfox.server.util;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Messages {
private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
private static final Collection<Locale> SUPPORTED_LOCALES = Collections.unmodifiableCollection(Arrays.asList(DEFAULT_LOCALE, new Locale("es")));
private static final String RESOURCE_BUNDLE_BASE_NAME = "com.grayfox.server.messages";
private static final String MISSING_RESOURCE_KEY_FORMAT = "???%s???";
private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);
private Messages() {
throw new IllegalAccessError("This class cannot be instantiated nor extended");
}
public static String get(String key, Locale locale) {
try {
ResourceBundle bundle = SUPPORTED_LOCALES.contains(locale) ? ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, locale) : ResourceBundle.getBundle(RESOURCE_BUNDLE_BASE_NAME, DEFAULT_LOCALE);
return bundle.getString(key);
} catch (MissingResourceException ex) {
LOGGER.warn("Can't find message for key: [{}]", key, ex);
return String.format(MISSING_RESOURCE_KEY_FORMAT, key);
}
}
public static String get(String key, Locale locale, Object[] formatArgs) {
String unformattedMessage = get(key, locale);
if (formatArgs != null && formatArgs.length > 0) {
try {
return MessageFormat.format(unformattedMessage, formatArgs);
} catch (IllegalArgumentException ex) {
LOGGER.warn("Can't format message: [{}] with args: {}", unformattedMessage, Arrays.deepToString(formatArgs), ex);
}
}
return unformattedMessage;
}
} |
package com.hadisatrio.optional;
import com.hadisatrio.optional.function.Consumer;
import com.hadisatrio.optional.function.Function;
import com.hadisatrio.optional.function.Supplier;
import java.io.Serializable;
/**
* A container object which may or may not contain a non-null value.
* If a value is present, {@code isPresent()} will return {@code true} and
* {@code get()} will return the value.
* <p>
* <p>Additional methods that depend on the presence or absence of a contained
* value are provided, such as {@link #or(java.lang.Object) orElse()}
* (return a default value if value not present),
* {@link #ifPresent(Consumer) ifPresent()} (execute a block of code
* if the value is present), and
* {@link #ifPresentOrElse(Consumer, Function) ifPresentOrElse()} (execute
* a block of code if the value is present, another block otherwise).
*
* @author Hadi Satrio
*/
public final class Optional<T> implements Serializable {
/**
* Common instance for {@code Optional}s with no value present / {@link #absent()}.
*/
private static final Optional<?> ABSENT = new Optional<>();
/**
* If non-null, the value; if null, indicates no value is present.
*/
private final T value;
/**
* Constructs an absent instance.
*/
private Optional() {
this.value = null;
}
private Optional(T value) {
if (value == null) {
throw new IllegalArgumentException();
} else {
this.value = value;
}
}
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an absent {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an absent {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? (Optional<T>) absent() : of(value);
}
/**
* Returns an absent {@code Optional} instance. No value is present for this
* Optional.
*
* @param <T> Type of the non-existent value
* @return an absent {@code Optional}
*/
public static <T> Optional<T> absent() {
return (Optional<T>) ABSENT;
}
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
public T get() {
if (isPresent()) {
return value;
}
throw new IllegalStateException("Value is absent.");
}
public T or(T other) {
if (other == null) {
throw new IllegalArgumentException("null may not be passed as an argument; use orNull() instead.");
}
return isPresent() ? value : other;
}
public T or(Supplier<T> otherSupplier) {
if (otherSupplier == null) {
throw new IllegalArgumentException("null may not be passed as an argument; use orNull() instead.");
}
return isPresent() ? value : otherSupplier.get();
}
public <X extends Throwable> T orThrow(X throwable) throws X {
if (throwable == null) {
throw new IllegalArgumentException("null may not be passed as an argument; use orNull() instead.");
}
if (isPresent()) {
return value;
}
throw throwable;
}
public <X extends Throwable> T orThrow(Supplier<? extends X> throwableSupplier) throws X {
if (throwableSupplier == null) {
throw new IllegalArgumentException("null may not be passed as an argument; use orNull() instead.");
}
if (isPresent()) {
return value;
}
throw throwableSupplier.get();
}
/**
* Return the contained value, if present, otherwise null.
*
* @return the present value, if present, otherwise null
*/
public T orNull() {
return isPresent() ? value : null;
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
*/
public void ifPresent(Consumer<T> consumer) {
if (isPresent()) {
consumer.consume(value);
}
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise invoke the function passed as the second parameter.
*
* @param consumer block to be executed if a value is present
* @param function block to be executed if a value is absent
*/
public void ifPresentOrElse(Consumer<T> consumer, Function function) {
if (isPresent()) {
consumer.consume(value);
} else {
function.call();
}
}
/**
* Indicates whether some other object is "equal to" this Optional. The
* other object is considered equal if:
* <ul>
* <li>it is also an {@code Optional} and;
* <li>both instances have no value present or;
* <li>the present values are "equal to" each other via {@code equals()}.
* </ul>
*
* @param object an object to be tested for equality
* @return {code true} if the other object is "equal to" this object
* otherwise {@code false}
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Optional)) {
return false;
}
final Optional<?> other = (Optional<?>) object;
return (value == null) ? (other.value == null) : value.equals(other.value);
}
/**
* Returns the hash code value of the present value, if any, or 0 (zero) if
* no value is present.
*
* @return hash code value of the present value or 0 if no value is present
*/
@Override
public int hashCode() {
return isPresent() ? value.hashCode() : 0;
}
/**
* Returns a non-empty string representation of this Optional suitable for
* debugging. The exact presentation format is unspecified and may vary
* between implementations and versions.
*
* @return the string representation of this instance
*/
@Override
public String toString() {
return isPresent() ? String.format("Optional[%s]", value) : "Optional.ABSENT";
}
} |
package io.jxcore.node;
import android.os.CountDownTimer;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.thaliproject.p2p.btconnectorlib.ConnectionManager;
import org.thaliproject.p2p.btconnectorlib.DiscoveryManager;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
public class StartStopOperationHandlerTest {
private ConnectionManager mConnectionManager;
private DiscoveryManager mDiscoveryManager;
private ConnectionHelper mConnectionHelper;
private StartStopOperationHandler mStartStopOperationHandler;
private JXcoreThaliCallbackMock mJXcoreThaliCallback;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
Thread.sleep(5000);
}
@Before
public void setUp() throws Exception {
mConnectionHelper = new ConnectionHelper();
mJXcoreThaliCallback = new JXcoreThaliCallbackMock();
mDiscoveryManager = mConnectionHelper.getDiscoveryManager();
Field fConnectionManager = mConnectionHelper.getClass().getDeclaredField("mConnectionManager");
fConnectionManager.setAccessible(true);
mConnectionManager = (ConnectionManager) fConnectionManager.get(mConnectionHelper);
Field fStartStopOperationHandler = mConnectionHelper.getClass().getDeclaredField("mStartStopOperationHandler");
fStartStopOperationHandler.setAccessible(true);
mStartStopOperationHandler = (StartStopOperationHandler) fStartStopOperationHandler.get(mConnectionHelper);
}
@After
public void tearDown() throws Exception {
mConnectionHelper.killConnections(true);
mConnectionHelper.stop(false, mJXcoreThaliCallback);
mConnectionHelper.dispose();
mConnectionHelper.getDiscoveryManager().stop();
mConnectionHelper.getDiscoveryManager().stopAdvertising();
mConnectionHelper.getDiscoveryManager().stopDiscovery();
mConnectionHelper.getDiscoveryManager().dispose();
mDiscoveryManager.stop();
mDiscoveryManager.stopDiscovery();
mDiscoveryManager.stopAdvertising();
mDiscoveryManager.dispose();
mConnectionManager.dispose();
}
@Test
public void testConstructor() throws Exception {
Field fConnectionManager = mStartStopOperationHandler.getClass()
.getDeclaredField("mConnectionManager");
Field fDiscoveryManager = mStartStopOperationHandler.getClass()
.getDeclaredField("mDiscoveryManager");
fConnectionManager.setAccessible(true);
fDiscoveryManager.setAccessible(true);
ConnectionManager mConnectionManager1 =
(ConnectionManager) fConnectionManager.get(mStartStopOperationHandler);
DiscoveryManager mDiscoveryManager1 =
(DiscoveryManager) fDiscoveryManager.get(mStartStopOperationHandler);
assertThat("mStartStopOperationHandler should not be null", mStartStopOperationHandler,
is(notNullValue()));
assertThat("mConnectionManager1 should not be null", mConnectionManager1,
is(notNullValue()));
assertThat("mConnectionManager1 should be equal to mConnectionManager",
mConnectionManager1, is(equalTo(mConnectionManager)));
assertThat("mDiscoveryManager1 should not be null", mDiscoveryManager1,
is(notNullValue()));
assertThat("mDiscoveryManager1 should be equal to mDiscoveryManager",
mDiscoveryManager1, is(equalTo(mDiscoveryManager)));
}
@Test
public void testCancelCurrentOperation() throws Exception {
mStartStopOperationHandler.cancelCurrentOperation();
Field fCurrentOperation = mStartStopOperationHandler.getClass()
.getDeclaredField("mCurrentOperation");
fCurrentOperation.setAccessible(true);
StartStopOperation mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
Field fOperationTimeoutTimer =
mStartStopOperationHandler.getClass().getDeclaredField("mOperationTimeoutTimer");
fOperationTimeoutTimer.setAccessible(true);
CountDownTimer mOperationTimeoutTimer =
(CountDownTimer) fOperationTimeoutTimer.get(mStartStopOperationHandler);
assertThat("mCurrentOperation should be null3", mCurrentOperation, is(nullValue()));
assertThat("mOperationTimeoutTimer should be null", mOperationTimeoutTimer,
is(nullValue()));
}
@Test
public void testExecuteStartOperation() throws Exception {
mStartStopOperationHandler.executeStartOperation(false, mJXcoreThaliCallback);
Thread.sleep(3000); //After 3s mCurrentOperation should be null
Field fDiscoveryManager =
mStartStopOperationHandler.getClass().getDeclaredField("mDiscoveryManager");
Field fCurrentOperation = mStartStopOperationHandler.getClass()
.getDeclaredField("mCurrentOperation");
fDiscoveryManager.setAccessible(true);
fCurrentOperation.setAccessible(true);
DiscoveryManager mDiscoveryManager1 =
(DiscoveryManager) fDiscoveryManager.get(mStartStopOperationHandler);
StartStopOperation mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
assertThat("mCurrentOperation should be null2", mCurrentOperation, is(nullValue()));
if (!mDiscoveryManager1.isBleMultipleAdvertisementSupported()) {
assertThat("mDiscoveryManager1 state should be NOT_STARTED",
mDiscoveryManager1.getState(),
is(equalTo(DiscoveryManager.DiscoveryManagerState.NOT_STARTED)));
assertThat("mDiscoveryManager1 should be not running",
mDiscoveryManager1.isRunning(),
is(false));
} else {
assertThat("mDiscoveryManager1 state should not be NOT_STARTED",
mDiscoveryManager1.getState(),
is(not(equalTo(DiscoveryManager.DiscoveryManagerState.NOT_STARTED))));
assertThat("mDiscoveryManager1 should be running", mDiscoveryManager1.isRunning(),
is(true));
}
}
@Test
public void testExecuteStopOperation() throws Exception {
mStartStopOperationHandler.executeStartOperation(false, mJXcoreThaliCallback);
mStartStopOperationHandler.executeStopOperation(false, mJXcoreThaliCallback);
Thread.sleep(3000); //After 3s mCurrentOperation should be null
Field fCurrentOperation = mStartStopOperationHandler.getClass()
.getDeclaredField("mCurrentOperation");
Field fDiscoveryManager =
mStartStopOperationHandler.getClass().getDeclaredField("mDiscoveryManager");
fCurrentOperation.setAccessible(true);
fDiscoveryManager.setAccessible(true);
StartStopOperation mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
DiscoveryManager mDiscoveryManager1 =
(DiscoveryManager) fDiscoveryManager.get(mStartStopOperationHandler);
assertThat("mCurrentOperation should be null", mCurrentOperation, is(nullValue()));
assertThat("mDiscoveryManager1 state should be NOT_STARTED", mDiscoveryManager1.getState(),
is(equalTo(DiscoveryManager.DiscoveryManagerState.NOT_STARTED)));
}
@Test
public void testCheckCurrentOperationStatus() throws Exception {
Field fCurrentOperation = mStartStopOperationHandler.getClass()
.getDeclaredField("mCurrentOperation");
fCurrentOperation.setAccessible(true);
fCurrentOperation.set(mStartStopOperationHandler,
StartStopOperation.createStartOperation(false, mJXcoreThaliCallback));
mStartStopOperationHandler.checkCurrentOperationStatus();
Method executeCurrentOperation = mStartStopOperationHandler.getClass()
.getDeclaredMethod("executeCurrentOperation");
executeCurrentOperation.setAccessible(true);
executeCurrentOperation.invoke(mStartStopOperationHandler);
StartStopOperation mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
if(mDiscoveryManager.isBleMultipleAdvertisementSupported())
{
fCurrentOperation.set(mStartStopOperationHandler, StartStopOperation.createStartOperation(false, mJXcoreThaliCallback));
mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
assertThat("mCurrentOperation should not be null1", mCurrentOperation, is(notNullValue()));
mStartStopOperationHandler.checkCurrentOperationStatus();
Thread.sleep(3000);
mCurrentOperation =
(StartStopOperation) fCurrentOperation.get(mStartStopOperationHandler);
assertThat("mCurrentOperation should be null1", mCurrentOperation, is(nullValue()));
} else {
Thread.sleep(3000);
assertThat("mCurrentOperation should be null1", mCurrentOperation, is(nullValue()));
}
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaDocumentService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaXInternalService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaSystemPartnerService;
import com.kaltura.client.services.KalturaEntryAdminService;
import com.kaltura.client.services.KalturaUiConfAdminService;
import com.kaltura.client.services.KalturaReportAdminService;
import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:15-11-28");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaDocumentService documentService;
public KalturaDocumentService getDocumentService() {
if(this.documentService == null)
this.documentService = new KalturaDocumentService(this);
return this.documentService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaXInternalService xInternalService;
public KalturaXInternalService getXInternalService() {
if(this.xInternalService == null)
this.xInternalService = new KalturaXInternalService(this);
return this.xInternalService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaSystemPartnerService systemPartnerService;
public KalturaSystemPartnerService getSystemPartnerService() {
if(this.systemPartnerService == null)
this.systemPartnerService = new KalturaSystemPartnerService(this);
return this.systemPartnerService;
}
protected KalturaEntryAdminService entryAdminService;
public KalturaEntryAdminService getEntryAdminService() {
if(this.entryAdminService == null)
this.entryAdminService = new KalturaEntryAdminService(this);
return this.entryAdminService;
}
protected KalturaUiConfAdminService uiConfAdminService;
public KalturaUiConfAdminService getUiConfAdminService() {
if(this.uiConfAdminService == null)
this.uiConfAdminService = new KalturaUiConfAdminService(this);
return this.uiConfAdminService;
}
protected KalturaReportAdminService reportAdminService;
public KalturaReportAdminService getReportAdminService() {
if(this.reportAdminService == null)
this.reportAdminService = new KalturaReportAdminService(this);
return this.reportAdminService;
}
protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService;
public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() {
if(this.kalturaInternalToolsSystemHelperService == null)
this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this);
return this.kalturaInternalToolsSystemHelperService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
// checkstyle: Checks Java source code for adherence to a set of rules.
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.puppycrawl.tools.checkstyle;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.LogOutputStream;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Path;
//import org.apache.regexp.RESyntaxException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Iterator;
import com.puppycrawl.tools.checkstyle.api.Configuration;
/**
* An implementation of a ANT task for calling checkstyle. See the documentation
* of the task for usage.
* @author <a href="mailto:oliver@puppycrawl.com">Oliver Burn</a>
*/
public class CheckStyleTask
extends Task
{
/** poor man's enum for an xml formatter */
private static final String E_XML = "xml";
/** poor man's enum for an plain formatter */
private static final String E_PLAIN = "plain";
/** class path to locate class files */
private Path mClasspath;
/** name of file to check */
private String mFileName;
/** config file containing configuration */
private File mConfigFile;
/** whether to fail build on violations */
private boolean mFailOnViolation = true;
/** property to set on violations */
private String mFailureProperty = null;
/** contains the filesets to process */
private final List mFileSets = new ArrayList();
/** contains the formatters to log to */
private final List mFormatters = new ArrayList();
/** contains the Properties to override */
private final List mOverrideProps = new ArrayList();
/** the name of the properties file */
private File mPropertiesFile;
// Setters for ANT specific attributes
/**
* Tells this task to set the named property to "true" when there
* is a violation.
* @param aPropertyName the name of the property to set
* in the event of an failure.
*/
public void setFailureProperty(String aPropertyName)
{
mFailureProperty = aPropertyName;
}
/** @param aFail whether to fail if a violation is found */
public void setFailOnViolation(boolean aFail)
{
mFailOnViolation = aFail;
}
/**
* Adds a set of files (nested fileset attribute).
* @param aFS the file set to add
*/
public void addFileset(FileSet aFS)
{
mFileSets.add(aFS);
}
/**
* Add a formatter
* @param aFormatter the formatter to add for logging.
*/
public void addFormatter(Formatter aFormatter)
{
mFormatters.add(aFormatter);
}
/**
* Add an override property
* @param aProperty the property to add
*/
public void addProperty(Property aProperty)
{
mOverrideProps.add(aProperty);
}
/**
* Set the class path.
* @param aClasspath the path to locate classes
*/
public void setClasspath(Path aClasspath)
{
mClasspath = aClasspath;
}
/** @return a created path for locating classes */
public Path createClasspath()
{
if (mClasspath == null) {
mClasspath = new Path(getProject());
}
return mClasspath.createPath();
}
/** @param aFile the file to be checked */
public void setFile(File aFile)
{
mFileName = aFile.getAbsolutePath();
}
/** @param aFile the configuration file to use */
public void setConfig(File aFile)
{
mConfigFile = aFile;
}
// Setters for Checker configuration attributes
/**
* Sets a properties file for use instead
* of individually setting them.
* @param aProps the properties File to use
*/
public void setProperties(File aProps)
{
mPropertiesFile = aProps;
}
// The doers
/**
* Actually checks the files specified. All errors are reported to
* System.out. Will fail if any errors occurred.
* @throws BuildException an error occurred
*/
public void execute()
throws BuildException
{
// Check for no arguments
if ((mFileName == null) && (mFileSets.size() == 0)) {
throw new BuildException(
"Must specify atleast one of 'file' or nested 'fileset'.",
getLocation());
}
if (mConfigFile == null) {
throw new BuildException("Must specify 'config'.", getLocation());
}
// Create the checker
Checker c = null;
try {
try {
final Properties props = createOverridingProperties();
final Configuration config =
ConfigurationLoader.loadConfiguration(
mConfigFile.getAbsolutePath(), props);
DefaultContext context = new DefaultContext();
ClassLoader loader =
new AntClassLoader(getProject(), mClasspath);
context.add("classloader", loader);
c = new Checker();
c.contextualize(context);
c.configure(config);
// setup the listeners
AuditListener[] listeners = getListeners();
for (int i = 0; i < listeners.length; i++) {
c.addListener(listeners[i]);
}
}
catch (Exception e) {
throw new BuildException(
"Unable to create a Checker: " + e.getMessage(), e);
}
// Process the files
final File[] files = scanFileSets();
final int numErrs = c.process(files);
// Handle the return status
if ((numErrs > 0) && mFailureProperty != null) {
getProject().setProperty(mFailureProperty, "true");
}
if ((numErrs > 0) && mFailOnViolation) {
throw new BuildException("Got " + numErrs + " errors.",
getLocation());
}
}
finally {
if (c != null) {
c.destroy();
}
}
}
/**
* Create the Properties object based on the arguments specified
* to the ANT task.
* @return Properties object
* @throws BuildException if an error occurs
*/
private Properties createOverridingProperties()
{
final Properties retVal = new Properties();
// Load the properties file if specified
if (mPropertiesFile != null) {
try {
retVal.load(new FileInputStream(mPropertiesFile));
}
catch (FileNotFoundException e) {
throw new BuildException(
"Could not find Properties file '" + mPropertiesFile + "'",
e, getLocation());
}
catch (IOException e) {
throw new BuildException(
"Error loading Properties file '" + mPropertiesFile + "'",
e, getLocation());
}
}
// Now override the properties specified
for (Iterator it = mOverrideProps.iterator(); it.hasNext();) {
final Property p = (Property) it.next();
retVal.put(p.getKey(), p.getValue());
}
return retVal;
}
protected AuditListener[] getListeners()
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException
{
final int listenerCount = Math.max(1, mFormatters.size());
final AuditListener[] listeners = new AuditListener[listenerCount];
if (mFormatters.size() == 0) {
OutputStream debug = new LogOutputStream(this, Project.MSG_DEBUG);
OutputStream err = new LogOutputStream(this, Project.MSG_ERR);
listeners[0] = new DefaultLogger(debug, true, err, true);
return listeners;
}
for (int i = 0; i < listeners.length; i++) {
final Formatter f = (Formatter) mFormatters.get(i);
listeners[i] = f.createListener(this);
}
return listeners;
}
/**
* returns the list of files (full path name) to process.
* @return the list of files included via the filesets.
*/
protected File[] scanFileSets()
{
final ArrayList list = new ArrayList();
if (mFileName != null) {
// oops we've got an additional one to process, don't
// forget it. No sweat, it's fully resolved via the setter.
log("Adding standalone file for audit", Project.MSG_VERBOSE);
list.add(new File(mFileName));
}
for (int i = 0; i < mFileSets.size(); i++) {
final FileSet fs = (FileSet) mFileSets.get(i);
final DirectoryScanner ds = fs.getDirectoryScanner(getProject());
ds.scan();
final String[] names = ds.getIncludedFiles();
log(i + ") Adding " + names.length + " files from directory "
+ ds.getBasedir(),
Project.MSG_VERBOSE);
for (int j = 0; j < names.length; j++) {
final String pathname =
ds.getBasedir() + File.separator + names[j];
list.add(new File(pathname));
}
}
return (File[]) list.toArray(new File[0]);
}
/**
* Poor mans enumeration for the formatter types.
* @author <a href="mailto:oliver@puppycrawl.com">Oliver Burn</a>
*/
public static class FormatterType
extends EnumeratedAttribute
{
/** my possible values */
private static final String[] VALUES = {E_XML, E_PLAIN};
/** @see EnumeratedAttribute */
public String[] getValues()
{
return VALUES;
}
}
/**
* Details about a formatter to be used.
* @author <a href="mailto:oliver@puppycrawl.com">Oliver Burn</a>
*/
public static class Formatter
{
/** the formatter type */
private FormatterType mFormatterType = null;
/** the file to output to */
private File mToFile = null;
/**
* Set the type of the formatter.
* @param aType the type
*/
public void setType(FormatterType aType)
{
final String val = aType.getValue();
if (!E_XML.equals(val) && !E_PLAIN.equals(val)) {
throw new BuildException("Invalid formatter type: " + val);
}
mFormatterType = aType;
}
/**
* Set the file to output to.
* @param aTo the file to output to
*/
public void setTofile(File aTo)
{
mToFile = aTo;
}
/**
* Creates a listener for the formatter.
* @param aTask the task running
* @return a listener
* @throws IOException if an error occurs
*/
public AuditListener createListener(Task aTask)
throws IOException
{
if (E_XML.equals(mFormatterType.getValue())) {
return createXMLLogger(aTask);
}
else {
return createDefaultLogger(aTask);
}
}
/**
* @return a DefaultLogger instance
* @param aTask the task to possibly log to
* @throws IOException if an error occurs
*/
private AuditListener createDefaultLogger(Task aTask)
throws IOException
{
if (mToFile == null) {
return new DefaultLogger(
new LogOutputStream(aTask, Project.MSG_DEBUG), true,
new LogOutputStream(aTask, Project.MSG_ERR), true);
}
return new DefaultLogger(new FileOutputStream(mToFile), true);
}
/**
* @return an XMLLogger instance
* @param aTask the task to possibly log to
* @throws IOException if an error occurs
*/
private AuditListener createXMLLogger(Task aTask)
throws IOException
{
if (mToFile == null) {
return new XMLLogger(
new LogOutputStream(aTask, Project.MSG_INFO), true);
}
else {
return new XMLLogger(new FileOutputStream(mToFile), true);
}
}
}
/**
* Represents a property that consists of a key and value.
*/
public static class Property
{
/** the property key */
private String mKey;
/** the property value */
private String mValue;
/** @return the property key */
public String getKey()
{
return mKey;
}
/** @param aKey sets the property key */
public void setKey(String aKey)
{
mKey = aKey;
}
/** @return the property value */
public String getValue()
{
return mValue;
}
/** @param aValue set the property value */
public void setValue(String aValue)
{
mValue = aValue;
}
/** @param aValue set the property value from a File */
public void setFile(File aValue)
{
setValue(aValue.getAbsolutePath());
}
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:16-10-23");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package me.coley.recaf.ui.component.panel;
import java.awt.BorderLayout;
import java.util.List;
import java.util.function.Consumer;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.AbstractInsnNode;
import me.coley.recaf.Program;
import me.coley.recaf.ui.component.LabeledComponent;
import me.coley.recaf.ui.component.action.ActionButton;
import me.coley.recaf.ui.component.tree.ASMFieldTreeNode;
import me.coley.recaf.ui.component.tree.ASMInsnTreeNode;
import me.coley.recaf.ui.component.tree.ASMMethodTreeNode;
import me.coley.recaf.ui.component.tree.ASMTreeNode;
import me.coley.recaf.ui.component.tree.JavaTreeListener;
import me.coley.recaf.ui.component.tree.JavaTreeRenderer;
import me.coley.recaf.util.Misc;
import me.coley.recaf.util.StreamUtil;
@SuppressWarnings("serial")
public class SearchPanel extends JPanel {
public static final int S_STRINGS = 0;
public static final int S_FIELD = 10;
public static final int S_METHOD = 20;
public static final int S_CLASS_NAME = 30, S_CLASS_REF = 31;
private final Program callback = Program.getInstance();
private final JTree tree = new JTree(new String[] {});
public SearchPanel(int type) {
setLayout(new BorderLayout());
JPanel pnlInput = new JPanel(), pnlOutput = new JPanel();
pnlInput.setLayout(new BoxLayout(pnlInput, BoxLayout.Y_AXIS));
pnlOutput.setLayout(new BorderLayout());
JScrollPane scrollTree = new JScrollPane(tree);
pnlOutput.add(scrollTree, BorderLayout.CENTER);
tree.setCellRenderer(new JavaTreeRenderer());
JavaTreeListener sel = new JavaTreeListener();
tree.addTreeSelectionListener(sel);
tree.addMouseListener(sel);
tree.addTreeExpansionListener(sel);
JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pnlInput, pnlOutput);
split.setResizeWeight(0.67);
switch (type) {
case S_STRINGS: {
JTextField text;
JCheckBox caseSense;
pnlInput.add(new LabeledComponent("String", text = new JTextField("")));
pnlInput.add(caseSense = new JCheckBox("Case sensitive"));
pnlInput.add(new ActionButton("Search", () -> searchString(text.getText(), caseSense.isSelected())));
break;
}
case S_FIELD: {
JTextField name, desc;
pnlInput.add(new LabeledComponent("Field name", name = new JTextField("")));
pnlInput.add(new LabeledComponent("Field desc", desc = new JTextField("")));
pnlInput.add(new ActionButton("Search", () -> searchField(name.getText(), desc.getText())));
break;
}
case S_METHOD: {
JTextField name, desc;
pnlInput.add(new LabeledComponent("Method name", name = new JTextField("")));
pnlInput.add(new LabeledComponent("Method desc", desc = new JTextField("")));
pnlInput.add(new ActionButton("Search", () -> searchMethod(name.getText(), desc.getText())));
break;
}
case S_CLASS_NAME: {
JTextField clazz;
JCheckBox ex;
pnlInput.add(new LabeledComponent("Class name", clazz = new JTextField("")));
pnlInput.add(ex = new JCheckBox("Exact match"));
pnlInput.add(new ActionButton("Search", () -> searchClass(clazz.getText(), ex.isSelected())));
break;
}
case S_CLASS_REF: {
JTextField clazz, name, desc;
JCheckBox ex;
pnlInput.add(new LabeledComponent("Class owner", clazz = new JTextField("")));
pnlInput.add(new LabeledComponent("Member name", name = new JTextField("")));
pnlInput.add(new LabeledComponent("Member desc", desc = new JTextField("")));
pnlInput.add(ex = new JCheckBox("Exact match"));
pnlInput.add(new ActionButton("Search", () -> searchClassRef(clazz.getText(), name.getText(), desc.getText(), ex.isSelected())));
break;
}
}
add(split, BorderLayout.CENTER);
}
private void searchString(String text, boolean caseSensitive) {
DefaultTreeModel model = setup();
search((n) -> {
for (MethodNode m : n.methods) {
for (AbstractInsnNode ain : m.instructions.toArray()) {
if (ain.getType() == AbstractInsnNode.LDC_INSN) {
LdcInsnNode ldc = (LdcInsnNode) ain;
String s = ldc.cst.toString();
if ((caseSensitive && s.contains(text)) || (!caseSensitive && (s.toLowerCase().contains(text.toLowerCase())))) {
// Get tree node for class
ASMTreeNode genClass = Misc.getOrCreateNode(model, n);
// Get or create tree node for method
ASMTreeNode genMethod = genClass.getChild(m.name);
if (genMethod == null) {
genClass.addChild(m.name, genMethod = new ASMMethodTreeNode(m.name + m.desc, n, m));
genClass.add(genMethod);
}
// Add opcode node to method tree node
genMethod.add(new ASMInsnTreeNode(m.instructions.indexOf(ain) + ": '" + s + "'", n, m, ain));
}
}
}
}
});
tree.setModel(model);
}
private void searchField(String name, String desc) {
DefaultTreeModel model = setup();
search((n) -> {
for (FieldNode f : n.fields) {
if (f.name.contains(name) && f.desc.contains(desc)) {
ASMTreeNode genClass = Misc.getOrCreateNode(model, n);
ASMTreeNode genMethod = genClass.getChild(f.name);
if (genMethod == null) {
genMethod = new ASMFieldTreeNode(f.desc + " " + f.name, n, f);
}
genClass.add(genMethod);
}
}
});
tree.setModel(model);
}
private void searchMethod(String name, String desc) {
DefaultTreeModel model = setup();
search((n) -> {
for (MethodNode m : n.methods) {
if (m.name.contains(name) && m.desc.contains(desc)) {
ASMTreeNode genClass = Misc.getOrCreateNode(model, n);
ASMTreeNode genMethod = genClass.getChild(m.name);
if (genMethod == null) {
genMethod = new ASMMethodTreeNode(m.name + m.desc, n,m);
}
genClass.add(genMethod);
}
}
});
tree.setModel(model);
}
private void searchClass(String text, boolean exact) {
DefaultTreeModel model = setup();
search((n) -> {
if (exact ? n.name.equals(text) : n.name.contains(text)) {
Misc.getOrCreateNode(model, n);
}
});
tree.setModel(model);
}
private void searchClassRef(String owner, String name, String desc, boolean exact) {
DefaultTreeModel model = setup();
search((n) -> {
for (MethodNode m : n.methods) {
for (AbstractInsnNode ain : m.instructions.toArray()) {
if (ain.getType() == AbstractInsnNode.FIELD_INSN) {
FieldInsnNode fin = (FieldInsnNode) ain;
if ((exact && (fin.owner.equals(owner) && fin.name.equals(name) && fin.desc.equals(desc))) ||
(!exact && (fin.owner.contains(owner) && fin.name.contains(name) && fin.desc.contains(desc)))) {
System.out.println("A");
ASMTreeNode genClass = Misc.getOrCreateNode(model, n);
// Get or create tree node for method
ASMTreeNode genMethod = genClass.getChild(m.name);
if (genMethod == null) {
genClass.addChild(m.name, genMethod = new ASMMethodTreeNode(m.name + m.desc, n, m));
genClass.add(genMethod);
}
// Add opcode node to method tree node
genMethod.add(new ASMInsnTreeNode(m.instructions.indexOf(ain) + ": " + fin.name, n, m, ain));
}
} else if (ain.getType() == AbstractInsnNode.METHOD_INSN) {
MethodInsnNode min = (MethodInsnNode) ain;
if ((exact && (min.owner.equals(owner) && min.name.equals(name) && min.desc.equals(desc))) ||
(!exact && (min.owner.contains(owner) && min.name.contains(name) && min.desc.contains(desc)))) {
// Get tree node for class
ASMTreeNode genClass = Misc.getOrCreateNode(model, n);
// Get or create tree node for method
ASMTreeNode genMethod = genClass.getChild(m.name);
if (genMethod == null) {
genClass.addChild(m.name, genMethod = new ASMMethodTreeNode(m.name + m.desc, n, m));
genClass.add(genMethod);
}
// Add opcode node to method tree node
genMethod.add(new ASMInsnTreeNode(m.instructions.indexOf(ain) + ": " + min.name, n, m, ain));
}
}
}
}
});
tree.setModel(model);
}
/**
* Setup and return the tree model for a search.
*
* @return
*/
private DefaultTreeModel setup() {
String jarName = callback.currentJar.getName();
ASMTreeNode root = new ASMTreeNode(jarName, null);
DefaultTreeModel model = new DefaultTreeModel(root);
model.setRoot(root);
return model;
}
/**
* Search and pass classnodes through the given function.
*
* @param model
* @param func
*/
private void search(Consumer<ClassNode> func) {
List<String> names = StreamUtil.listOfSortedJavaNames(callback.jarData.classes.keySet());
for (String className : names) {
ClassNode node = callback.jarData.classes.get(className);
func.accept(node);
}
}
} |
package org.opencms.db;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsGroup;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsResource;
import org.opencms.file.CmsUser;
import org.opencms.file.history.I_CmsHistoryResource;
import org.opencms.main.OpenCms;
import org.opencms.test.OpenCmsTestCase;
import org.opencms.test.OpenCmsTestProperties;
import java.util.List;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* Unit tests for OpenCms subscription manager.<p>
*/
public class TestSubscriptionManager extends OpenCmsTestCase {
/** Time to wait for a database operation to finish. */
private static final long WAIT_FOR_DB_MILLIS = 300;
/**
* Default JUnit constructor.<p>
*
* @param arg0 JUnit parameters
*/
public TestSubscriptionManager(String arg0) {
super(arg0);
}
/**
* Test suite for this test class.<p>
*
* @return the test suite
*/
public static Test suite() {
OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
TestSuite suite = new TestSuite();
suite.setName(TestSubscriptionManager.class.getName());
suite.addTest(new TestSubscriptionManager("testVisitResources"));
suite.addTest(new TestSubscriptionManager("testSubscribeResources"));
suite.addTest(new TestSubscriptionManager("testReadSubscribedResources"));
TestSetup wrapper = new TestSetup(suite) {
@Override
protected void setUp() {
setupOpenCms("simpletest", "/");
}
@Override
protected void tearDown() {
removeOpenCms();
}
};
return wrapper;
}
/**
* Test reading subscribed resources.<p>
*
* @throws Throwable if something goes wrong
*/
public void testReadSubscribedResources() throws Throwable {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
CmsGroup group = cms.readGroup("Users");
echo("Testing reading subscribed resources");
CmsSubscriptionManager subMan = OpenCms.getSubscriptionManager();
subMan.subscribeResourceFor(cms, user, "/folder2/index.html");
List<CmsResource> subscribedUserResources = subMan.readAllSubscribedResources(cms, user);
assertEquals(1, subscribedUserResources.size());
assertEquals("/folder2/index.html", cms.getSitePath(subscribedUserResources.get(0)));
subMan.subscribeResourceFor(cms, group, "/folder2/index.html");
CmsSubscriptionFilter filter = new CmsSubscriptionFilter();
filter.addGroup(group);
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(1, subscribedUserResources.size());
filter.setUser(user);
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(1, subscribedUserResources.size());
subMan.subscribeResourceFor(cms, user, "/folder2/page1.html");
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(2, subscribedUserResources.size());
Thread.sleep(WAIT_FOR_DB_MILLIS);
subMan.markResourceAsVisitedBy(cms, "/folder2/page1.html", user);
Thread.sleep(WAIT_FOR_DB_MILLIS);
filter.setMode(CmsSubscriptionReadMode.VISITED);
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(1, subscribedUserResources.size());
filter.setMode(CmsSubscriptionReadMode.UNVISITED);
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(1, subscribedUserResources.size());
long beforeChangeTime = System.currentTimeMillis();
Thread.sleep(WAIT_FOR_DB_MILLIS);
cms.lockResource("/folder2/page1.html");
CmsFile file = cms.readFile("/folder2/page1.html");
cms.writeFile(file);
cms.unlockResource("/folder2/page1.html");
OpenCms.getPublishManager().publishResource(cms, "/folder2/page1.html");
OpenCms.getPublishManager().waitWhileRunning();
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(2, subscribedUserResources.size());
filter.setFromDate(beforeChangeTime);
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(1, subscribedUserResources.size());
filter.setFromDate(System.currentTimeMillis());
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(0, subscribedUserResources.size());
filter.setFromDate(beforeChangeTime);
cms.lockResource("/folder2/page1.html");
cms.deleteResource("/folder2/page1.html", CmsResource.DELETE_REMOVE_SIBLINGS);
OpenCms.getPublishManager().publishResource(cms, "/folder2/page1.html");
OpenCms.getPublishManager().waitWhileRunning();
subscribedUserResources = subMan.readSubscribedResources(cms, filter);
assertEquals(0, subscribedUserResources.size());
List<I_CmsHistoryResource> subscribedDeletedResources = subMan.readSubscribedDeletedResources(
cms,
user,
false,
"/folder2/",
false,
0);
assertEquals(1, subscribedDeletedResources.size());
subMan.unsubscribeAllDeletedResources(cms, Long.MAX_VALUE);
subscribedDeletedResources = subMan.readSubscribedDeletedResources(cms, user, false, null, false, 0);
assertEquals(0, subscribedDeletedResources.size());
}
/**
* Test subscription of resources.<p>
*
* @throws Throwable if something goes wrong
*/
public void testSubscribeResources() throws Throwable {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
echo("Testing subscription of resources");
CmsSubscriptionManager subMan = OpenCms.getSubscriptionManager();
subMan.subscribeResourceFor(cms, user, "/index.html");
List<CmsResource> subscribedUserResources = subMan.readAllSubscribedResources(cms, user);
assertEquals(1, subscribedUserResources.size());
assertEquals("/index.html", cms.getSitePath(subscribedUserResources.get(0)));
subMan.unsubscribeResourceFor(cms, user, "/index.html");
subscribedUserResources = subMan.readAllSubscribedResources(cms, user);
assertEquals(0, subscribedUserResources.size());
}
/**
* Test subscription of resources.<p>
*
* @throws Throwable if something goes wrong
*/
public void testVisitResources() throws Throwable {
CmsObject cms = getCmsObject();
CmsUser user = cms.getRequestContext().getCurrentUser();
echo("Testing visitation of resources");
CmsSubscriptionManager subMan = OpenCms.getSubscriptionManager();
subMan.markResourceAsVisitedBy(cms, "/folder1/index.html", user);
CmsVisitedByFilter filter = new CmsVisitedByFilter(cms);
List<CmsResource> visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(1, visitedUserResources.size());
assertEquals("/folder1/index.html", cms.getSitePath(visitedUserResources.get(0)));
// wait between operations to be able to perform time based tests
Thread.sleep(WAIT_FOR_DB_MILLIS);
long storedTime = System.currentTimeMillis();
Thread.sleep(WAIT_FOR_DB_MILLIS);
subMan.markResourceAsVisitedBy(cms, "/folder1/page1.html", user);
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(2, visitedUserResources.size());
filter.setFromDate(storedTime);
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(1, visitedUserResources.size());
assertEquals("/folder1/page1.html", cms.getSitePath(visitedUserResources.get(0)));
Thread.sleep(WAIT_FOR_DB_MILLIS);
storedTime = System.currentTimeMillis();
filter.setFromDate(storedTime);
Thread.sleep(WAIT_FOR_DB_MILLIS);
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(0, visitedUserResources.size());
subMan.markResourceAsVisitedBy(cms, "/folder1/page2.html", user);
Thread.sleep(WAIT_FOR_DB_MILLIS);
subMan.markResourceAsVisitedBy(cms, "/folder1/page3.html", user);
Thread.sleep(WAIT_FOR_DB_MILLIS);
subMan.markResourceAsVisitedBy(cms, "/folder1/subfolder11/page1.html", user);
Thread.sleep(WAIT_FOR_DB_MILLIS);
subMan.markResourceAsVisitedBy(cms, "/folder1/subfolder11/page2.html", user);
filter = new CmsVisitedByFilter(cms);
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(6, visitedUserResources.size());
filter.setToDate(storedTime);
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(2, visitedUserResources.size());
assertNotSame(Long.valueOf(0L), Long.valueOf(subMan.getDateLastVisitedBy(cms, user, "/folder1/page2.html")));
assertNotSame(Long.valueOf(0L), Long.valueOf(subMan.getDateLastVisitedBy(cms, user, "/folder1/index.html")));
assertSame(Long.valueOf(0L), Long.valueOf(subMan.getDateLastVisitedBy(cms, user, "/index.html")));
filter.setToDate(Long.MAX_VALUE);
filter.setParentResource(cms.readResource("/folder1/subfolder11/page1.html"));
visitedUserResources = subMan.readResourcesVisitedBy(cms, filter);
assertEquals(2, visitedUserResources.size());
}
} |
package com.typee.typee;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends Activity {
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello",
"bar@example.com:world"
};
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Add your initialization code here
Parse.initialize(this, "mFrewsKnWGVdz9AJJHfaN7WXKxq5LAz2Mp8B8mIR", "R88iw1KmwjFuUqaOxx8qceVGkzivBiQnKuICJCvJ");
//Parse
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
//End Parse
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!mEmail.contains("@")) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate()
.setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate()
.setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
} |
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
// This program is free software: you can redistribute it and/or modify
// published by the Free Software Foundation, either version 3 of the
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// @ignore
package com.kaltura.client;
import com.kaltura.client.services.KalturaAccessControlProfileService;
import com.kaltura.client.services.KalturaAccessControlService;
import com.kaltura.client.services.KalturaAdminUserService;
import com.kaltura.client.services.KalturaAnalyticsService;
import com.kaltura.client.services.KalturaAppTokenService;
import com.kaltura.client.services.KalturaBaseEntryService;
import com.kaltura.client.services.KalturaBulkUploadService;
import com.kaltura.client.services.KalturaCategoryEntryService;
import com.kaltura.client.services.KalturaCategoryService;
import com.kaltura.client.services.KalturaCategoryUserService;
import com.kaltura.client.services.KalturaConversionProfileAssetParamsService;
import com.kaltura.client.services.KalturaConversionProfileService;
import com.kaltura.client.services.KalturaDataService;
import com.kaltura.client.services.KalturaDeliveryProfileService;
import com.kaltura.client.services.KalturaEmailIngestionProfileService;
import com.kaltura.client.services.KalturaEntryServerNodeService;
import com.kaltura.client.services.KalturaFileAssetService;
import com.kaltura.client.services.KalturaFlavorAssetService;
import com.kaltura.client.services.KalturaFlavorParamsOutputService;
import com.kaltura.client.services.KalturaFlavorParamsService;
import com.kaltura.client.services.KalturaGroupUserService;
import com.kaltura.client.services.KalturaLiveChannelSegmentService;
import com.kaltura.client.services.KalturaLiveChannelService;
import com.kaltura.client.services.KalturaLiveReportsService;
import com.kaltura.client.services.KalturaLiveStatsService;
import com.kaltura.client.services.KalturaLiveStreamService;
import com.kaltura.client.services.KalturaMediaInfoService;
import com.kaltura.client.services.KalturaMediaService;
import com.kaltura.client.services.KalturaMixingService;
import com.kaltura.client.services.KalturaNotificationService;
import com.kaltura.client.services.KalturaPartnerService;
import com.kaltura.client.services.KalturaPermissionItemService;
import com.kaltura.client.services.KalturaPermissionService;
import com.kaltura.client.services.KalturaPlaylistService;
import com.kaltura.client.services.KalturaReportService;
import com.kaltura.client.services.KalturaResponseProfileService;
import com.kaltura.client.services.KalturaSchemaService;
import com.kaltura.client.services.KalturaSearchService;
import com.kaltura.client.services.KalturaServerNodeService;
import com.kaltura.client.services.KalturaSessionService;
import com.kaltura.client.services.KalturaStatsService;
import com.kaltura.client.services.KalturaStorageProfileService;
import com.kaltura.client.services.KalturaSyndicationFeedService;
import com.kaltura.client.services.KalturaSystemService;
import com.kaltura.client.services.KalturaThumbAssetService;
import com.kaltura.client.services.KalturaThumbParamsOutputService;
import com.kaltura.client.services.KalturaThumbParamsService;
import com.kaltura.client.services.KalturaUiConfService;
import com.kaltura.client.services.KalturaUploadService;
import com.kaltura.client.services.KalturaUploadTokenService;
import com.kaltura.client.services.KalturaUserEntryService;
import com.kaltura.client.services.KalturaUserRoleService;
import com.kaltura.client.services.KalturaUserService;
import com.kaltura.client.services.KalturaWidgetService;
import com.kaltura.client.services.KalturaMetadataService;
import com.kaltura.client.services.KalturaMetadataProfileService;
import com.kaltura.client.services.KalturaDocumentsService;
import com.kaltura.client.services.KalturaVirusScanProfileService;
import com.kaltura.client.services.KalturaDistributionProfileService;
import com.kaltura.client.services.KalturaEntryDistributionService;
import com.kaltura.client.services.KalturaDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderService;
import com.kaltura.client.services.KalturaGenericDistributionProviderActionService;
import com.kaltura.client.services.KalturaCuePointService;
import com.kaltura.client.services.KalturaAnnotationService;
import com.kaltura.client.services.KalturaQuizService;
import com.kaltura.client.services.KalturaShortLinkService;
import com.kaltura.client.services.KalturaBulkService;
import com.kaltura.client.services.KalturaDropFolderService;
import com.kaltura.client.services.KalturaDropFolderFileService;
import com.kaltura.client.services.KalturaCaptionAssetService;
import com.kaltura.client.services.KalturaCaptionParamsService;
import com.kaltura.client.services.KalturaCaptionAssetItemService;
import com.kaltura.client.services.KalturaAttachmentAssetService;
import com.kaltura.client.services.KalturaTagService;
import com.kaltura.client.services.KalturaLikeService;
import com.kaltura.client.services.KalturaVarConsoleService;
import com.kaltura.client.services.KalturaEventNotificationTemplateService;
import com.kaltura.client.services.KalturaExternalMediaService;
import com.kaltura.client.services.KalturaScheduleEventService;
import com.kaltura.client.services.KalturaScheduleResourceService;
import com.kaltura.client.services.KalturaScheduleEventResourceService;
import com.kaltura.client.services.KalturaScheduledTaskProfileService;
import com.kaltura.client.services.KalturaIntegrationService;
import com.kaltura.client.types.KalturaBaseResponseProfile;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
public class KalturaClient extends KalturaClientBase {
public KalturaClient(KalturaConfiguration config) {
super(config);
this.setClientTag("java:17-03-15");
this.setApiVersion("3.3.0");
}
protected KalturaAccessControlProfileService accessControlProfileService;
public KalturaAccessControlProfileService getAccessControlProfileService() {
if(this.accessControlProfileService == null)
this.accessControlProfileService = new KalturaAccessControlProfileService(this);
return this.accessControlProfileService;
}
protected KalturaAccessControlService accessControlService;
public KalturaAccessControlService getAccessControlService() {
if(this.accessControlService == null)
this.accessControlService = new KalturaAccessControlService(this);
return this.accessControlService;
}
protected KalturaAdminUserService adminUserService;
public KalturaAdminUserService getAdminUserService() {
if(this.adminUserService == null)
this.adminUserService = new KalturaAdminUserService(this);
return this.adminUserService;
}
protected KalturaAnalyticsService analyticsService;
public KalturaAnalyticsService getAnalyticsService() {
if(this.analyticsService == null)
this.analyticsService = new KalturaAnalyticsService(this);
return this.analyticsService;
}
protected KalturaAppTokenService appTokenService;
public KalturaAppTokenService getAppTokenService() {
if(this.appTokenService == null)
this.appTokenService = new KalturaAppTokenService(this);
return this.appTokenService;
}
protected KalturaBaseEntryService baseEntryService;
public KalturaBaseEntryService getBaseEntryService() {
if(this.baseEntryService == null)
this.baseEntryService = new KalturaBaseEntryService(this);
return this.baseEntryService;
}
protected KalturaBulkUploadService bulkUploadService;
public KalturaBulkUploadService getBulkUploadService() {
if(this.bulkUploadService == null)
this.bulkUploadService = new KalturaBulkUploadService(this);
return this.bulkUploadService;
}
protected KalturaCategoryEntryService categoryEntryService;
public KalturaCategoryEntryService getCategoryEntryService() {
if(this.categoryEntryService == null)
this.categoryEntryService = new KalturaCategoryEntryService(this);
return this.categoryEntryService;
}
protected KalturaCategoryService categoryService;
public KalturaCategoryService getCategoryService() {
if(this.categoryService == null)
this.categoryService = new KalturaCategoryService(this);
return this.categoryService;
}
protected KalturaCategoryUserService categoryUserService;
public KalturaCategoryUserService getCategoryUserService() {
if(this.categoryUserService == null)
this.categoryUserService = new KalturaCategoryUserService(this);
return this.categoryUserService;
}
protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService;
public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() {
if(this.conversionProfileAssetParamsService == null)
this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this);
return this.conversionProfileAssetParamsService;
}
protected KalturaConversionProfileService conversionProfileService;
public KalturaConversionProfileService getConversionProfileService() {
if(this.conversionProfileService == null)
this.conversionProfileService = new KalturaConversionProfileService(this);
return this.conversionProfileService;
}
protected KalturaDataService dataService;
public KalturaDataService getDataService() {
if(this.dataService == null)
this.dataService = new KalturaDataService(this);
return this.dataService;
}
protected KalturaDeliveryProfileService deliveryProfileService;
public KalturaDeliveryProfileService getDeliveryProfileService() {
if(this.deliveryProfileService == null)
this.deliveryProfileService = new KalturaDeliveryProfileService(this);
return this.deliveryProfileService;
}
protected KalturaEmailIngestionProfileService EmailIngestionProfileService;
public KalturaEmailIngestionProfileService getEmailIngestionProfileService() {
if(this.EmailIngestionProfileService == null)
this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this);
return this.EmailIngestionProfileService;
}
protected KalturaEntryServerNodeService entryServerNodeService;
public KalturaEntryServerNodeService getEntryServerNodeService() {
if(this.entryServerNodeService == null)
this.entryServerNodeService = new KalturaEntryServerNodeService(this);
return this.entryServerNodeService;
}
protected KalturaFileAssetService fileAssetService;
public KalturaFileAssetService getFileAssetService() {
if(this.fileAssetService == null)
this.fileAssetService = new KalturaFileAssetService(this);
return this.fileAssetService;
}
protected KalturaFlavorAssetService flavorAssetService;
public KalturaFlavorAssetService getFlavorAssetService() {
if(this.flavorAssetService == null)
this.flavorAssetService = new KalturaFlavorAssetService(this);
return this.flavorAssetService;
}
protected KalturaFlavorParamsOutputService flavorParamsOutputService;
public KalturaFlavorParamsOutputService getFlavorParamsOutputService() {
if(this.flavorParamsOutputService == null)
this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this);
return this.flavorParamsOutputService;
}
protected KalturaFlavorParamsService flavorParamsService;
public KalturaFlavorParamsService getFlavorParamsService() {
if(this.flavorParamsService == null)
this.flavorParamsService = new KalturaFlavorParamsService(this);
return this.flavorParamsService;
}
protected KalturaGroupUserService groupUserService;
public KalturaGroupUserService getGroupUserService() {
if(this.groupUserService == null)
this.groupUserService = new KalturaGroupUserService(this);
return this.groupUserService;
}
protected KalturaLiveChannelSegmentService liveChannelSegmentService;
public KalturaLiveChannelSegmentService getLiveChannelSegmentService() {
if(this.liveChannelSegmentService == null)
this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this);
return this.liveChannelSegmentService;
}
protected KalturaLiveChannelService liveChannelService;
public KalturaLiveChannelService getLiveChannelService() {
if(this.liveChannelService == null)
this.liveChannelService = new KalturaLiveChannelService(this);
return this.liveChannelService;
}
protected KalturaLiveReportsService liveReportsService;
public KalturaLiveReportsService getLiveReportsService() {
if(this.liveReportsService == null)
this.liveReportsService = new KalturaLiveReportsService(this);
return this.liveReportsService;
}
protected KalturaLiveStatsService liveStatsService;
public KalturaLiveStatsService getLiveStatsService() {
if(this.liveStatsService == null)
this.liveStatsService = new KalturaLiveStatsService(this);
return this.liveStatsService;
}
protected KalturaLiveStreamService liveStreamService;
public KalturaLiveStreamService getLiveStreamService() {
if(this.liveStreamService == null)
this.liveStreamService = new KalturaLiveStreamService(this);
return this.liveStreamService;
}
protected KalturaMediaInfoService mediaInfoService;
public KalturaMediaInfoService getMediaInfoService() {
if(this.mediaInfoService == null)
this.mediaInfoService = new KalturaMediaInfoService(this);
return this.mediaInfoService;
}
protected KalturaMediaService mediaService;
public KalturaMediaService getMediaService() {
if(this.mediaService == null)
this.mediaService = new KalturaMediaService(this);
return this.mediaService;
}
protected KalturaMixingService mixingService;
public KalturaMixingService getMixingService() {
if(this.mixingService == null)
this.mixingService = new KalturaMixingService(this);
return this.mixingService;
}
protected KalturaNotificationService notificationService;
public KalturaNotificationService getNotificationService() {
if(this.notificationService == null)
this.notificationService = new KalturaNotificationService(this);
return this.notificationService;
}
protected KalturaPartnerService partnerService;
public KalturaPartnerService getPartnerService() {
if(this.partnerService == null)
this.partnerService = new KalturaPartnerService(this);
return this.partnerService;
}
protected KalturaPermissionItemService permissionItemService;
public KalturaPermissionItemService getPermissionItemService() {
if(this.permissionItemService == null)
this.permissionItemService = new KalturaPermissionItemService(this);
return this.permissionItemService;
}
protected KalturaPermissionService permissionService;
public KalturaPermissionService getPermissionService() {
if(this.permissionService == null)
this.permissionService = new KalturaPermissionService(this);
return this.permissionService;
}
protected KalturaPlaylistService playlistService;
public KalturaPlaylistService getPlaylistService() {
if(this.playlistService == null)
this.playlistService = new KalturaPlaylistService(this);
return this.playlistService;
}
protected KalturaReportService reportService;
public KalturaReportService getReportService() {
if(this.reportService == null)
this.reportService = new KalturaReportService(this);
return this.reportService;
}
protected KalturaResponseProfileService responseProfileService;
public KalturaResponseProfileService getResponseProfileService() {
if(this.responseProfileService == null)
this.responseProfileService = new KalturaResponseProfileService(this);
return this.responseProfileService;
}
protected KalturaSchemaService schemaService;
public KalturaSchemaService getSchemaService() {
if(this.schemaService == null)
this.schemaService = new KalturaSchemaService(this);
return this.schemaService;
}
protected KalturaSearchService searchService;
public KalturaSearchService getSearchService() {
if(this.searchService == null)
this.searchService = new KalturaSearchService(this);
return this.searchService;
}
protected KalturaServerNodeService serverNodeService;
public KalturaServerNodeService getServerNodeService() {
if(this.serverNodeService == null)
this.serverNodeService = new KalturaServerNodeService(this);
return this.serverNodeService;
}
protected KalturaSessionService sessionService;
public KalturaSessionService getSessionService() {
if(this.sessionService == null)
this.sessionService = new KalturaSessionService(this);
return this.sessionService;
}
protected KalturaStatsService statsService;
public KalturaStatsService getStatsService() {
if(this.statsService == null)
this.statsService = new KalturaStatsService(this);
return this.statsService;
}
protected KalturaStorageProfileService storageProfileService;
public KalturaStorageProfileService getStorageProfileService() {
if(this.storageProfileService == null)
this.storageProfileService = new KalturaStorageProfileService(this);
return this.storageProfileService;
}
protected KalturaSyndicationFeedService syndicationFeedService;
public KalturaSyndicationFeedService getSyndicationFeedService() {
if(this.syndicationFeedService == null)
this.syndicationFeedService = new KalturaSyndicationFeedService(this);
return this.syndicationFeedService;
}
protected KalturaSystemService systemService;
public KalturaSystemService getSystemService() {
if(this.systemService == null)
this.systemService = new KalturaSystemService(this);
return this.systemService;
}
protected KalturaThumbAssetService thumbAssetService;
public KalturaThumbAssetService getThumbAssetService() {
if(this.thumbAssetService == null)
this.thumbAssetService = new KalturaThumbAssetService(this);
return this.thumbAssetService;
}
protected KalturaThumbParamsOutputService thumbParamsOutputService;
public KalturaThumbParamsOutputService getThumbParamsOutputService() {
if(this.thumbParamsOutputService == null)
this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this);
return this.thumbParamsOutputService;
}
protected KalturaThumbParamsService thumbParamsService;
public KalturaThumbParamsService getThumbParamsService() {
if(this.thumbParamsService == null)
this.thumbParamsService = new KalturaThumbParamsService(this);
return this.thumbParamsService;
}
protected KalturaUiConfService uiConfService;
public KalturaUiConfService getUiConfService() {
if(this.uiConfService == null)
this.uiConfService = new KalturaUiConfService(this);
return this.uiConfService;
}
protected KalturaUploadService uploadService;
public KalturaUploadService getUploadService() {
if(this.uploadService == null)
this.uploadService = new KalturaUploadService(this);
return this.uploadService;
}
protected KalturaUploadTokenService uploadTokenService;
public KalturaUploadTokenService getUploadTokenService() {
if(this.uploadTokenService == null)
this.uploadTokenService = new KalturaUploadTokenService(this);
return this.uploadTokenService;
}
protected KalturaUserEntryService userEntryService;
public KalturaUserEntryService getUserEntryService() {
if(this.userEntryService == null)
this.userEntryService = new KalturaUserEntryService(this);
return this.userEntryService;
}
protected KalturaUserRoleService userRoleService;
public KalturaUserRoleService getUserRoleService() {
if(this.userRoleService == null)
this.userRoleService = new KalturaUserRoleService(this);
return this.userRoleService;
}
protected KalturaUserService userService;
public KalturaUserService getUserService() {
if(this.userService == null)
this.userService = new KalturaUserService(this);
return this.userService;
}
protected KalturaWidgetService widgetService;
public KalturaWidgetService getWidgetService() {
if(this.widgetService == null)
this.widgetService = new KalturaWidgetService(this);
return this.widgetService;
}
protected KalturaMetadataService metadataService;
public KalturaMetadataService getMetadataService() {
if(this.metadataService == null)
this.metadataService = new KalturaMetadataService(this);
return this.metadataService;
}
protected KalturaMetadataProfileService metadataProfileService;
public KalturaMetadataProfileService getMetadataProfileService() {
if(this.metadataProfileService == null)
this.metadataProfileService = new KalturaMetadataProfileService(this);
return this.metadataProfileService;
}
protected KalturaDocumentsService documentsService;
public KalturaDocumentsService getDocumentsService() {
if(this.documentsService == null)
this.documentsService = new KalturaDocumentsService(this);
return this.documentsService;
}
protected KalturaVirusScanProfileService virusScanProfileService;
public KalturaVirusScanProfileService getVirusScanProfileService() {
if(this.virusScanProfileService == null)
this.virusScanProfileService = new KalturaVirusScanProfileService(this);
return this.virusScanProfileService;
}
protected KalturaDistributionProfileService distributionProfileService;
public KalturaDistributionProfileService getDistributionProfileService() {
if(this.distributionProfileService == null)
this.distributionProfileService = new KalturaDistributionProfileService(this);
return this.distributionProfileService;
}
protected KalturaEntryDistributionService entryDistributionService;
public KalturaEntryDistributionService getEntryDistributionService() {
if(this.entryDistributionService == null)
this.entryDistributionService = new KalturaEntryDistributionService(this);
return this.entryDistributionService;
}
protected KalturaDistributionProviderService distributionProviderService;
public KalturaDistributionProviderService getDistributionProviderService() {
if(this.distributionProviderService == null)
this.distributionProviderService = new KalturaDistributionProviderService(this);
return this.distributionProviderService;
}
protected KalturaGenericDistributionProviderService genericDistributionProviderService;
public KalturaGenericDistributionProviderService getGenericDistributionProviderService() {
if(this.genericDistributionProviderService == null)
this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this);
return this.genericDistributionProviderService;
}
protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService;
public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() {
if(this.genericDistributionProviderActionService == null)
this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this);
return this.genericDistributionProviderActionService;
}
protected KalturaCuePointService cuePointService;
public KalturaCuePointService getCuePointService() {
if(this.cuePointService == null)
this.cuePointService = new KalturaCuePointService(this);
return this.cuePointService;
}
protected KalturaAnnotationService annotationService;
public KalturaAnnotationService getAnnotationService() {
if(this.annotationService == null)
this.annotationService = new KalturaAnnotationService(this);
return this.annotationService;
}
protected KalturaQuizService quizService;
public KalturaQuizService getQuizService() {
if(this.quizService == null)
this.quizService = new KalturaQuizService(this);
return this.quizService;
}
protected KalturaShortLinkService shortLinkService;
public KalturaShortLinkService getShortLinkService() {
if(this.shortLinkService == null)
this.shortLinkService = new KalturaShortLinkService(this);
return this.shortLinkService;
}
protected KalturaBulkService bulkService;
public KalturaBulkService getBulkService() {
if(this.bulkService == null)
this.bulkService = new KalturaBulkService(this);
return this.bulkService;
}
protected KalturaDropFolderService dropFolderService;
public KalturaDropFolderService getDropFolderService() {
if(this.dropFolderService == null)
this.dropFolderService = new KalturaDropFolderService(this);
return this.dropFolderService;
}
protected KalturaDropFolderFileService dropFolderFileService;
public KalturaDropFolderFileService getDropFolderFileService() {
if(this.dropFolderFileService == null)
this.dropFolderFileService = new KalturaDropFolderFileService(this);
return this.dropFolderFileService;
}
protected KalturaCaptionAssetService captionAssetService;
public KalturaCaptionAssetService getCaptionAssetService() {
if(this.captionAssetService == null)
this.captionAssetService = new KalturaCaptionAssetService(this);
return this.captionAssetService;
}
protected KalturaCaptionParamsService captionParamsService;
public KalturaCaptionParamsService getCaptionParamsService() {
if(this.captionParamsService == null)
this.captionParamsService = new KalturaCaptionParamsService(this);
return this.captionParamsService;
}
protected KalturaCaptionAssetItemService captionAssetItemService;
public KalturaCaptionAssetItemService getCaptionAssetItemService() {
if(this.captionAssetItemService == null)
this.captionAssetItemService = new KalturaCaptionAssetItemService(this);
return this.captionAssetItemService;
}
protected KalturaAttachmentAssetService attachmentAssetService;
public KalturaAttachmentAssetService getAttachmentAssetService() {
if(this.attachmentAssetService == null)
this.attachmentAssetService = new KalturaAttachmentAssetService(this);
return this.attachmentAssetService;
}
protected KalturaTagService tagService;
public KalturaTagService getTagService() {
if(this.tagService == null)
this.tagService = new KalturaTagService(this);
return this.tagService;
}
protected KalturaLikeService likeService;
public KalturaLikeService getLikeService() {
if(this.likeService == null)
this.likeService = new KalturaLikeService(this);
return this.likeService;
}
protected KalturaVarConsoleService varConsoleService;
public KalturaVarConsoleService getVarConsoleService() {
if(this.varConsoleService == null)
this.varConsoleService = new KalturaVarConsoleService(this);
return this.varConsoleService;
}
protected KalturaEventNotificationTemplateService eventNotificationTemplateService;
public KalturaEventNotificationTemplateService getEventNotificationTemplateService() {
if(this.eventNotificationTemplateService == null)
this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this);
return this.eventNotificationTemplateService;
}
protected KalturaExternalMediaService externalMediaService;
public KalturaExternalMediaService getExternalMediaService() {
if(this.externalMediaService == null)
this.externalMediaService = new KalturaExternalMediaService(this);
return this.externalMediaService;
}
protected KalturaScheduleEventService scheduleEventService;
public KalturaScheduleEventService getScheduleEventService() {
if(this.scheduleEventService == null)
this.scheduleEventService = new KalturaScheduleEventService(this);
return this.scheduleEventService;
}
protected KalturaScheduleResourceService scheduleResourceService;
public KalturaScheduleResourceService getScheduleResourceService() {
if(this.scheduleResourceService == null)
this.scheduleResourceService = new KalturaScheduleResourceService(this);
return this.scheduleResourceService;
}
protected KalturaScheduleEventResourceService scheduleEventResourceService;
public KalturaScheduleEventResourceService getScheduleEventResourceService() {
if(this.scheduleEventResourceService == null)
this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this);
return this.scheduleEventResourceService;
}
protected KalturaScheduledTaskProfileService scheduledTaskProfileService;
public KalturaScheduledTaskProfileService getScheduledTaskProfileService() {
if(this.scheduledTaskProfileService == null)
this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this);
return this.scheduledTaskProfileService;
}
protected KalturaIntegrationService integrationService;
public KalturaIntegrationService getIntegrationService() {
if(this.integrationService == null)
this.integrationService = new KalturaIntegrationService(this);
return this.integrationService;
}
/**
* @param String $clientTag
*/
public void setClientTag(String clientTag){
this.clientConfiguration.put("clientTag", clientTag);
}
/**
* @return String
*/
public String getClientTag(){
if(this.clientConfiguration.containsKey("clientTag")){
return (String) this.clientConfiguration.get("clientTag");
}
return null;
}
/**
* @param String $apiVersion
*/
public void setApiVersion(String apiVersion){
this.clientConfiguration.put("apiVersion", apiVersion);
}
/**
* @return String
*/
public String getApiVersion(){
if(this.clientConfiguration.containsKey("apiVersion")){
return (String) this.clientConfiguration.get("apiVersion");
}
return null;
}
/**
* Impersonated partner id
*
* @param Integer $partnerId
*/
public void setPartnerId(Integer partnerId){
this.requestConfiguration.put("partnerId", partnerId);
}
/**
* Impersonated partner id
*
* @return Integer
*/
public Integer getPartnerId(){
if(this.requestConfiguration.containsKey("partnerId")){
return (Integer) this.requestConfiguration.get("partnerId");
}
return null;
}
/**
* Kaltura API session
*
* @param String $ks
*/
public void setKs(String ks){
this.requestConfiguration.put("ks", ks);
}
/**
* Kaltura API session
*
* @return String
*/
public String getKs(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Kaltura API session
*
* @param String $sessionId
*/
public void setSessionId(String sessionId){
this.requestConfiguration.put("ks", sessionId);
}
/**
* Kaltura API session
*
* @return String
*/
public String getSessionId(){
if(this.requestConfiguration.containsKey("ks")){
return (String) this.requestConfiguration.get("ks");
}
return null;
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @param KalturaBaseResponseProfile $responseProfile
*/
public void setResponseProfile(KalturaBaseResponseProfile responseProfile){
this.requestConfiguration.put("responseProfile", responseProfile);
}
/**
* Response profile - this attribute will be automatically unset after every API call.
*
* @return KalturaBaseResponseProfile
*/
public KalturaBaseResponseProfile getResponseProfile(){
if(this.requestConfiguration.containsKey("responseProfile")){
return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile");
}
return null;
}
/**
* Clear all volatile configuration parameters
*/
protected void resetRequest(){
this.requestConfiguration.remove("responseProfile");
}
} |
package uk.co.panaxiom.playjongo;
import static org.fest.assertions.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import play.Configuration;
import static uk.co.panaxiom.playjongo.PlayJongoTest.MapBuilder.*;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.typesafe.config.ConfigFactory;
public class PlayJongoTest {
@Test
public void testMongoUriConfig() throws Exception {
Map<String, String> config = mapBuilder("playjongo.uri", "mongodb://localhost:27017/foo").get();
final PlayJongo cut = playJongo(config, false);
assertMongoProperties(cut, "localhost", 27017, "foo");
}
@Test
public void testMongoTestUriConfig() throws Exception {
Map<String, String> config = mapBuilder("playjongo.test-uri", "mongodb://localhost:27017/bar").get();
final PlayJongo cut = playJongo(config, true);
assertMongoProperties(cut, "localhost", 27017, "bar");
}
@Test
public void testMongoWriteConcern() throws Exception {
Map<String, String> config = mapBuilder("playjongo.uri", "mongodb://localhost:27017/foo")
.with("playjongo.defaultWriteConcern", "REPLICAS_SAFE").get();
final PlayJongo cut = playJongo(config, false);
assertThat(cut.jongo.getDatabase().getWriteConcern()).isEqualTo(WriteConcern.REPLICAS_SAFE);
}
private void assertMongoProperties(final PlayJongo cut, String host, int port, String dbName) {
assertThat(cut.mongo.getServerAddressList().size()).isEqualTo(1);
final ServerAddress server0 = cut.mongo.getServerAddressList().get(0);
assertThat(server0.getHost()).isEqualTo(host);
assertThat(server0.getPort()).isEqualTo(port);
assertThat(cut.jongo.getDatabase().getName()).isEqualTo(dbName);
}
private static PlayJongo playJongo(Map<String, ? extends Object> config, boolean isTest) throws Exception {
return new PlayJongo(new Configuration(ConfigFactory.parseMap(config)), classLoader(), isTest);
}
private static ClassLoader classLoader() {
return Thread.currentThread().getContextClassLoader();
}
static class MapBuilder<K, V> {
private final Map<K, V> m = new HashMap<K, V>();
public MapBuilder(K key, V value) {
m.put(key, value);
}
public static <K, V> MapBuilder<K, V> mapBuilder(K key, V value) {
return new MapBuilder<K, V>(key, value);
}
public MapBuilder<K, V> with(K key, V value) {
m.put(key, value);
return this;
}
public Map<K, V> get() {
return m;
}
}
} |
package com.ljs.ifootballmanager.ai;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.io.CharSink;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import com.ljs.ifootballmanager.ai.formation.Formation;
import com.ljs.ifootballmanager.ai.formation.SelectionCriteria;
import com.ljs.ifootballmanager.ai.formation.score.AtPotentialScorer;
import com.ljs.ifootballmanager.ai.formation.score.DefaultScorer;
import com.ljs.ifootballmanager.ai.formation.score.FormationScorer;
import com.ljs.ifootballmanager.ai.formation.score.SecondXIScorer;
import com.ljs.ifootballmanager.ai.league.EliteFootballLeague;
import com.ljs.ifootballmanager.ai.league.Esl;
import com.ljs.ifootballmanager.ai.league.IFootballManager;
import com.ljs.ifootballmanager.ai.league.Jafl;
import com.ljs.ifootballmanager.ai.league.League;
import com.ljs.ifootballmanager.ai.league.LeagueHolder;
import com.ljs.ifootballmanager.ai.league.Ssl;
import com.ljs.ifootballmanager.ai.math.Maths;
import com.ljs.ifootballmanager.ai.player.Player;
import com.ljs.ifootballmanager.ai.player.Squad;
import com.ljs.ifootballmanager.ai.player.SquadHolder;
import com.ljs.ifootballmanager.ai.report.Report;
import com.ljs.ifootballmanager.ai.report.Reports;
import com.ljs.ifootballmanager.ai.report.SquadReport;
import com.ljs.ifootballmanager.ai.report.SquadSummaryReport;
import com.ljs.ifootballmanager.ai.report.TeamSheet;
import com.ljs.ifootballmanager.ai.selection.Bench;
import com.ljs.ifootballmanager.ai.selection.ChangePlan;
import com.ljs.ifootballmanager.ai.value.AcquisitionValue;
import com.ljs.ifootballmanager.ai.value.ReplacementLevel;
import com.ljs.ifootballmanager.ai.value.ReplacementLevelHolder;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Set;
/**
* Hello world!
*
*/
public class Main {
private static final ImmutableMap<String, League> SITES =
ImmutableMap
.<String, League>builder()
.put("EFL_TTH", EliteFootballLeague.create())
.put("ESL_WAT", Esl.create())
//.put("IFM_LIV", IFootballManager.create("liv"))
//.put("IFM_ NOR", IFootballManager.create("nor"))
//.put("IFM - DER", IFootballManager.create("der"))
//.put("IFM - Holland", IFootballManager.create("hol"))
.put("JAFL_GLI", Jafl.get())
.put("SSL_MIS", Ssl.create("mis", "msy"))
//.put("SSL - ARG", Ssl.create("arg"))
.build();
public static void main( String[] args ) throws IOException {
new Main().run();
}
public void run() throws IOException {
String site = System.getenv("ESMSAI_SITE");
Preconditions.checkNotNull(site, "ESMSAI_SITE must be provided");
run(SITES.get(site));
}
private void run(League league) throws IOException {
File baseDir = Config.get().getDataDirectory();
CharSink sink = Files.asCharSink(new File(baseDir, league.getTeam() + "ovr.txt"), Charsets.ISO_8859_1);
try (
Writer w = sink.openStream();
PrintWriter p = new PrintWriter(w); ) {
run(league, p);
p.flush();
}
}
public void run(League league, PrintWriter w) throws IOException {
System.out.println("Running for: " + league.getTeam());
LeagueHolder.set(league);
Squad squad = Squad.load(league);
SquadHolder.set(squad);
System.out.println("Selecting First XI...");
ImmutableList<Formation> firstXICandidates = Formation.select(league, squad.players(), DefaultScorer.get());
Set<Player> allFirstXI = Sets.newHashSet();
for (Formation f : firstXICandidates) {
allFirstXI.addAll(f.players());
}
Preconditions.checkState(!firstXICandidates.isEmpty());
Formation firstXI = firstXICandidates.get(0);
ReplacementLevelHolder.set(ReplacementLevel.create(squad, firstXI));
print(w, SquadReport.create(league, firstXI.getTactic(), squad.players()).sortByValue());
Integer count = 1;
Integer total = firstXICandidates.size();
for (Formation f : firstXICandidates) {
print(w, String.format("1st XI (%d/%d)", count++, total), f);
}
Set<Player> remaining = Sets.newHashSet(
Sets.difference(
ImmutableSet.copyOf(squad.players()),
ImmutableSet.copyOf(firstXI.players())));
System.out.println("Selecting At Potential XI...");
Iterable<Player> atPotentialCandidates = FluentIterable.from(squad.players()).filter(Predicates.not(Predicates.in(allFirstXI)));
Formation atPotentialXI = Formation.select(league, atPotentialCandidates, AtPotentialScorer.create(league.getPlayerPotential())).get(0);
remaining.removeAll(atPotentialXI.players());
Set<Player> reservesSquad = Sets.newHashSet();
Formation reservesXI = null;
Set<Player> allReservesXI = Sets.newHashSet();
if (league.getReserveTeam().isPresent()) {
System.out.println("Selecting Reservers XI...");
ImmutableList<Formation> reserveXICandiates = Formation.select(
league,
SelectionCriteria.create(ImmutableSet.<Player>of(), squad.reserves(league)),
DefaultScorer.get());
reservesXI = reserveXICandiates.get(0);
for (Formation f : reserveXICandiates) {
allReservesXI.addAll(f.players());
}
print(w, "Reserves XI", reservesXI);
for (Player p : allReservesXI) {
reservesSquad.add(squad.findPlayer(p.getName()));
}
}
print(w, "At Potential XI", atPotentialXI);
Set<Player> desiredSquad = Sets.newHashSet();
desiredSquad.addAll(allFirstXI);
desiredSquad.addAll(atPotentialXI.players());
/*if (secondXI != null) {
desiredSquad.addAll(secondXI.players());
}*/
Set<Player> firstSquad = Sets.newHashSet();
for (Player p : desiredSquad) {
if (p.isReserves()) {
reservesSquad.add(p);
} else {
firstSquad.add(p);
}
}
remaining.removeAll(firstSquad);
remaining.removeAll(reservesSquad);
System.out.println("Selecting Training Squad...");
Set<Player> trainingSquadCandidates = Sets.newHashSet(remaining);
while ((reservesSquad.size() < 21 || firstSquad.size() < 21) && !trainingSquadCandidates.isEmpty()) {
Player toAdd = Player.byValue(AcquisitionValue.create(league)).max(trainingSquadCandidates);
trainingSquadCandidates.remove(toAdd);
if (toAdd.isReserves() && reservesSquad.size() < 21) {
reservesSquad.add(toAdd);
remaining.remove(toAdd);
}
if (!toAdd.isReserves() && firstSquad.size() < 21) {
firstSquad.add(toAdd);
remaining.remove(toAdd);
}
}
print(w, "First XI", SquadReport.create(league, firstXI.getTactic(), allFirstXI).sortByValue());
print(
w,
String.format("First Squad (%d)", firstSquad.size()),
SquadReport
.create(
league,
firstXI.getTactic(),
FluentIterable
.from(firstSquad)
.filter(Predicates.not(Predicates.in(allFirstXI))))
.sortByValue());
if (!reservesSquad.isEmpty()) {
print(w, "Reserves XI", SquadReport.create(league, reservesXI.getTactic(), allReservesXI).sortByValue());
print(
w,
String.format("Reserves Squad (%d)", reservesSquad.size()),
SquadReport.create(league, reservesXI.getTactic(), FluentIterable.from(reservesSquad).filter(Predicates.not(Predicates.in(allReservesXI)))).sortByValue());
}
Set<Player> trainingSquad = Sets.newHashSet(Iterables.concat(firstSquad, reservesSquad));
trainingSquad.removeAll(allFirstXI);
/*if (secondXI != null) {
trainingSquad.removeAll(secondXI.players());
}*/
if (reservesXI != null) {
trainingSquad.removeAll(allReservesXI);
}
trainingSquad.removeAll(atPotentialXI.players());
print(w, "Training Squad", SquadReport.create(league, firstXI.getTactic(), trainingSquad).sortByValue());
Iterable<Player> potentials = FluentIterable
.from(atPotentialXI.players())
.filter(Predicates.not(Predicates.in(allFirstXI)))
.filter(Predicates.not(Predicates.in(allReservesXI)));
print(
w,
"Potentials",
SquadReport
.create(
league,
firstXI.getTactic(),
potentials)
.sortByValue());
print(w, "Remaining", SquadReport.create(league, firstXI.getTactic(), remaining).sortByValue());
print(
w,
SquadSummaryReport
.builder()
.squad(squad)
.firstXI(firstXI)
//.secondXI(secondXI)
.reservesXI(reservesXI)
.build());
for (String f : league.getAdditionalPlayerFiles()) {
String resource = "/rosters/" + league.getClass().getSimpleName() + f;
System.out.println("Loading:" + resource);
File sq = new File(Config.get().getDataDirectory(), resource);
Squad additional = Squad.load(league, Files.asCharSource(sq, Charsets.UTF_8));
print(w, f, SquadReport.create(league, firstXI.getTactic(), additional.players()).sortByValue());
}
File sheetFile = new File(Config.get().getDataDirectory(), league.getTeam() + "sht.txt");
CharSink sheet = Files.asCharSink(sheetFile, Charsets.UTF_8);
printSelection(w, league, "Selection", league.getTeam(), squad.forSelection(league), league.getForcedPlay(), sheet, DefaultScorer.get());
Files.copy(sheetFile, new File(Config.get().getDataDirectory(), "shts/" + sheetFile.getName()));
if (league.getReserveTeam().isPresent()) {
Set<String> forced = Sets.newHashSet();
Iterables.addAll(forced, league.getForcedPlay());
ReplacementLevel repl = ReplacementLevelHolder.get();
for (Player p : potentials) {
Integer vsRepl = Maths.round(repl.getValueVsReplacement(league.getPlayerPotential().atPotential(p)));
if (vsRepl > 0) {
forced.add(p.getName());
}
}
File rsheetFile = new File(Config.get().getDataDirectory(), league.getReserveTeam().get() + "sht.txt");
CharSink rsheet = Files.asCharSink(rsheetFile, Charsets.UTF_8);
printSelection(w, league, "Reserves Selection", league.getReserveTeam().get(), squad.forReservesSelection(league), forced, rsheet, DefaultScorer.get());
Files.copy(rsheetFile, new File(Config.get().getDataDirectory(), "shts/" + rsheetFile.getName()));
}
}
private void printSelection(PrintWriter w, League league, String title, String team, Iterable<Player> available, Iterable<String> forcedPlay, CharSink sheet, FormationScorer scorer) throws IOException {
Set<Player> forced = Sets.newHashSet();
for (Player p : available) {
Boolean isForced = Iterables.contains(forcedPlay, p.getName());
Boolean isFullFitness = SquadHolder.get().findPlayer(p.getName()).isFullFitness();
if (isForced && isFullFitness) {
forced.add(p);
}
}
System.out.print("Forced:");
for (Player p : Player.byName().sortedCopy(forced)) {
System.out.print(p.getName() + "/");
}
System.out.println();
Formation formation = Formation.selectOne(league, SelectionCriteria.create(forced, available), scorer);
ChangePlan cp =
ChangePlan.select(league, formation, available);
Bench bench =
Bench.select(formation, cp.getSubstitutes(), available);
print(w, title, SquadReport.create(league, formation.getTactic(), available));
print(w, formation, bench, cp);
Reports.print(TeamSheet.create(team, formation, cp, bench)).to(sheet);
}
private void print(PrintWriter w, String title, Report report) {
w.format("** %s **%n", title);
print(w, report);
}
private void print(PrintWriter w, Report... rs) {
for (Report r : rs) {
r.print(w);
w.println();
w.flush();
}
}
} |
package net.machinemuse.api;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class MusePlayerUtils {
public static MovingObjectPosition doCustomRayTrace(World world, EntityPlayer player, boolean collisionFlag, double reachDistance)
{
MovingObjectPosition pickedEntity = null;
Vec3 playerPosition = Vec3.createVectorHelper(player.posX, player.posY + player.getEyeHeight(), player.posZ);
Vec3 playerLook = player.getLookVec();
Vec3 playerViewOffset = Vec3.createVectorHelper(
playerPosition.xCoord + playerLook.xCoord * reachDistance,
playerPosition.yCoord + playerLook.yCoord * reachDistance,
playerPosition.zCoord + playerLook.zCoord * reachDistance);
double playerBorder = 1.1 * reachDistance;
AxisAlignedBB boxToScan = player.boundingBox.expand(playerBorder, playerBorder, playerBorder);
// AxisAlignedBB boxToScan =
// player.boundingBox.addCoord(playerLook.xCoord * reachDistance,
// playerLook.yCoord * reachDistance, playerLook.zCoord
// * reachDistance);
List entitiesHit = world.getEntitiesWithinAABBExcludingEntity(player, boxToScan);
double closestEntity = reachDistance;
for (int i = 0; i < entitiesHit.size(); ++i)
{
Entity entityHit = (Entity) entitiesHit.get(i);
if (entityHit.canBeCollidedWith())
{
float border = entityHit.getCollisionBorderSize();
AxisAlignedBB aabb = entityHit.boundingBox.expand((double) border, (double) border, (double) border);
MovingObjectPosition hitMOP = aabb.calculateIntercept(playerPosition, playerViewOffset);
if (aabb.isVecInside(playerPosition))
{
if (0.0D < closestEntity || closestEntity == 0.0D)
{
pickedEntity = new MovingObjectPosition(entityHit);
pickedEntity.hitVec = hitMOP.hitVec;
closestEntity = 0.0D;
}
}
else if (hitMOP != null)
{
double distance = playerPosition.distanceTo(hitMOP.hitVec);
if (distance < closestEntity || closestEntity == 0.0D)
{
pickedEntity = new MovingObjectPosition(entityHit);
pickedEntity.hitVec = hitMOP.hitVec;
closestEntity = distance;
}
}
}
}
// Somehow this destroys the playerPosition vector -.-
MovingObjectPosition pickedBlock = world.rayTraceBlocks_do_do(playerPosition, playerViewOffset, collisionFlag, !collisionFlag);
if (pickedBlock == null) {
return pickedEntity;
} else if (pickedEntity == null) {
return pickedBlock;
} else {
playerPosition = Vec3.createVectorHelper(player.posX, player.posY + player.getEyeHeight(), player.posZ);
double dBlock = pickedBlock.hitVec.distanceTo(playerPosition);
if (closestEntity < dBlock) {
return pickedEntity;
} else {
return pickedBlock;
}
}
// float one = 1.0F;
// float pitch = player.prevRotationPitch + (player.rotationPitch -
// player.prevRotationPitch) * one;
// float yaw = player.prevRotationYaw + (player.rotationYaw -
// player.prevRotationYaw) * one;
// double posx = player.prevPosX + (player.posX - player.prevPosX) *
// (double) one;
// double posy = player.prevPosY + (player.posY - player.prevPosY) *
// (double) one + 1.62D - (double) player.yOffset;
// double posz = player.prevPosZ + (player.posZ - player.prevPosZ) *
// (double) one;
// Vec3 posVector = World.getWorldVec3Pool().getVecFromPool(posx, posy,
// posz);
// float yawz = MathHelper.cos(-yaw * 0.017453292F - (float) Math.PI);
// float yawx = MathHelper.sin(-yaw * 0.017453292F - (float) Math.PI);
// float pitchhorizontal = -MathHelper.cos(-pitch * 0.017453292F);
// float pitchvertical = MathHelper.sin(-pitch * 0.017453292F);
// float directionx = yawx * pitchhorizontal;
// float directionz = yawz * pitchhorizontal;
// Vec3 rayToCheck = posVector.addVector((double) directionx *
// reachDistance, (double) pitchvertical * reachDistance, (double)
// directionz
// * reachDistance);
// return World.rayTraceBlocks_do_do(posVector, rayToCheck,
// collisionFlag, !collisionFlag);
}
public static void teleportEntity(EntityPlayer entityPlayer, MovingObjectPosition hitMOP) {
if (hitMOP != null && entityPlayer instanceof EntityPlayerMP) {
EntityPlayerMP player = (EntityPlayerMP) entityPlayer;
if (!player.playerNetServerHandler.connectionClosed) {
switch (hitMOP.typeOfHit) {
case ENTITY:
player.setPositionAndUpdate(hitMOP.hitVec.xCoord, hitMOP.hitVec.yCoord, hitMOP.hitVec.zCoord);
break;
case TILE:
double hitx = hitMOP.hitVec.xCoord;
double hity = hitMOP.hitVec.yCoord;
double hitz = hitMOP.hitVec.zCoord;
switch (hitMOP.sideHit) {
case 0: // Bottom
hity -= 2;
break;
case 1: // Top
// hity += 1;
break;
case 2: // East
hitz -= 0.5;
break;
case 3: // West
hitz += 0.5;
break;
case 4: // North
hitx -= 0.5;
break;
case 5: // South
hitx += 0.5;
break;
}
player.setPositionAndUpdate(hitx, hity, hitz);
break;
default:
break;
}
}
}
}
} |
package com.mcjty.rftools;
import com.mcjty.rftools.dimension.RfToolsDimensionManager;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.world.WorldEvent;
public class WorldLoadEvent {
// @SubscribeEvent
// public void loadEvent(WorldEvent.Load evt) {
// System.out.println("
// System.out.println("evt.world.provider.dimensionId = " + evt.world.provider.dimensionId);
// if (evt.world.isRemote) {
// return;
// int d = evt.world.provider.dimensionId;
// if (d == 0) {
// TeleportDestinations.clearInstance();
// RfToolsDimensionManager.clearInstance();
// DimensionStorage.clearInstance();
@SubscribeEvent
public void unloadEvent(WorldEvent.Unload evt) {
if (evt.world.isRemote) {
return;
}
int d = evt.world.provider.dimensionId;
if (d == 0) {
RfToolsDimensionManager.unregisterDimensions();
}
}
} |
package cat.ppicas.spades.map;
import java.lang.reflect.Field;
import cat.ppicas.spades.Related;
import android.content.ContentValues;
import android.database.Cursor;
public class RelatedMapper implements ValueMapper {
private Field mRelatedField;
private Field mField;
public RelatedMapper(Field field) {
Class<?> type = field.getType();
if (type != Related.class) {
throw new IllegalArgumentException("Invalid Field type");
}
mRelatedField = field;
mRelatedField.setAccessible(true);
try {
mField = Related.class.getField("mValue");
mField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
@Override
public void putContetValue(Object object, ContentValues values, String key, boolean notNull) {
try {
values.put(key, (Integer) mField.get(mRelatedField.get(object)));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void setFieldValue(Object object, Cursor cursor, int index) {
try {
mField.setInt(mRelatedField.get(object), cursor.getInt(index));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
} |
package com.microsoft.sqlserver.jdbc;
import static java.nio.charset.StandardCharsets.US_ASCII;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
/**
* Utility class for all Data Dependant Conversions (DDC).
*/
final class DDC {
/**
* Convert an Integer object to desired target user type.
*
* @param intvalue
* the value to convert.
* @param valueLength
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the type of stream required.
* @return the required object.
*/
static final Object convertIntegerToObject(int intValue,
int valueLength,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case INTEGER:
return new Integer(intValue);
case SMALLINT: // 2.21 small and tinyint returned as short
case TINYINT:
return new Short((short) intValue);
case BIT:
case BOOLEAN:
return new Boolean(0 != intValue);
case BIGINT:
return new Long(intValue);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Integer.toString(intValue));
case FLOAT:
case DOUBLE:
return new Double(intValue);
case REAL:
return new Float(intValue);
case BINARY:
return convertIntToBytes(intValue, valueLength);
default:
return Integer.toString(intValue);
}
}
/**
* Convert a Long object to desired target user type.
*
* @param longVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param baseSSType
* the base SQLServer type.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertLongToObject(long longVal,
JDBCType jdbcType,
SSType baseSSType,
StreamType streamType) {
switch (jdbcType) {
case BIGINT:
return new Long(longVal);
case INTEGER:
return new Integer((int) longVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) longVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != longVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Long.toString(longVal));
case FLOAT:
case DOUBLE:
return new Double(longVal);
case REAL:
return new Float(longVal);
case BINARY:
byte[] convertedBytes = convertLongToBytes(longVal);
int bytesToReturnLength;
byte[] bytesToReturn;
switch (baseSSType) {
case BIT:
case TINYINT:
bytesToReturnLength = 1;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case SMALLINT:
bytesToReturnLength = 2;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case INTEGER:
bytesToReturnLength = 4;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
case BIGINT:
bytesToReturnLength = 8;
bytesToReturn = new byte[bytesToReturnLength];
System.arraycopy(convertedBytes, convertedBytes.length - bytesToReturnLength, bytesToReturn, 0, bytesToReturnLength);
return bytesToReturn;
default:
return convertedBytes;
}
case VARBINARY:
switch (baseSSType) {
case BIGINT:
return new Long(longVal);
case INTEGER:
return new Integer((int) longVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) longVal);
case BIT:
return new Boolean(0 != longVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Long.toString(longVal));
case FLOAT:
return new Double(longVal);
case REAL:
return new Float(longVal);
case BINARY:
return convertLongToBytes(longVal);
default:
return Long.toString(longVal);
}
default:
return Long.toString(longVal);
}
}
/**
* Encodes an integer value to a byte array in big-endian order.
*
* @param intValue
* the integer value to encode.
* @param valueLength
* the number of bytes to encode.
* @return the byte array containing the big-endian encoded value.
*/
static final byte[] convertIntToBytes(int intValue,
int valueLength) {
byte bytes[] = new byte[valueLength];
for (int i = valueLength; i
bytes[i] = (byte) (intValue & 0xFF);
intValue >>= 8;
}
return bytes;
}
/**
* Convert a Float object to desired target user type.
*
* @param floatVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertFloatToObject(float floatVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case REAL:
return new Float(floatVal);
case INTEGER:
return new Integer((int) floatVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) floatVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != Float.compare(0.0f, floatVal));
case BIGINT:
return new Long((long) floatVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Float.toString(floatVal));
case FLOAT:
case DOUBLE:
return new Double((new Float(floatVal)).doubleValue());
case BINARY:
return convertIntToBytes(Float.floatToRawIntBits(floatVal), 4);
default:
return Float.toString(floatVal);
}
}
/**
* Encodes a long value to a byte array in big-endian order.
*
* @param longValue
* the long value to encode.
* @return the byte array containing the big-endian encoded value.
*/
static final byte[] convertLongToBytes(long longValue) {
byte bytes[] = new byte[8];
for (int i = 8; i
bytes[i] = (byte) (longValue & 0xFF);
longValue >>= 8;
}
return bytes;
}
/**
* Convert a Double object to desired target user type.
*
* @param doubleVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertDoubleToObject(double doubleVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case FLOAT:
case DOUBLE:
return new Double(doubleVal);
case REAL:
return new Float((new Double(doubleVal)).floatValue());
case INTEGER:
return new Integer((int) doubleVal);
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short((short) doubleVal);
case BIT:
case BOOLEAN:
return new Boolean(0 != Double.compare(0.0d, doubleVal));
case BIGINT:
return new Long((long) doubleVal);
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(Double.toString(doubleVal));
case BINARY:
return convertLongToBytes(Double.doubleToRawLongBits(doubleVal));
default:
return Double.toString(doubleVal);
}
}
static final byte[] convertBigDecimalToBytes(BigDecimal bigDecimalVal,
int scale) {
byte[] valueBytes;
if (bigDecimalVal == null) {
valueBytes = new byte[2];
valueBytes[0] = (byte) scale;
valueBytes[1] = 0; // data length
}
else {
boolean isNegative = (bigDecimalVal.signum() < 0);
// NOTE: Handle negative scale as a special case for JDK 1.5 and later VMs.
if (bigDecimalVal.scale() < 0)
bigDecimalVal = bigDecimalVal.setScale(0);
BigInteger bi = bigDecimalVal.unscaledValue();
if (isNegative)
bi = bi.negate();
byte[] unscaledBytes = bi.toByteArray();
valueBytes = new byte[unscaledBytes.length + 3];
int j = 0;
valueBytes[j++] = (byte) bigDecimalVal.scale();
valueBytes[j++] = (byte) (unscaledBytes.length + 1); // data length + sign
valueBytes[j++] = (byte) (isNegative ? 0 : 1); // 1 = +ve, 0 = -ve
for (int i = unscaledBytes.length - 1; i >= 0; i
valueBytes[j++] = unscaledBytes[i];
}
return valueBytes;
}
/**
* Convert a BigDecimal object to desired target user type.
*
* @param bigDecimalVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @return the required object.
*/
static final Object convertBigDecimalToObject(BigDecimal bigDecimalVal,
JDBCType jdbcType,
StreamType streamType) {
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return bigDecimalVal;
case FLOAT:
case DOUBLE:
return new Double(bigDecimalVal.doubleValue());
case REAL:
return new Float(bigDecimalVal.floatValue());
case INTEGER:
return new Integer(bigDecimalVal.intValue());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short(bigDecimalVal.shortValue());
case BIT:
case BOOLEAN:
return new Boolean(0 != bigDecimalVal.compareTo(BigDecimal.valueOf(0)));
case BIGINT:
return new Long(bigDecimalVal.longValue());
case BINARY:
return convertBigDecimalToBytes(bigDecimalVal, bigDecimalVal.scale());
default:
return bigDecimalVal.toString();
}
}
/**
* Convert a Money object to desired target user type.
*
* @param bigDecimalVal
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param streamType
* the stream type.
* @param numberOfBytes
* the number of bytes to convert
* @return the required object.
*/
static final Object convertMoneyToObject(BigDecimal bigDecimalVal,
JDBCType jdbcType,
StreamType streamType,
int numberOfBytes) {
switch (jdbcType) {
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return bigDecimalVal;
case FLOAT:
case DOUBLE:
return new Double(bigDecimalVal.doubleValue());
case REAL:
return new Float(bigDecimalVal.floatValue());
case INTEGER:
return new Integer(bigDecimalVal.intValue());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return new Short(bigDecimalVal.shortValue());
case BIT:
case BOOLEAN:
return new Boolean(0 != bigDecimalVal.compareTo(BigDecimal.valueOf(0)));
case BIGINT:
return new Long(bigDecimalVal.longValue());
case BINARY:
return convertToBytes(bigDecimalVal, bigDecimalVal.scale(), numberOfBytes);
default:
return bigDecimalVal.toString();
}
}
// converts big decimal to money and smallmoney
private static byte[] convertToBytes(BigDecimal value,
int scale,
int numBytes) {
boolean isNeg = value.signum() < 0;
value = value.setScale(scale);
BigInteger bigInt = value.unscaledValue();
byte[] unscaledBytes = bigInt.toByteArray();
byte[] ret = new byte[numBytes];
if (unscaledBytes.length < numBytes) {
for (int i = 0; i < numBytes - unscaledBytes.length; ++i) {
ret[i] = (byte) (isNeg ? -1 : 0);
}
}
int offset = numBytes - unscaledBytes.length;
for (int i = offset; i < numBytes; ++i) {
ret[i] = unscaledBytes[i - offset];
}
return ret;
}
/**
* Convert a byte array to desired target user type.
*
* @param bytesValue
* the value to convert.
* @param jdbcType
* the jdbc type required.
* @param baseTypeInfo
* the type information associated with bytesValue.
* @return the required object.
* @throws SQLServerException
* when an error occurs.
*/
static final Object convertBytesToObject(byte[] bytesValue,
JDBCType jdbcType,
TypeInfo baseTypeInfo) throws SQLServerException {
switch (jdbcType) {
case CHAR:
String str = Util.bytesToHexString(bytesValue, bytesValue.length);
if ((SSType.BINARY == baseTypeInfo.getSSType()) && (str.length() < (baseTypeInfo.getPrecision() * 2))) {
StringBuilder strbuf = new StringBuilder(str);
while (strbuf.length() < (baseTypeInfo.getPrecision() * 2)) {
strbuf.append('0');
}
return strbuf.toString();
}
return str;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
if ((SSType.BINARY == baseTypeInfo.getSSType()) && (bytesValue.length < baseTypeInfo.getPrecision())) {
byte[] newBytes = new byte[baseTypeInfo.getPrecision()];
System.arraycopy(bytesValue, 0, newBytes, 0, bytesValue.length);
return newBytes;
}
return bytesValue;
default:
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unsupportedConversionFromTo"));
throw new SQLServerException(form.format(new Object[] {baseTypeInfo.getSSType().name(), jdbcType}), null, 0, null);
}
}
/**
* Convert a String object to desired target user type.
*
* @param stringVal
* the value to convert.
* @param charset
* the character set.
* @param jdbcType
* the jdbc type required.
* @return the required object.
*/
static final Object convertStringToObject(String stringVal,
Charset charset,
JDBCType jdbcType,
StreamType streamType) throws UnsupportedEncodingException, IllegalArgumentException {
switch (jdbcType) {
// Convert String to Numeric types.
case DECIMAL:
case NUMERIC:
case MONEY:
case SMALLMONEY:
return new BigDecimal(stringVal.trim());
case FLOAT:
case DOUBLE:
return Double.valueOf(stringVal.trim());
case REAL:
return Float.valueOf(stringVal.trim());
case INTEGER:
return Integer.valueOf(stringVal.trim());
case SMALLINT: // small and tinyint returned as short
case TINYINT:
return Short.valueOf(stringVal.trim());
case BIT:
case BOOLEAN:
String trimmedString = stringVal.trim();
return (1 == trimmedString.length()) ? Boolean.valueOf('1' == trimmedString.charAt(0)) : Boolean.valueOf(trimmedString);
case BIGINT:
return Long.valueOf(stringVal.trim());
// Convert String to Temporal types.
case TIMESTAMP:
return java.sql.Timestamp.valueOf(stringVal.trim());
case DATE:
return java.sql.Date.valueOf(getDatePart(stringVal.trim()));
case TIME: {
// Accepted character formats for conversion to java.sql.Time are:
// hh:mm:ss[.nnnnnnnnn]
// YYYY-MM-DD hh:mm:ss[.nnnnnnnnn]
// To handle either of these formats:
// 1) Normalize and parse as a Timestamp
// 2) Round fractional seconds up to the nearest millisecond (max resolution of java.sql.Time)
// 3) Renormalize (as rounding may have changed the date) to a java.sql.Time
java.sql.Timestamp ts = java.sql.Timestamp.valueOf(TDS.BASE_DATE_1970 + " " + getTimePart(stringVal.trim()));
GregorianCalendar cal = new GregorianCalendar(Locale.US);
cal.clear();
cal.setTimeInMillis(ts.getTime());
if (ts.getNanos() % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);
cal.set(TDS.BASE_YEAR_1970, Calendar.JANUARY, 1);
return new java.sql.Time(cal.getTimeInMillis());
}
case BINARY:
return stringVal.getBytes(charset);
default:
// For everything else, just return either a string or appropriate stream.
switch (streamType) {
case CHARACTER:
return new StringReader(stringVal);
case ASCII:
return new ByteArrayInputStream(stringVal.getBytes(US_ASCII));
case BINARY:
return new ByteArrayInputStream(stringVal.getBytes());
default:
return stringVal;
}
}
}
static final Object convertStreamToObject(BaseInputStream stream,
TypeInfo typeInfo,
JDBCType jdbcType,
InputStreamGetterArgs getterArgs) throws SQLServerException {
// Need to handle the simple case of a null value here, as it is not done
// outside this function.
if (null == stream)
return null;
assert null != typeInfo;
assert null != getterArgs;
SSType ssType = typeInfo.getSSType();
try {
switch (jdbcType) {
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
default:
// Binary streams to character types:
// - Direct conversion to ASCII stream
// - Convert as hexized value to other character types
if (SSType.BINARY == ssType || SSType.VARBINARY == ssType || SSType.VARBINARYMAX == ssType || SSType.TIMESTAMP == ssType
|| SSType.IMAGE == ssType || SSType.UDT == ssType) {
if (StreamType.ASCII == getterArgs.streamType) {
return stream;
}
else {
assert StreamType.CHARACTER == getterArgs.streamType || StreamType.NONE == getterArgs.streamType;
byte[] byteValue = stream.getBytes();
if (JDBCType.GUID == jdbcType) {
return Util.readGUID(byteValue);
}
else {
String hexString = Util.bytesToHexString(byteValue, byteValue.length);
if (StreamType.NONE == getterArgs.streamType)
return hexString;
return new StringReader(hexString);
}
}
}
// Handle streams converting to ASCII
if (StreamType.ASCII == getterArgs.streamType) {
// Fast path for SBCS data that converts directly/easily to ASCII
if (typeInfo.supportsFastAsciiConversion())
return new AsciiFilteredInputStream(stream);
// Slightly less fast path for MBCS data that converts directly/easily to ASCII
if (getterArgs.isAdaptive) {
return AsciiFilteredUnicodeInputStream.MakeAsciiFilteredUnicodeInputStream(stream,
new BufferedReader(new InputStreamReader(stream, typeInfo.getCharset())));
}
else {
return new ByteArrayInputStream((new String(stream.getBytes(), typeInfo.getCharset())).getBytes(US_ASCII));
}
}
else if (StreamType.CHARACTER == getterArgs.streamType || StreamType.NCHARACTER == getterArgs.streamType) {
if (getterArgs.isAdaptive)
return new BufferedReader(new InputStreamReader(stream, typeInfo.getCharset()));
else
return new StringReader(new String(stream.getBytes(), typeInfo.getCharset()));
}
// None of the special/fast textual conversion cases applied. Just go the normal route of converting via String.
return convertStringToObject(new String(stream.getBytes(), typeInfo.getCharset()), typeInfo.getCharset(), jdbcType,
getterArgs.streamType);
case CLOB:
return new SQLServerClob(stream, typeInfo);
case NCLOB:
return new SQLServerNClob(stream, typeInfo);
case SQLXML:
return new SQLServerSQLXML(stream, getterArgs, typeInfo);
case BINARY:
case VARBINARY:
case LONGVARBINARY:
case BLOB:
// Where allowed, streams convert directly to binary representation
if (StreamType.BINARY == getterArgs.streamType)
return stream;
if (JDBCType.BLOB == jdbcType)
return new SQLServerBlob(stream);
return stream.getBytes();
}
}
// Conversion can throw either of these exceptions:
// UnsupportedEncodingException (binary conversions)
// Catch them and translate them to a SQLException so that we don't propagate an unexpected exception
// type all the way up to the app, which may not catch it either...
catch (IllegalArgumentException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {typeInfo.getSSType(), jdbcType}), null, 0, e);
}
catch (UnsupportedEncodingException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {typeInfo.getSSType(), jdbcType}), null, 0, e);
}
}
// Returns date portion of string.
// Expects one of "<date>" or "<date><space><time>".
private static String getDatePart(String s) {
int sp = s.indexOf(' ');
if (-1 == sp)
return s;
return s.substring(0, sp);
}
// Returns time portion of string.
// Expects one of "<time>" or "<date><space><time>".
private static String getTimePart(String s) {
int sp = s.indexOf(' ');
if (-1 == sp)
return s;
return s.substring(sp + 1);
}
// Formats nanoseconds as a String of the form ".nnnnnnn...." where the number
// of digits is equal to the scale. Returns the empty string for scale = 0;
private static String fractionalSecondsString(long subSecondNanos,
int scale) {
assert 0 <= subSecondNanos && subSecondNanos < Nanos.PER_SECOND;
assert 0 <= scale && scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
// Fast path for 0 scale (avoids creation of two BigDecimal objects and
// two Strings when the answer is going to be "" anyway...)
if (0 == scale)
return "";
return java.math.BigDecimal.valueOf(subSecondNanos % Nanos.PER_SECOND, 9).setScale(scale).toPlainString().substring(1);
}
/**
* Convert a SQL Server temporal value to the desired Java object type.
*
* Accepted SQL server data types:
*
* DATETIME SMALLDATETIME DATE TIME DATETIME2 DATETIMEOFFSET
*
* Converts to Java types (determined by JDBC type):
*
* java.sql.Date java.sql.Time java.sql.Timestamp java.lang.String
*
* @param jdbcType
* the JDBC type indicating the desired conversion
*
* @param ssType
* the SQL Server data type of the value being converted
*
* @param timeZoneCalendar
* (optional) a Calendar representing the time zone to associate with the resulting converted value. For DATETIMEOFFSET, this parameter
* represents the time zone associated with the value. Null means to use the default VM time zone.
*
* @param daysSinceBaseDate
* The date part of the value, expressed as a number of days since the base date for the specified SQL Server data type. For DATETIME
* and SMALLDATETIME, the base date is 1/1/1900. For other types, the base date is 1/1/0001. The number of days assumes Gregorian leap
* year behavior over the entire supported range of values. For TIME values, this parameter must be the number of days between 1/1/0001
* and 1/1/1900 when converting to java.sql.Timestamp.
*
* @param ticksSinceMidnight
* The time part of the value, expressed as a number of time units (ticks) since midnight. For DATETIME and SMALLDATETIME SQL Server
* data types, time units are in milliseconds. For other types, time units are in nanoseconds. For DATE values, this parameter must be
* 0.
*
* @param fractionalSecondsScale
* the desired fractional seconds scale to use when formatting the value as a String. Ignored for conversions to Java types other than
* String.
*
* @return a Java object of the desired type.
*/
static final Object convertTemporalToObject(JDBCType jdbcType,
SSType ssType,
Calendar timeZoneCalendar,
int daysSinceBaseDate,
long ticksSinceMidnight,
int fractionalSecondsScale) {
// Determine the local time zone to associate with the value. Use the default VM
// time zone if no time zone is otherwise specified.
TimeZone localTimeZone = (null != timeZoneCalendar) ? timeZoneCalendar.getTimeZone() : TimeZone.getDefault();
// Assumed time zone associated with the date and time parts of the value.
// For DATETIMEOFFSET, the date and time parts are assumed to be relative to UTC.
// For other data types, the date and time parts are assumed to be relative to the local time zone.
TimeZone componentTimeZone = (SSType.DATETIMEOFFSET == ssType) ? UTC.timeZone : localTimeZone;
int subSecondNanos;
// The date and time parts assume a Gregorian calendar with Gregorian leap year behavior
// over the entire supported range of values. Create and initialize such a calendar to
// use to interpret the date and time parts in their associated time zone.
GregorianCalendar cal = new GregorianCalendar(componentTimeZone, Locale.US);
// Allow overflow in "smaller" fields (such as MILLISECOND and DAY_OF_YEAR) to update
// "larger" fields (such as HOUR, MINUTE, SECOND, and YEAR, MONTH, DATE).
cal.setLenient(true);
// Clear old state from the calendar. Newly created calendars are always initialized to the
// current date and time.
cal.clear();
// Set the calendar value according to the specified local time zone and constituent
// date (days since base date) and time (ticks since midnight) parts.
switch (ssType) {
case TIME: {
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to standard Gregorian leap year rules, which are sufficient
// for all TIME values.
// When initializing the value, set the date component to 1/1/1900 to facilitate conversion
// to String and java.sql.Timestamp. Note that conversion to java.sql.Time, which is
// the expected majority conversion, resets the date to 1/1/1970. It is not measurably
// faster to conditionalize the date on the target data type to avoid resetting it.
// Ticks are in nanoseconds.
cal.set(TDS.BASE_YEAR_1900, Calendar.JANUARY, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
subSecondNanos = (int) (ticksSinceMidnight % Nanos.PER_SECOND);
break;
}
case DATE:
case DATETIME2:
case DATETIMEOFFSET: {
// For dates after the standard Julian-Gregorian calendar change date,
// the calendar value can be accurately set using a straightforward
// (and measurably better performing) assignment.
// This optimized path is not functionally correct for dates earlier
// than the standard Gregorian change date.
if (daysSinceBaseDate >= GregorianChange.DAYS_SINCE_BASE_DATE_HINT) {
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to pure Gregorian calendar rules.
// Ticks are in nanoseconds.
cal.set(1, Calendar.JANUARY, 1 + daysSinceBaseDate + GregorianChange.EXTRA_DAYS_TO_BE_ADDED, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
}
// For dates before the standard change date, it is necessary to rationalize
// the difference between SQL Server (pure Gregorian) calendar behavior and
// Java (standard Gregorian) calendar behavior. Rationalization ensures that
// the "wall calendar" representation of the value on both server and client
// are the same, taking into account the difference in the respective calendars'
// leap year rules.
// This code path is functionally correct, but less performant, than the
// optimized path above for dates after the standard Gregorian change date.
else {
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to pure Gregorian calendar rules.
// Ticks are in nanoseconds.
cal.set(1, Calendar.JANUARY, 1 + daysSinceBaseDate, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) (ticksSinceMidnight / Nanos.PER_MILLISECOND));
// Recompute the calendar's internal UTC milliseconds value according to the historically
// standard Gregorian cutover date, which is needed for constructing java.sql.Time,
// java.sql.Date, and java.sql.Timestamp values from UTC milliseconds.
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
cal.setGregorianChange(GregorianChange.STANDARD_CHANGE_DATE);
cal.set(year, month, date, hour, minute, second);
cal.set(Calendar.MILLISECOND, millis);
}
// For DATETIMEOFFSET values, recompute the calendar's UTC milliseconds value according
// to the specified local time zone (the time zone associated with the offset part
// of the DATETIMEOFFSET value).
// Optimization: Skip this step if there is no time zone difference
// (i.e. the time zone of the DATETIMEOFFSET value is UTC).
if (SSType.DATETIMEOFFSET == ssType && !componentTimeZone.hasSameRules(localTimeZone)) {
GregorianCalendar localCalendar = new GregorianCalendar(localTimeZone, Locale.US);
localCalendar.clear();
localCalendar.setTimeInMillis(cal.getTimeInMillis());
cal = localCalendar;
}
subSecondNanos = (int) (ticksSinceMidnight % Nanos.PER_SECOND);
break;
}
case DATETIME: // and SMALLDATETIME
{
// For Yukon (and earlier) data types DATETIME and SMALLDATETIME, there is no need to
// change the Gregorian cutover because the earliest representable value (1/1/1753)
// is after the historically standard cutover date (10/15/1582).
// Set the calendar to the specified value. Lenient calendar behavior will update
// individual fields according to standard Gregorian leap year rules, which are sufficient
// for all values in the supported DATETIME range.
// Ticks are in milliseconds.
cal.set(TDS.BASE_YEAR_1900, Calendar.JANUARY, 1 + daysSinceBaseDate, 0, 0, 0);
cal.set(Calendar.MILLISECOND, (int) ticksSinceMidnight);
subSecondNanos = (int) ((ticksSinceMidnight * Nanos.PER_MILLISECOND) % Nanos.PER_SECOND);
break;
}
default:
throw new AssertionError("Unexpected SSType: " + ssType);
}
int localMillisOffset;
if (null == timeZoneCalendar) {
TimeZone tz = TimeZone.getDefault();
GregorianCalendar _cal = new GregorianCalendar(componentTimeZone, Locale.US);
_cal.setLenient(true);
_cal.clear();
localMillisOffset = tz.getOffset(_cal.getTimeInMillis());
}
else {
localMillisOffset = timeZoneCalendar.get(Calendar.ZONE_OFFSET);
}
// Convert the calendar value (in local time) to the desired Java object type.
switch (jdbcType.category) {
case BINARY: {
switch (ssType) {
case DATE: {
// Per JDBC spec, the time part of java.sql.Date values is initialized to midnight
// in the specified local time zone.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new java.sql.Date(cal.getTimeInMillis());
}
case DATETIME:
case DATETIME2: {
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return ts;
}
case DATETIMEOFFSET: {
// Per driver spec, conversion to DateTimeOffset is only supported from
// DATETIMEOFFSET SQL Server values.
assert SSType.DATETIMEOFFSET == ssType;
// For DATETIMEOFFSET SQL Server values, the time zone offset is in minutes.
// The offset from Java TimeZone objects is in milliseconds. Because we
// are only dealing with DATETIMEOFFSET SQL Server values here, we can assume
// that the offset is precise only to the minute and that rescaling from
// milliseconds precision results in no loss of precision.
assert 0 == localMillisOffset % (60 * 1000);
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return microsoft.sql.DateTimeOffset.valueOf(ts, localMillisOffset / (60 * 1000));
}
case TIME: {
// Per driver spec, values of sql server data types types (including TIME) which have greater
// than millisecond precision are rounded, not truncated, to the nearest millisecond when
// converting to java.sql.Time. Since the milliseconds value in the calendar is truncated,
// round it now.
if (subSecondNanos % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);
// Per JDBC spec, the date part of java.sql.Time values is initialized to 1/1/1970
// in the specified local time zone. This must be done after rounding (above) to
// prevent rounding values within nanoseconds of the next day from ending up normalized
// to 1/2/1970 instead...
cal.set(TDS.BASE_YEAR_1970, Calendar.JANUARY, 1);
return new java.sql.Time(cal.getTimeInMillis());
}
default:
throw new AssertionError("Unexpected SSType: " + ssType);
}
}
case DATE: {
// Per JDBC spec, the time part of java.sql.Date values is initialized to midnight
// in the specified local time zone.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new java.sql.Date(cal.getTimeInMillis());
}
case TIME: {
// Per driver spec, values of sql server data types types (including TIME) which have greater
// than millisecond precision are rounded, not truncated, to the nearest millisecond when
// converting to java.sql.Time. Since the milliseconds value in the calendar is truncated,
// round it now.
if (subSecondNanos % Nanos.PER_MILLISECOND >= Nanos.PER_MILLISECOND / 2)
cal.add(Calendar.MILLISECOND, 1);
// Per JDBC spec, the date part of java.sql.Time values is initialized to 1/1/1970
// in the specified local time zone. This must be done after rounding (above) to
// prevent rounding values within nanoseconds of the next day from ending up normalized
// to 1/2/1970 instead...
cal.set(TDS.BASE_YEAR_1970, Calendar.JANUARY, 1);
return new java.sql.Time(cal.getTimeInMillis());
}
case TIMESTAMP: {
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return ts;
}
case DATETIMEOFFSET: {
// Per driver spec, conversion to DateTimeOffset is only supported from
// DATETIMEOFFSET SQL Server values.
assert SSType.DATETIMEOFFSET == ssType;
// For DATETIMEOFFSET SQL Server values, the time zone offset is in minutes.
// The offset from Java TimeZone objects is in milliseconds. Because we
// are only dealing with DATETIMEOFFSET SQL Server values here, we can assume
// that the offset is precise only to the minute and that rescaling from
// milliseconds precision results in no loss of precision.
assert 0 == localMillisOffset % (60 * 1000);
java.sql.Timestamp ts = new java.sql.Timestamp(cal.getTimeInMillis());
ts.setNanos(subSecondNanos);
return microsoft.sql.DateTimeOffset.valueOf(ts, localMillisOffset / (60 * 1000));
}
case CHARACTER: {
switch (ssType) {
case DATE: {
return String.format(Locale.US, "%1$tF", // yyyy-mm-dd
cal);
}
case TIME: {
return String.format(Locale.US, "%1$tT%2$s", // hh:mm:ss[.nnnnnnn]
cal, fractionalSecondsString(subSecondNanos, fractionalSecondsScale));
}
case DATETIME2: {
return String.format(Locale.US, "%1$tF %1$tT%2$s", // yyyy-mm-dd hh:mm:ss[.nnnnnnn]
cal, fractionalSecondsString(subSecondNanos, fractionalSecondsScale));
}
case DATETIMEOFFSET: {
// The offset part of a DATETIMEOFFSET value is precise only to the minute,
// but TimeZone returns the raw offset as precise to the millisecond.
assert 0 == localMillisOffset % (60 * 1000);
int unsignedMinutesOffset = Math.abs(localMillisOffset / (60 * 1000));
return String.format(Locale.US, "%1$tF %1$tT%2$s %3$c%4$02d:%5$02d", // yyyy-mm-dd hh:mm:ss[.nnnnnnn] [+|-]hh:mm
cal, fractionalSecondsString(subSecondNanos, fractionalSecondsScale), (localMillisOffset >= 0) ? '+' : '-',
unsignedMinutesOffset / 60, unsignedMinutesOffset % 60);
}
case DATETIME: // and SMALLDATETIME
{
return (new java.sql.Timestamp(cal.getTimeInMillis())).toString();
}
default:
throw new AssertionError("Unexpected SSType: " + ssType);
}
}
default:
throw new AssertionError("Unexpected JDBCType: " + jdbcType);
}
}
/**
* Returns the number of days elapsed from January 1 of the specified baseYear (Gregorian) to the specified dayOfYear in the specified year,
* assuming pure Gregorian calendar rules (no Julian to Gregorian cutover).
*/
static int daysSinceBaseDate(int year,
int dayOfYear,
int baseYear) {
assert year >= 1;
assert baseYear >= 1;
assert dayOfYear >= 1;
return (dayOfYear - 1) + // Days into the current year
(year - baseYear) * TDS.DAYS_PER_YEAR + // plus whole years (in days) ...
leapDaysBeforeYear(year) - // ... plus leap days
leapDaysBeforeYear(baseYear);
}
/**
* Returns the number of leap days that have occurred between January 1, 1AD and January 1 of the specified year, assuming a Proleptic Gregorian
* Calendar
*/
private static int leapDaysBeforeYear(int year) {
assert year >= 1;
// On leap years, the US Naval Observatory says:
// "According to the Gregorian calendar, which is the civil calendar
// in use today, years evenly divisible by 4 are leap years, with
// the exception of centurial years that are not evenly divisible
// by 400. Therefore, the years 1700, 1800, 1900 and 2100 are not
// leap years, but 1600, 2000, and 2400 are leap years."
// So, using year 1AD as a base, we can compute the number of leap
// days between 1AD and the specified year as follows:
return (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
}
// Maximum allowed RPC decimal value (raw integer value with scale removed).
// This limits the value to 38 digits of precision for SQL.
private final static BigInteger maxRPCDecimalValue = new BigInteger("99999999999999999999999999999999999999");
// Returns true if input bigDecimalValue exceeds allowable
// TDS wire format precision or scale for DECIMAL TDS token.
static final boolean exceedsMaxRPCDecimalPrecisionOrScale(BigDecimal bigDecimalValue) {
if (null == bigDecimalValue)
return false;
// Maximum scale allowed is same as maximum precision allowed.
if (bigDecimalValue.scale() > SQLServerConnection.maxDecimalPrecision)
return true;
// Convert to unscaled integer value, then compare with maxRPCDecimalValue.
// NOTE: Handle negative scale as a special case for JDK 1.5 and later VMs.
BigInteger bi = (bigDecimalValue.scale() < 0) ? bigDecimalValue.setScale(0).unscaledValue() : bigDecimalValue.unscaledValue();
if (bigDecimalValue.signum() < 0)
bi = bi.negate();
return (bi.compareTo(maxRPCDecimalValue) > 0);
}
// Converts a Reader to a String.
static String convertReaderToString(Reader reader,
int readerLength) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == readerLength || readerLength >= 0;
// Optimize simple cases.
if (null == reader)
return null;
if (0 == readerLength)
return "";
try {
// Set up a StringBuilder big enough to hold the Reader value. If we weren't told the size of
// the value then start with a "reasonable" guess StringBuilder size. If necessary, the StringBuilder
// will grow automatically to accomodate arbitrary amounts of data.
StringBuilder sb = new StringBuilder((DataTypes.UNKNOWN_STREAM_LENGTH != readerLength) ? readerLength : 4000);
// Set up the buffer into which blocks of characters are read from the Reader. This buffer
// should be no larger than the Reader value's size (if known). For known very large values,
// limit the buffer's size to reduce this function's memory requirements.
char charArray[] = new char[(DataTypes.UNKNOWN_STREAM_LENGTH != readerLength && readerLength < 4000) ? readerLength : 4000];
// Loop and read characters, chunk into StringBuilder until EOS.
int readChars;
while ((readChars = reader.read(charArray, 0, charArray.length)) > 0) {
// Check for invalid bytesRead returned from InputStream.read
if (readChars > charArray.length) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true);
}
sb.append(charArray, 0, readChars);
}
return sb.toString();
}
catch (IOException ioEx) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {ioEx.toString()};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true);
}
// Unreachable code, but needed for compiler.
return null;
}
}
/**
* InputStream implementation that wraps a contained InputStream, filtering it for 7-bit ASCII characters.
*
* The wrapped input stream must supply byte values from a SBCS character set whose first 128 entries match the 7-bit US-ASCII character set. Values
* that lie outside of the 7-bit US-ASCII range are translated to the '?' character.
*/
final class AsciiFilteredInputStream extends InputStream {
private final InputStream containedStream;
private final static byte[] ASCII_FILTER;
static {
ASCII_FILTER = new byte[256];
// First 128 entries map ASCII values in to ASCII values out
for (int i = 0; i < 128; i++)
ASCII_FILTER[i] = (byte) i;
// Remaining 128 filter entries map other values to '?'
for (int i = 128; i < 256; i++)
ASCII_FILTER[i] = (byte) '?';
}
AsciiFilteredInputStream(BaseInputStream containedStream) throws SQLServerException {
if (BaseInputStream.logger.isLoggable(java.util.logging.Level.FINER))
BaseInputStream.logger.finer(containedStream.toString() + " wrapping in AsciiFilteredInputStream");
this.containedStream = containedStream;
}
public void close() throws IOException {
containedStream.close();
}
public long skip(long n) throws IOException {
return containedStream.skip(n);
}
public int available() throws IOException {
return containedStream.available();
}
public int read() throws IOException {
int value = containedStream.read();
if (value >= 0 && value <= 255)
return ASCII_FILTER[value];
return value;
}
public int read(byte[] b) throws IOException {
int bytesRead = containedStream.read(b);
if (bytesRead > 0) {
assert bytesRead <= b.length;
for (int i = 0; i < bytesRead; i++)
b[i] = ASCII_FILTER[b[i] & 0xFF];
}
return bytesRead;
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
int bytesRead = containedStream.read(b, offset, maxBytes);
if (bytesRead > 0) {
assert offset + bytesRead <= b.length;
for (int i = 0; i < bytesRead; i++)
b[offset + i] = ASCII_FILTER[b[offset + i] & 0xFF];
}
return bytesRead;
}
public boolean markSupported() {
return containedStream.markSupported();
}
public void mark(int readLimit) {
containedStream.mark(readLimit);
}
public void reset() throws IOException {
containedStream.reset();
}
}
/**
* InputStream implementation that wraps a contained InputStream, filtering it for 7-bit ASCII characters from UNICODE.
*
* The wrapped input stream must supply byte values from a UNICODE character set.
*
*/
final class AsciiFilteredUnicodeInputStream extends InputStream {
private final Reader containedReader;
private final Charset asciiCharSet;
static AsciiFilteredUnicodeInputStream MakeAsciiFilteredUnicodeInputStream(BaseInputStream strm,
Reader rd) throws SQLServerException {
if (BaseInputStream.logger.isLoggable(java.util.logging.Level.FINER))
BaseInputStream.logger.finer(strm.toString() + " wrapping in AsciiFilteredInputStream");
return new AsciiFilteredUnicodeInputStream(rd);
}
// Note the Reader provided should support mark, reset
private AsciiFilteredUnicodeInputStream(Reader rd) throws SQLServerException {
containedReader = rd;
asciiCharSet = US_ASCII;
}
public void close() throws IOException {
containedReader.close();
}
public long skip(long n) throws IOException {
return containedReader.skip(n);
}
public int available() throws IOException {
// from the JDBC spec
// Note: A stream may return 0 when the method InputStream.available is called whether there is data available or not.
// Reader does not give us available data.
return 0;
}
private final byte[] bSingleByte = new byte[1];
public int read() throws IOException {
int bytesRead = read(bSingleByte);
return (-1 == bytesRead) ? -1 : (bSingleByte[0] & 0xFF);
}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
char tempBufferToHoldCharDataForConversion[] = new char[maxBytes];
int charsRead = containedReader.read(tempBufferToHoldCharDataForConversion);
if (charsRead > 0) {
if (charsRead < maxBytes)
maxBytes = charsRead;
ByteBuffer encodedBuff = asciiCharSet.encode(CharBuffer.wrap(tempBufferToHoldCharDataForConversion));
encodedBuff.get(b, offset, maxBytes);
}
return charsRead;
}
public boolean markSupported() {
return containedReader.markSupported();
}
public void mark(int readLimit) {
try {
containedReader.mark(readLimit);
}
catch (IOException e) {
// unfortunately inputstream mark does not throw an exception so we have to eat any exception from the reader here
// likely to be a bug in the original InputStream spec.
return;
}
}
public void reset() throws IOException {
containedReader.reset();
}
}
// Helper class to hold + pass around stream/reader setter arguments.
final class StreamSetterArgs {
private long length;
final long getLength() {
return length;
}
final void setLength(long newLength) {
// We only expect length to be changed from an initial unknown value (-1)
// to an actual length (+ve or 0).
assert DataTypes.UNKNOWN_STREAM_LENGTH == length;
assert newLength >= 0;
length = newLength;
}
final StreamType streamType;
StreamSetterArgs(StreamType streamType,
long length) {
this.streamType = streamType;
this.length = length;
}
}
// Helper class to hold + pass around InputStream getter arguments.
final class InputStreamGetterArgs {
final StreamType streamType;
final boolean isAdaptive;
final boolean isStreaming;
final String logContext;
static final InputStreamGetterArgs defaultArgs = new InputStreamGetterArgs(StreamType.NONE, false, false, "");
static final InputStreamGetterArgs getDefaultArgs() {
return defaultArgs;
}
InputStreamGetterArgs(StreamType streamType,
boolean isAdaptive,
boolean isStreaming,
String logContext) {
this.streamType = streamType;
this.isAdaptive = isAdaptive;
this.isStreaming = isStreaming;
this.logContext = logContext;
}
} |
package com.mnt.base.evaluator;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
* <pre>
* providing the method to evaluate the simple expression
*
* 1. check the expression match
*
* e.g. [M3] { k = 1 and M2.k > 3 }
*
* 2. retrieve the value
* e.g. M3.k|int or k|int
*
* </pre>
*
* @author Peng Peng
*
*/
public interface Evaluator {
public static final String FIRST_LAYER_MAP = "M1";
public static final String SECOND_LAYER_MAP = "M2";
public static final String THIRD_LAYER_MAP = "M3";
public static final String THIRD_LAYER_EXT_MAP = "M31"; // for msgpack data process the activity
public static final String FORTH_LAYER_MAP = "M4";
String EXPRESSION_MATCH_REGEX_STR = "\\[(M.*)\\](\\s*\\{(.*)\\})?";
Pattern EXPRESSION_MATCH_REGEX = Pattern.compile(EXPRESSION_MATCH_REGEX_STR);
String NUMBER_REGEX = "^(\\-|\\+)?[0-9]+(\\.[0-9]*)?$";
String BOOLEAN_REGEX = "^(true|false)$";
char COMMA = ',';
String PERIOD_REGEX = "\\.";
String COMMA_REGEX = "\\,";
String COLON_REGEX = ":";
String SEMICOLON_REGEX = ";";
String STR_POUND = "
String STR_EXCLAMATORY_MARK = "!";
String KEY_DEFAULT = "default";
char SQL_EXPRESSION_START = '(';
char SQL_EXPRESSION_END = ')';
String SQL_EXPRESSION_ENDSTR = String.valueOf(SQL_EXPRESSION_END);
String SQL_EXPRESSION_SPACE = " ";
String SQL_EXPRESSION_AND = "AND";
String SQL_EXPRESSION_OR = "OR";
String SQL_EXPRESSION_NOT = "NOT";
String SQL_EXPRESSION_EQ = "=";
String SQL_EXPRESSION_EQ2 = "==";
String SQL_EXPRESSION_NE = "!=";
String SQL_EXPRESSION_LT = "<";
String SQL_EXPRESSION_LE = "<=";
String SQL_EXPRESSION_GT = ">";
String SQL_EXPRESSION_GE = ">=";
String SQL_EXPRESSION_IN = "IN";
String SQL_EXPRESSION_INS = "INS";
String SQL_EXPRESSION_NOT_IN = "NOT IN";
String SQL_EXPRESSION_NOT_INS = "NOT INS";
char SQL_NOT_FLAG_CHAR = '!';
String SQL_NOT_FLAG = String.valueOf(SQL_NOT_FLAG_CHAR);
int SQL_EXPRESSION_EQ_N = 101;
int SQL_EXPRESSION_NE_N = 102;
int SQL_EXPRESSION_LT_N = 103;
int SQL_EXPRESSION_LE_N = 104;
int SQL_EXPRESSION_GT_N = 105;
int SQL_EXPRESSION_GE_N = 106;
int SQL_EXPRESSION_IN_N = 107;
int SQL_EXPRESSION_NOT_IN_N = 108;
int SQL_EXPRESSION_INS_N = 109;
int SQL_EXPRESSION_NOT_INS_N = 110;
int SQL_EXPRESSION_AND_N = 201;
int SQL_EXPRESSION_OR_N = 202;
int POW_N = 100;
int SQL_EXPRESSION_AND_OR = 2;
char BACKSLASH = '\\';
char S_QUOT = '\'';
String PIPE = "|";
String QUESTION_MARK = "?";
Map<String, Integer> SQL_EVAL_MAP = new HashMap<String, Integer>();
Map<String, Method> FUNC_MAP = new HashMap<String, Method>();
String[] STRING_ARR_TEMP = new String[0];
Object eval(Object... ms);
void setOutputFormatter(OutputFormatter outputFormatter);
} |
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ItemTest {
@Test
public void cria1ItemEspada() {
Item item = new Item(1, "espada");
assertEquals(1, item.getQtd());
assertTrue(item.getDescricao().equals("espada"));
}
@Test
public void umItemNaoEhIgualAoOutro() {
Item itemUm = new Item(1, "Espada");
Item itemDois = new Item(2, "Espada");
assertFalse(itemUm.equals(itemDois));
}
} |
package com.molina.cvmfs.catalog;
import com.molina.cvmfs.catalog.exception.CatalogInitializationException;
import com.molina.cvmfs.common.Common;
import com.molina.cvmfs.common.DatabaseObject;
import com.molina.cvmfs.common.PathHash;
import com.molina.cvmfs.directoryentry.Chunk;
import com.molina.cvmfs.directoryentry.DirectoryEntry;
import com.molina.cvmfs.directoryentry.exception.ChunkFileDoesNotMatch;
import javax.crypto.Mac;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
/**
* @author Jose Molina Colmenero
*
* Wraps the basic functionality of CernVM-FS Catalogs
*/
public class Catalog extends DatabaseObject {
public static final char CATALOG_ROOT_PREFIX = 'C';
protected float schema;
protected float schemaRevision;
protected int revision;
protected String hash;
protected Date lastModified;
protected String rootPrefix;
protected int previousRevision;
public static Catalog open(String catalogPath)
throws SQLException, CatalogInitializationException {
return new Catalog(new File(catalogPath), "");
}
public Catalog(File databaseFile, String catalogHash)
throws SQLException, CatalogInitializationException {
super(databaseFile);
hash = catalogHash;
schemaRevision = 0;
readProperties();
guessRootPrefixIfNeeded();
guessLastModifiedIfNeeded();
checkValidity();
}
public float getSchema() {
return schema;
}
/**
* Check all crucial properties have been found in the database
*/
protected void checkValidity() throws CatalogInitializationException {
if (revision == 0)
throw new CatalogInitializationException(
"Catalog lacks a revision entry");
if (schema == 0.0f)
throw new CatalogInitializationException(
"Catalog lacks a schema entry");
if (rootPrefix == null)
throw new CatalogInitializationException(
"Catalog lacks a root prefix entry");
if (lastModified == null)
throw new CatalogInitializationException(
"Catalog lacks a last modification entry");
}
/**
* Catalogs w/o a last_modified field, we set it to 0
*/
protected void guessLastModifiedIfNeeded() {
if (lastModified == null)
lastModified = new Date(0);
}
/**
* Root catalogs don't have a root prefix property
*/
protected void guessRootPrefixIfNeeded() {
if (rootPrefix == null)
rootPrefix = "/";
}
/**
* Detect catalog properties and store them
*/
protected void readProperties() throws SQLException {
Map<String, Object> map = readPropertiesTable();
for (String key : map.keySet()){
readProperty(key, map.get(key));
}
}
public float getSchemaRevision() {
return schemaRevision;
}
public int getRevision() {
return revision;
}
public String getHash() {
return hash;
}
public Date getLastModified() {
return lastModified;
}
public String getRootPrefix() {
return rootPrefix;
}
public int getPreviousRevision() {
return previousRevision;
}
protected void readProperty(String key, Object value){
if (key.equals("revision"))
revision = (Integer) value;
else if (key.equals("schema"))
schema = (Float) value;
else if (key.equals("schema_revision"))
schemaRevision = (Float) value;
else if (key.equals("last_modified"))
lastModified = new Date((Long) value);
else if (key.equals("previous_revision"))
previousRevision = (Integer) value;
else if (key.equals("root_prefix"))
rootPrefix = (String) value;
}
public boolean hasNested() {
return nestedCount() > 0;
}
public boolean isRoot() {
return rootPrefix.equals("/");
}
/**
* Returns the number of nested catalogs in the catalog
* @return the number of nested catalogs in this catalog
*/
public int nestedCount(){
ResultSet rs = null;
int numCatalogs = 0;
try {
rs = runSQL("SELECT count(*) FROM nested_catalogs;");
if (rs.next())
numCatalogs = rs.getInt(0);
} catch (SQLException e) {
return 0;
}
return numCatalogs;
}
/**
* List CatalogReferences to all contained nested catalogs
* @return array of CatalogReference containing all nested catalogs in this catalog
*/
public CatalogReference[] listNested() {
boolean newVersion = (schema <= 1.2 && schemaRevision > 0);
String sqlQuery;
if (newVersion) {
sqlQuery = "SELECT path, sha1, size FROM nested_catalogs";
} else {
sqlQuery = "SELECT path, sha1 FROM nested_catalogs";
}
ResultSet rs;
ArrayList<CatalogReference> arr = new ArrayList<CatalogReference>();
try {
rs = runSQL(sqlQuery);
while (rs.next()) {
String path = rs.getString(0);
String sha1 = rs.getString(1);
int size = 0;
if (newVersion)
size = rs.getInt(2);
arr.add(new CatalogReference(path, sha1, size));
}
} catch (SQLException e) {
return new CatalogReference[0];
}
return arr.toArray(new CatalogReference[arr.size()]);
}
public CatalogStatistics getStatistics() {
try {
return new CatalogStatistics(this);
} catch (SQLException e) {
return null;
}
}
/**
* Find the best matching nested CatalogReference for a given path
* @param needlePath path to search in the catalog
* @return The catalogs that best matches the given path
*/
public CatalogReference findNestedForPath(String needlePath) {
CatalogReference[] catalogRefs = listNested();
CatalogReference bestMatch = null;
int bestMatchScore = 0;
String realNeedlePath = cannonicalizePath(needlePath);
for (CatalogReference nestedCatalog : catalogRefs) {
if (realNeedlePath.startsWith(nestedCatalog.getRootPath()) &&
nestedCatalog.getRootPath().length() > bestMatchScore) {
bestMatchScore = nestedCatalog.getRootPath().length();
bestMatch = nestedCatalog;
}
}
return bestMatch;
}
/**
* Create a directory listing of the given directory path
* @param path path to be listed
* @return a list with all the DirectoryEntries contained in that path
*/
public DirectoryEntry[] listDirectory(String path) {
String realPath = cannonicalizePath(path);
try {
Mac md5Mac = Mac.getInstance("MD5");
PathHash parentHash = Common.splitMd5(
md5Mac.doFinal(realPath.getBytes()));
return listDirectorySplitMd5(parentHash.getHash1(),
parentHash.getHash2());
} catch (NoSuchAlgorithmException e) {
return new DirectoryEntry[0];
} catch (SQLException e) {
return new DirectoryEntry[0];
}
}
/**
* Create a directory listing of DirectoryEntry items based on MD5 path
* @param parent1 first part of the parent MD5 hash
* @param parent2 second part of the parent MD5 hash
*/
public DirectoryEntry[] listDirectorySplitMd5(Integer parent1,
Integer parent2)
throws SQLException {
ResultSet rs = runSQL("SELECT " +
DirectoryEntry.catalogDatabaseFields() + " FROM catalog " +
"WHERE parent_1 = " + parent1.toString() +
" AND parent_2 = " + parent2.toString() +
" ORDER BY name ASC;");
ArrayList<DirectoryEntry> arr = new ArrayList<DirectoryEntry>();
while (rs.next()) {
arr.add(makeDirectoryEntry(rs));
}
return arr.toArray(new DirectoryEntry[arr.size()]);
}
private DirectoryEntry makeDirectoryEntry(ResultSet rs)
throws SQLException {
DirectoryEntry dirent = new DirectoryEntry(rs);
readChunks(dirent);
return dirent;
}
/**
* Finds and adds the file chunk of a DirectoryEntry
* @param dirent DirectoryEntry that contains chunks
*/
private void readChunks(DirectoryEntry dirent) throws SQLException {
if (schema < 2.4)
return;
ResultSet rs = runSQL("SELECT " + Chunk.catalogDatabaseFields() +
" FROM chunks " +
"WHERE md5path_1 = " +
Integer.toString(dirent.getMd5path_1()) +
" AND md5path_2 = " +
Integer.toString(dirent.getMd5path_2()) +
" ORDER BY offset ASC");
try {
dirent.addChunks(rs);
} catch (ChunkFileDoesNotMatch chunkFileDoesNotMatch) {
}
}
private static String cannonicalizePath(String path) {
if (path == null)
return "";
return new File(path).getAbsolutePath();
}
} |
package com.openxc.openxcdiagnostic.diagnostic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.openxc.VehicleManager;
import com.openxc.messages.DiagnosticRequest;
import com.openxc.messages.DiagnosticResponse;
import com.openxc.openxcdiagnostic.R;
import com.openxc.openxcdiagnostic.dash.DashboardActivity;
import com.openxc.openxcdiagnostic.menu.MenuActivity;
import com.openxc.openxcdiagnostic.resources.Utilities;
public class DiagnosticActivity extends Activity {
private static String TAG = "VehicleDashboard";
private VehicleManager mVehicleManager;
private boolean mIsBound;
private final Handler mHandler = new Handler();
private Button sendRequestButton;
private Button clearButton;
private Button mFrequencyInfoButton;
private Button mBusInfoButton;
private Button mIdInfoButton;
private Button mModeInfoButton;
private Button mPidInfoButton;
private Button mPayloadInfoButton;
private Button mFactorInfoButton;
private Button mOffsetInfoButton;
private Button mNameInfoButton;
private Map<Button, String> buttonInfo = new HashMap<>();
private EditText mFrequencyInputText;
private EditText mBusInputText;
private EditText mIdInputText;
private EditText mModeInputText;
private EditText mPidInputText;
private EditText mPayloadInputText;
private EditText mFactorInputText;
private EditText mOffsetInputText;
private EditText mNameInputText;
private List<View> responseRows = new ArrayList<>();
private List<EditText> textFields = new ArrayList<>();
DiagnosticResponse.Listener mResponseListener = new DiagnosticResponse.Listener() {
public void receive(DiagnosticResponse response) {
mHandler.post(new Runnable() {
public void run() {
}
});
}
};
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Programmatically added views in the output disappear on orientation
// change. This is a workaround to add them back
LinearLayout outputRows = (LinearLayout) findViewById(R.id.outputRows);
outputRows.removeAllViews();
for (int i = 0; i < responseRows.size(); i++) {
View row = responseRows.get(i);
outputRows.addView(row);
}
}
private void outputResponse(DiagnosticResponse response) {
final LinearLayout outputRows = (LinearLayout) findViewById(R.id.outputRows);
LinearLayout row = (LinearLayout) getLayoutInflater().inflate(R.layout.createsingleoutputrow, null);
TextView output = (TextView) row.getChildAt(0);
final Button deleteButton = (Button) row.getChildAt(1);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
View row = (View) deleteButton.getParent();
outputRows.removeView(row);
responseRows.remove(row);
}
});
Utilities.writeLine(output, "bus : "
+ String.valueOf(response.getCanBus()));
Utilities.writeLine(output, "id : " + String.valueOf(response.getId()));
Utilities.writeLine(output, "mode: "
+ String.valueOf(response.getMode()));
boolean success = response.getSuccess();
Utilities.writeLine(output, "success : " + String.valueOf(success));
if (success) {
Utilities.writeLine(output, "payload : "
+ String.valueOf(response.getPayload()));
output.append("value : " + String.valueOf(response.getValue()));
} else {
output.append("negative_response_code"
+ response.getNegativeResponseCode().toString());
}
outputRows.addView(row, 0);
responseRows.add(0, row);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void
onServiceConnected(ComponentName className, IBinder service) {
Log.i(TAG, "Bound to VehicleManager");
mVehicleManager = ((VehicleManager.VehicleBinder) service).getService();
mIsBound = true;
}
public void onServiceDisconnected(ComponentName className) {
Log.w(TAG, "VehicleService disconnected unexpectedly");
mVehicleManager = null;
mIsBound = false;
}
};
/**
* Method to ensure that null is returned by
* generateDiagnosticRequestFromInputFields() when it should be. There are
* so many fail points in that method that it's safer to always return a
* call to this method than to match up a "return null" statement everywhere
* there should be a fail and a Toast. If the Toast happens when it should,
* the fail must too.
*/
private DiagnosticRequest failAndToastError(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return null;
}
private DiagnosticRequest generateDiagnosticRequestFromInputFields() {
Map<String, Object> map = new HashMap<>();
try {
String freqInput = mFrequencyInputText.getText().toString();
// frequency is optional, ok if empty
if (!freqInput.equals("")) {
float freq = Float.parseFloat(freqInput);
if (freq > 0) {
map.put(DiagnosticRequest.FREQUENCY_KEY, freq);
}
}
} catch (NumberFormatException e) {
return failAndToastError("Enter frequency does not appear to be a number.");
}
try {
int bus = Integer.parseInt(mBusInputText.getText().toString());
if (bus <= (int) DiagnosticRequest.BUS_RANGE.getMax()
&& bus >= (int) DiagnosticRequest.BUS_RANGE.getMin()) {
map.put(DiagnosticRequest.BUS_KEY, bus);
} else {
return failAndToastError("Invalid Bus entry. Did you mean 1 or 2?");
}
} catch (NumberFormatException e) {
return failAndToastError("Entered Bus does not appear to be an integer.");
}
try {
int id = Integer.parseInt(mIdInputText.getText().toString());
map.put(DiagnosticRequest.ID_KEY, id);
} catch (NumberFormatException e) {
return failAndToastError("Entered ID does not appear to be an integer.");
}
try {
int mode = Integer.parseInt(mModeInputText.getText().toString());
if (mode <= (int) DiagnosticRequest.MODE_RANGE.getMax()
&& mode >= (int) DiagnosticRequest.MODE_RANGE.getMin()) {
map.put(DiagnosticRequest.MODE_KEY, mode);
} else {
return failAndToastError("Invalid mode entry. Mode must be 0 < Mode < 16");
}
} catch (NumberFormatException e) {
return failAndToastError("Entered Mode does not appear to be an integer.");
}
try {
String pidInput = mPidInputText.getText().toString();
// pid is optional, ok if empty
if (!pidInput.equals("")) {
int pid = Integer.parseInt(pidInput);
map.put(DiagnosticRequest.PID_KEY, pid);
}
} catch (NumberFormatException e) {
return failAndToastError("Entered PID does not appear to be an integer.");
}
String payloadString = mPayloadInputText.getText().toString();
if (!payloadString.equals("")) {
if (payloadString.length() <= DiagnosticRequest.MAX_PAYLOAD_LENGTH_IN_CHARS) {
if (payloadString.length() % 2 == 0) {
map.put(DiagnosticRequest.PAYLOAD_KEY, payloadString);
} else {
return failAndToastError("Payload must have an even number of digits.");
}
} else {
return failAndToastError("Payload can only be up to 7 bytes, i.e. 14 digits");
}
}
try {
String factorInput = mFactorInputText.getText().toString();
// factor is optional, ok if empty
if (!factorInput.equals("")) {
float factor = Float.parseFloat(mFactorInputText.getText().toString());
map.put(DiagnosticRequest.FACTOR_KEY, factor);
}
} catch (NumberFormatException e) {
return failAndToastError("Entered Factor does not appear to be a decimal number.");
}
try {
String offsetInput = mOffsetInputText.getText().toString();
// factor is optional, ok if empty
if (!offsetInput.equals("")) {
float offset = Float.parseFloat(offsetInput);
map.put(DiagnosticRequest.OFFSET_KEY, offset);
}
} catch (NumberFormatException e) {
return failAndToastError("Entered Offset does not appear to be a decimal number.");
}
String name = mNameInputText.getText().toString();
if (!name.equals("")) {
map.put(DiagnosticRequest.NAME_KEY, name);
}
return new DiagnosticRequest(map);
}
private void initButtons() {
sendRequestButton = (Button) findViewById(R.id.sendRequestButton);
sendRequestButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
hideKeyboard();
getCurrentFocus().clearFocus();
DiagnosticRequest request = generateDiagnosticRequestFromInputFields();
if (request != null) {
DiagnosticResponse response = mVehicleManager.request(request);
outputResponse(response);
}
}
});
clearButton = (Button) findViewById(R.id.clearButton);
clearButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < textFields.size(); i++) {
textFields.get(i).setText("");
}
}
});
initInfoButtons();
}
private void initInfoButtons() {
Resources res = getResources();
final BiMap<String, String> infoMap = HashBiMap.create();
mFrequencyInfoButton = (Button) findViewById(R.id.frequencyQuestionButton);
buttonInfo.put(mFrequencyInfoButton, res.getString(R.string.frequencyInfo));
infoMap.put(res.getString(R.string.frequency_label), res.getString(R.string.frequencyInfo));
mBusInfoButton = (Button) findViewById(R.id.busQuestionButton);
buttonInfo.put(mBusInfoButton, res.getString(R.string.busInfo));
infoMap.put(res.getString(R.string.bus_label), res.getString(R.string.busInfo));
mIdInfoButton = (Button) findViewById(R.id.idQuestionButton);
buttonInfo.put(mIdInfoButton, res.getString(R.string.idInfo));
infoMap.put(res.getString(R.string.id_label), res.getString(R.string.idInfo));
mModeInfoButton = (Button) findViewById(R.id.modeQuestionButton);
buttonInfo.put(mModeInfoButton, res.getString(R.string.modeInfo));
infoMap.put(res.getString(R.string.mode_label), res.getString(R.string.modeInfo));
mPidInfoButton = (Button) findViewById(R.id.pidQuestionButton);
buttonInfo.put(mPidInfoButton, res.getString(R.string.pidInfo));
infoMap.put(res.getString(R.string.pid_label), res.getString(R.string.pidInfo));
mPayloadInfoButton = (Button) findViewById(R.id.payloadQuestionButton);
buttonInfo.put(mPayloadInfoButton, res.getString(R.string.payloadInfo));
infoMap.put(res.getString(R.string.payload_label), res.getString(R.string.payloadInfo));
mFactorInfoButton = (Button) findViewById(R.id.factorQuestionButton);
buttonInfo.put(mFactorInfoButton, res.getString(R.string.factorInfo));
infoMap.put(res.getString(R.string.factor_label), res.getString(R.string.factorInfo));
mOffsetInfoButton = (Button) findViewById(R.id.offsetQuestionButton);
buttonInfo.put(mOffsetInfoButton, res.getString(R.string.offsetInfo));
infoMap.put(res.getString(R.string.offset_label), res.getString(R.string.offsetInfo));
mNameInfoButton = (Button) findViewById(R.id.nameQuestionButton);
buttonInfo.put(mNameInfoButton, res.getString(R.string.nameInfo));
infoMap.put(res.getString(R.string.name_label), res.getString(R.string.nameInfo));
for (final Button button : buttonInfo.keySet()) {
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(DiagnosticActivity.this);
String info = buttonInfo.get(button);
builder.setMessage(info).setTitle(infoMap.inverse().get(info));
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.create().show();
}
});
}
}
private void hideKeyboard() {
InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if (manager.isAcceptingText()) {
manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
private void initTextFields() {
mFrequencyInputText = (EditText) findViewById(R.id.frequencyInput);
mFrequencyInputText.setHint("0");
textFields.add(mFrequencyInputText);
mBusInputText = (EditText) findViewById(R.id.busInput);
mBusInputText.setHint("Likely 1 or 2");
textFields.add(mBusInputText);
mIdInputText = (EditText) findViewById(R.id.idInput);
mIdInputText.setHint("
textFields.add(mIdInputText);
mModeInputText = (EditText) findViewById(R.id.modeInput);
mModeInputText.setHint(DiagnosticRequest.MODE_RANGE.getMin() + " - "
+ DiagnosticRequest.MODE_RANGE.getMax());
textFields.add(mModeInputText);
mPidInputText = (EditText) findViewById(R.id.pidInput);
mPidInputText.setHint("
textFields.add(mPidInputText);
mPayloadInputText = (EditText) findViewById(R.id.payloadInput);
mPayloadInputText.setHint("e.g. 0x1234");
textFields.add(mPayloadInputText);
mFactorInputText = (EditText) findViewById(R.id.factorInput);
mFactorInputText.setHint("1.0");
textFields.add(mFactorInputText);
mOffsetInputText = (EditText) findViewById(R.id.offsetInput);
mOffsetInputText.setHint("0");
textFields.add(mOffsetInputText);
mNameInputText = (EditText) findViewById(R.id.nameInput);
textFields.add(mNameInputText);
for (int i = 0; i < textFields.size(); i++) {
final EditText textField = textFields.get(i);
textField.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
hideKeyboard();
getCurrentFocus().clearFocus();
}
return false;
}
});
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diagnostic);
Log.i(TAG, "Vehicle diagnostic created");
initButtons();
initTextFields();
}
@Override
public void onResume() {
super.onResume();
bindService(new Intent(this, VehicleManager.class), mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public void onPause() {
super.onPause();
if (mIsBound) {
Log.i(TAG, "Unbinding from vehicle service");
unbindService(mConnection);
mIsBound = false;
}
}
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.Diagnostic) {
// do nothing
startActivity(new Intent(this, DiagnosticActivity.class));
} else if (item.getItemId() == R.id.Menu) {
startActivity(new Intent(this, MenuActivity.class));
return true;
} else if (item.getItemId() == R.id.Dashboard) {
startActivity(new Intent(this, DashboardActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
} |
package musician101.minetanks.listeners;
import java.io.File;
import java.util.Arrays;
import java.util.UUID;
import musician101.minetanks.MineTanks;
import musician101.minetanks.battlefield.BattleField;
import musician101.minetanks.battlefield.PlayerTank;
import musician101.minetanks.menu.Menus;
import musician101.minetanks.util.MTUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.file.YamlConfiguration;
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.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
public class FieldListener implements Listener
{
MineTanks plugin;
public FieldListener(MineTanks plugin)
{
this.plugin = plugin;
}
private boolean isInField(UUID playerId)
{
for (BattleField field : plugin.fieldStorage.getFields())
if (field.getPlayer(playerId) != null)
return true;
return false;
}
private boolean isSword(Material material)
{
//It's technically a sword without a blade.
//Stick is the default item if a player hasn't chosen a tank.
if (material == Material.STICK)
return true;
if (material == Material.WOOD_SWORD)
return true;
if (material == Material.STONE_SWORD)
return true;
if (material == Material.IRON_SWORD)
return true;
if (material == Material.GOLD_SWORD)
return true;
if (material == Material.DIAMOND_SWORD)
return true;
return false;
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onBlockInteract(PlayerInteractEvent event)
{
Player player = event.getPlayer();
if (!isInField(player.getUniqueId()))
return;
if (event.getAction() != Action.RIGHT_CLICK_AIR || event.getAction() != Action.RIGHT_CLICK_BLOCK)
return;
if (!isSword(event.getItem().getType()) || event.getItem().getType() != Material.WATCH)
return;
if (isSword(event.getItem().getType()))
{
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(player.getUniqueId());
if (pt != null)
{
if (pt.isReady())
{
player.sendMessage(ChatColor.RED + plugin.prefix + " You must unready to change your tank.");
return;
}
}
}
Menus.countrySelection.open(event.getPlayer());
return;
}
if (event.getItem().getType() == Material.WATCH)
{
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(player.getUniqueId());
if (pt != null)
{
if (pt.isReady())
{
pt.setReady(false);
player.getInventory().setItem(1, MTUtils.createCustomItem(Material.WATCH, "Ready Up", "You are currently not ready."));
return;
}
pt.setReady(true);
player.getInventory().setItem(1, MTUtils.createCustomItem(Material.WATCH, "Unready", "You are currently ready."));
field.startMatch();
}
}
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event)
{
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
File file = new File(plugin.getDataFolder() + File.separator + "InventoryStorage", player.getUniqueId().toString() + ".yml");
if (!file.exists())
return;
player.sendMessage(ChatColor.GREEN + plugin.prefix + " You logged off with items still stored away. They will now be returned to you.");
YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
for (int slot = 0; slot < player.getInventory().getSize(); slot++)
player.getInventory().setItem(slot, yml.getItemStack("inventory." + slot));
ItemStack[] armor = new ItemStack[4];
for (int slot = 0; slot < player.getInventory().getArmorContents().length; slot++)
armor[slot] = yml.getItemStack("armor." + slot);
player.getInventory().setArmorContents(armor);
player.teleport(new Location(Bukkit.getWorld(yml.getString("world")), yml.getDouble("x"), yml.getDouble("y"), yml.getDouble("z")));
file.delete();
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event)
{
Player player = event.getEntity();
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(player.getUniqueId());
if (pt != null)
{
player.getInventory().clear();
player.getInventory().setHelmet(null);
player.getInventory().setChestplate(null);
player.getInventory().setLeggings(null);
player.getInventory().setBoots(null);
field.playerKilled(pt);
field.endMatch();
return;
}
}
}
@EventHandler
public void onPlayerDisconnect(PlayerQuitEvent event)
{
for (BattleField field : plugin.fieldStorage.getFields())
{
PlayerTank pt = field.getPlayer(event.getPlayer().getUniqueId());
if (pt != null)
{
field.removePlayer(event.getPlayer());
return;
}
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
if (!isInField(event.getPlayer().getUniqueId()))
return;
Player player = event.getPlayer();
for (BattleField field : plugin.fieldStorage.getFields())
{
if (field.getPlayer(player.getUniqueId()) != null)
{
Location loc = player.getLocation();
double[] x = new double[2];
x[0] = field.getPoint1().getX();
x[1] = field.getPoint2().getX();
Arrays.sort(x);
double[] z = new double[2];
z[0] = field.getPoint1().getZ();
z[1] = field.getPoint2().getZ();
Arrays.sort(z);
if (loc.getX() < x[0] || loc.getX() > x[1] || loc.getZ() < z[0] || loc.getZ() > z[1])
{
player.sendMessage(ChatColor.RED + plugin.prefix + " Out of bounds!");
event.setCancelled(true);
return;
}
}
}
}
@EventHandler
public void onPlayerTeleport(PlayerTeleportEvent event)
{
if (event.getCause() == TeleportCause.COMMAND)
event.setCancelled(isInField(event.getPlayer().getUniqueId()));
}
} |
package com.redhat.ceylon.model.typechecker.model;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getNativeHeader;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getSignature;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getTypeArgumentMap;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.hasMatchingSignature;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isNameMatching;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isOverloadedVersion;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.isResolvable;
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.strictlyBetterMatch;
import static java.util.Collections.emptyList;
import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public abstract class TypeDeclaration extends Declaration
implements ImportableScope, Cloneable, Generic {
private Type extendedType;
private List<Type> satisfiedTypes =
needsSatisfiedTypes() ?
new ArrayList<Type>(3) :
Collections.<Type>emptyList();
private List<Type> caseTypes = null;
private Type selfType;
private List<Type> brokenSupertypes = null; // delayed allocation
private boolean inconsistentType;
private boolean dynamic;
private boolean sealed;
private List<TypedDeclaration> caseValues;
/**
* true if the type arguments of this type are not
* available at runtime
*/
public boolean isErasedTypeArguments() {
return false;
}
public boolean isSealed() {
return sealed;
}
public void setSealed(boolean sealed) {
this.sealed = sealed;
}
public boolean isDynamic() {
return dynamic;
}
public void setDynamic(boolean dynamic) {
this.dynamic = dynamic;
}
public boolean isInconsistentType() {
return inconsistentType;
}
protected boolean needsSatisfiedTypes() {
// NothingType doesn't need any so we save allocation
return true;
}
public void setInconsistentType(boolean inconsistentType) {
this.inconsistentType = inconsistentType;
}
public boolean isAbstract() {
return true;
}
@Override
protected TypeDeclaration clone() {
try {
return (TypeDeclaration) super.clone();
}
catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public boolean isSelfType() {
return false;
}
public boolean isFinal() {
return false;
}
public boolean isObjectClass() {
return false;
}
public boolean isValueConstructor() {
return false;
}
@Override
public List<TypeParameter> getTypeParameters() {
return emptyList();
}
@Override
public void setTypeParameters(List<TypeParameter> params) {
throw new UnsupportedOperationException();
}
/**
* The class or constructor extended by a class, the
* type aliased by a class or interface alias, or the
* class Anything for any other type.
*/
public Type getExtendedType() {
return extendedType;
}
public void setExtendedType(Type extendedType) {
this.extendedType = extendedType;
}
public List<Type> getSatisfiedTypes() {
return satisfiedTypes;
}
public void setSatisfiedTypes(List<Type> satisfiedTypes) {
this.satisfiedTypes = satisfiedTypes;
}
public List<Type> getCaseTypes() {
return caseTypes;
}
public void setCaseTypes(List<Type> caseTypes) {
this.caseTypes = caseTypes;
}
public List<Type> getBrokenSupertypes() {
return brokenSupertypes == null ?
Collections.<Type>emptyList() :
brokenSupertypes;
}
public void addBrokenSupertype(Type type) {
if (brokenSupertypes == null) {
brokenSupertypes =
new ArrayList<Type>(1);
}
brokenSupertypes.add(type);
}
@Override
public Reference appliedReference(Type pt,
List<Type> typeArguments) {
return appliedType(pt, typeArguments);
}
@Override
public final Type getReference() {
return getType();
}
/**
* Get a produced type for this declaration by
* binding explicit or inferred type arguments
* and type arguments of the type of which this
* declaration is a member, in the case that this
* is a nested type.
*
* @param qualifyingType the qualifying produced
* type or null if this is
* not a nested type dec
* @param typeArguments arguments to the type
* parameters of this
* declaration
*/
public Type appliedType(
Type qualifyingType,
List<Type> typeArguments) {
if (qualifyingType!=null &&
qualifyingType.isNothing()) {
return qualifyingType;
}
else {
Type pt = new Type();
pt.setDeclaration(this);
pt.setQualifyingType(qualifyingType);
pt.setTypeArguments(getTypeArgumentMap(this,
qualifyingType, typeArguments));
return pt;
}
}
/**
* The type of the declaration as seen from within the
* body of the declaration itself.
* <p/>
* Note that for certain special types which we happen
* to know don't have type arguments, we use this as a
* convenience method to quickly get a produced type for
* use outside the body of the declaration, but this is
* not really correct!
*/
public Type getType() {
Type type = new Type();
type.setQualifyingType(getMemberContainerType());
type.setDeclaration(this);
type.setTypeArguments(getTypeParametersAsArguments());
return type;
}
private List<Declaration> getInheritableMembers(
String name, List<TypeDeclaration> visited) {
if (visited.contains(this)) {
return Collections.emptyList();
}
else {
visited.add(this);
List<Declaration> members =
new ArrayList<Declaration>();
for (Declaration d: getMembers()) {
if (d.isShared() &&
d.getName()!=null &&
d.getName().equals(name) &&
isResolvable(d)) {
members.add(d);
}
}
if (members.isEmpty()) {
members.addAll(getInheritedMembers(name,
visited));
}
return members;
}
}
/**
* Get all members inherited by this type declaration
* with the given name. Do not include members declared
* directly by this type. Do not include declarations
* refined by a supertype.
*
* @deprecated This does not handle Java's inheritance
* model where overloads can be inherited
* from different supertypes ... I think we
* can remove this now and use getRefinedMember()
*/
public List<Declaration> getInheritedMembers(String name) {
return getInheritedMembers(name,
new ArrayList<TypeDeclaration>());
}
//identity containment
private static <T> boolean contains(Iterable<T> iter, T object) {
for (Object elem: iter) {
if (elem==object) {
return true;
}
}
return false;
}
private List<Declaration> getInheritedMembers(
String name, List<TypeDeclaration> visited) {
List<Declaration> members =
new ArrayList<Declaration>();
for (Type st: getSatisfiedTypes()) {
//if ( !(t instanceof TypeParameter) ) { //don't look for members in a type parameter with a self-referential lower bound
for (Declaration member:
st.getDeclaration()
.getInheritableMembers(name,
visited)) {
if (!contains(members, member)) {
members.add(member);
}
}
}
Type et = getExtendedType();
if (et!=null) {
for (Declaration member:
et.getDeclaration()
.getInheritableMembers(name,
visited)) {
if (!contains(members, member)) {
members.add(member);
}
}
}
return members;
}
/**
* Is the given declaration a direct or inherited
* member of this type?
*/
public boolean isMember(Declaration dec) {
return isMember(dec,
new ArrayList<TypeDeclaration>());
}
private boolean isMember(Declaration dec,
List<TypeDeclaration> visited) {
if (visited.contains(this)) {
return false;
}
visited.add(this);
for (Declaration member: getMembers()) {
if (dec.equals(member)) {
return true;
}
}
for (Type t: getSatisfiedTypes()) {
if (t.getDeclaration().isMember(dec, visited)) {
return true;
}
}
Type et = getExtendedType();
if (et!=null) {
if (et.getDeclaration()
.isMember(dec, visited)) {
return true;
}
}
return false;
}
/**
* Does the given declaration inherit the given type?
*/
public abstract boolean inherits(TypeDeclaration dec);
/**
* Return the least-refined (i.e. the non-actual member)
* with the given name, by reversing the usual search
* order and searching supertypes first.
*/
public Declaration getRefinedMember(String name,
List<Type> signature, boolean ellipsis) {
return getRefinedMember(name, signature, ellipsis,
false);
}
public Declaration getRefinedMember(String name,
List<Type> signature, boolean ellipsis,
boolean onlyExactMatches) {
return getRefinedMember(name, signature, ellipsis,
onlyExactMatches,
new HashSet<TypeDeclaration>());
}
protected Declaration getRefinedMember(String name,
List<Type> signature, boolean ellipsis,
boolean onlyExactMatches,
Set<TypeDeclaration> visited) {
if (!visited.add(this)) {
return null;
}
else {
Declaration result = null;
Type et = getExtendedType();
if (et!=null) {
Declaration ed =
et.getDeclaration()
.getRefinedMember(name,
signature, ellipsis,
onlyExactMatches,
visited);
if (isBetterRefinement(signature,
ellipsis, result, ed)) {
result = ed;
}
}
for (Type st: getSatisfiedTypes()) {
Declaration sd =
st.getDeclaration()
.getRefinedMember(name,
signature, ellipsis,
onlyExactMatches,
visited);
if (isBetterRefinement(signature,
ellipsis, result, sd)) {
result = sd;
}
}
Declaration dd =
getDirectMember(name,
signature, ellipsis,
onlyExactMatches);
if (isBetterRefinement(signature,
ellipsis, result, dd)) {
result = dd;
}
return result;
}
}
public boolean isBetterRefinement(
List<Type> signature, boolean ellipsis,
Declaration result, Declaration candidate) {
if (candidate==null ||
candidate.isActual() /*&&
!candidate.getNameAsString()
.equals("ceylon.language::Object")*/ ||
!candidate.isShared()) {
return false;
}
if (result==null) {
return signature!=null ==
candidate instanceof Functional;
}
if (!(result instanceof Functional)) {
return signature!=null;
}
if (!(candidate instanceof Functional)) {
return signature==null;
}
if (signature==null) {
throw new RuntimeException("missing signature");
}
if (candidate.isAbstraction() &&
!result.isAbstraction()) {
return false;
}
if (!candidate.isAbstraction() &&
result.isAbstraction()) {
return true;
}
if (hasMatchingSignature(candidate, signature, ellipsis)) {
return !hasMatchingSignature(result, signature, ellipsis) ||
strictlyBetterMatch(candidate, result);
}
return false; //asymmetric!!
}
/**
* Get the most-refined member with the given name,
* searching this type first, taking aliases into
* account, followed by supertypes. We're looking
* for shared members.
*/
public Declaration getMember(
String name,
Unit unit,
List<Type> signature,
boolean variadic) {
//TODO: does not handle aliased members of supertypes
Declaration dec =
unit.getImportedDeclaration(this, name,
signature, variadic);
if (dec==null) {
return getMemberInternal(name,
signature, variadic, false)
.getMember();
}
else {
return dec;
}
}
/**
* Is the most-refined member with the given name,
* searching this type first, taking aliases into
* account, followed by supertypes, ambiguous,
* because we could not construct a principal
* instantiation for an intersection?
* TODO: this information should really be encoded
* into the return value of getMember() but
* I'm leaving it like this for now to avoid
* breaking the backends
*/
public boolean isMemberAmbiguous(
String name,
Unit unit,
List<Type> signature,
boolean variadic) {
//TODO: does not handle aliased members of supertypes
Declaration dec =
unit.getImportedDeclaration(this, name,
signature, variadic);
if (dec==null) {
return getMemberInternal(name,
signature, variadic, false)
.isAmbiguous();
}
else {
return false;
}
}
/**
* Get the most-refined member with the given name,
* searching this type first, followed by supertypes.
* We're looking for shared members.
*/
@Override
public Declaration getMember(
String name,
List<Type> signature,
boolean variadic,
boolean onlyExactMatches) {
return getMemberInternal(name,
signature, variadic,
onlyExactMatches)
.getMember();
}
private SupertypeDeclaration getMemberInternal(
String name,
List<Type> signature, boolean variadic,
boolean onlyExactMatches) {
if (!onlyExactMatches && signature!=null) {
//first try for an exact match
SupertypeDeclaration sd =
getMemberInternal(name,
signature, variadic,
true);
if (sd.getMember()!=null || sd.isAmbiguous()) {
return sd;
}
}
//first search for the member in the local
//scope, including non-shared declarations
Declaration dec =
getDirectMember(name,
signature, variadic,
onlyExactMatches);
if (dec!=null && dec.isShared()) {
//if it's shared, it's what we're looking
//for, return it
//TODO: should also return it if we're
// calling from local scope!
return new SupertypeDeclaration(dec, false);
}
else {
//now look for inherited shared declarations
SupertypeDeclaration sd =
getSupertypeDeclaration(name,
signature, variadic,
onlyExactMatches);
if (sd.getMember()!=null || sd.isAmbiguous()) {
return sd;
}
}
//finally return the non-shared member we
//found earlier, so that the caller can give
//a nice error message
return new SupertypeDeclaration(dec, false);
}
/**
* Get the parameter or most-refined member with the
* given name, searching this type first, followed by
* supertypes. Return un-shared members declared by
* this type.
*/
@Override
protected Declaration getMemberOrParameter(
String name,
List<Type> signature, boolean variadic,
boolean onlyExactMatches) {
//first search for the member or parameter
//in the local scope, including non-shared
//declarations
Declaration dec =
getDirectMember(name,
signature, variadic,
onlyExactMatches);
if (dec!=null) {
if (signature!=null &&
dec.isAbstraction()) {
// look for a supertype declaration that
// matches the given signature better
Declaration supertype =
getSupertypeDeclaration(name,
signature, variadic,
onlyExactMatches)
.getMember();
if (supertype!=null &&
!supertype.isAbstraction()) {
return supertype;
}
}
}
else {
// If we couldn't find the declaration in the current
// scope and the scope is a native implementation we
// will try again with its header
if (isNativeImplementation()) {
Declaration hdr = getNativeHeader(this);
if (hdr != null) {
dec = hdr.getDirectMember(name,
signature, variadic,
onlyExactMatches);
}
}
if (dec == null) {
//now look for inherited shared declarations
dec = getSupertypeDeclaration(name,
signature, variadic,
onlyExactMatches)
.getMember();
}
}
return dec;
}
/**
* Is the given declaration inherited from
* a supertype of this type or an outer
* type?
*
* @return true if it is
*/
@Override
public boolean isInherited(Declaration member) {
if (member.getContainer().equals(this)) {
return false;
}
else if (isInheritedFromSupertype(member)) {
return true;
}
else if (getContainer()!=null) {
return getContainer()
.isInherited(member);
}
else {
return false;
}
}
/**
* Get the containing type which inherits the given declaration.
*
* @return null if the declaration is not inherited!!
*/
@Override
public TypeDeclaration getInheritingDeclaration(
Declaration member) {
Scope container = member.getContainer();
if (container!=null && container.equals(this)) {
return null;
}
else if (isInheritedFromSupertype(member)) {
return this;
}
else if (getContainer()!=null) {
return getContainer()
.getInheritingDeclaration(member);
}
else {
return null;
}
}
public boolean isInheritedFromSupertype(
final Declaration member) {
final List<Type> signature =
getSignature(member);
class Criteria implements Type.Criteria {
@Override
public boolean satisfies(TypeDeclaration type) {
if (type.equals(TypeDeclaration.this)) {
return false;
}
else {
Declaration dm =
type.getDirectMember(
member.getName(),
signature, false);
return dm!=null && dm.equals(member);
}
}
@Override
public boolean isMemberLookup() {
return false;
}
};
return getType()
.getSupertype(new Criteria())!=null;
}
static class SupertypeDeclaration {
private Declaration member;
private boolean ambiguous;
SupertypeDeclaration(Declaration declaration,
boolean ambiguous) {
this.member = declaration;
this.ambiguous = ambiguous;
}
private boolean isAmbiguous() {
return ambiguous;
}
private Declaration getMember() {
return member;
}
}
/**
* Get the supertype which defines the most-refined
* member with the given name.
*/
SupertypeDeclaration getSupertypeDeclaration(
final String name,
final List<Type> signature,
final boolean variadic,
final boolean onlyExactMatches) {
class ExactCriteria implements Type.Criteria {
@Override
public boolean satisfies(TypeDeclaration type) {
// do not look in ourselves
if (type == TypeDeclaration.this) {
return false;
}
Declaration dm =
type.getDirectMember(name,
signature, variadic,
onlyExactMatches);
if (dm!=null &&
dm.isShared() &&
isResolvable(dm)) {
// only accept abstractions if we
// don't have a signature
return !dm.isAbstraction() ||
signature == null;
}
else {
return false;
}
}
@Override
public boolean isMemberLookup() {
return true;
}
};
class LooseCriteria implements Type.Criteria {
@Override
public boolean satisfies(TypeDeclaration type) {
// do not look in ourselves
if (type == TypeDeclaration.this) {
return false;
}
Declaration dm =
type.getDirectMember(name,
null, false);
if (dm!=null &&
dm.isShared() &&
isResolvable(dm)) {
// only accept abstractions
return dm.isAbstraction();
}
else {
return false;
}
}
@Override
public boolean isMemberLookup() {
return true;
}
};
class SkipFormalCriteria implements Type.Criteria {
@Override
public boolean satisfies(TypeDeclaration type) {
// do not look in ourselves
if (type == TypeDeclaration.this) {
return false;
}
Declaration dm =
type.getDirectMember(name,
signature, variadic,
onlyExactMatches);
if (dm!=null &&
dm.isShared() &&
isResolvable(dm)) {
//ignore formals, to allow for Java's
//refinement model
return !dm.isFormal() &&
(!dm.isAbstraction() ||
signature == null);
}
else {
return false;
}
}
@Override
public boolean isMemberLookup() {
return true;
}
};
//this works by finding the most-specialized
//supertype that defines the member
Type type = getType();
Type st = type.getSupertype(new ExactCriteria());
if (st == null) {
//no match
if (!onlyExactMatches) {
//try again, ignoring the given signature
st = type.getSupertype(new LooseCriteria());
}
}
else if (st.isUnknown()) {
//ambiguous
if (this instanceof Class) {
//try again, ignoring Java abstract members
st = type.getSupertype(new SkipFormalCriteria());
}
}
if (st == null) {
//no such member
return new SupertypeDeclaration(null, false);
}
else if (st.isUnknown()) {
//we're dealing with an ambiguous member of an
//intersection type
//TODO: this is pretty fragile - it depends upon
// the fact that getSupertype() just happens
// to return an UnknownType instead of null
// in this case
return new SupertypeDeclaration(null, true);
}
else {
//we got exactly one uniquely-defined member
Declaration member =
st.getDeclaration()
.getDirectMember(name,
signature, variadic,
onlyExactMatches);
return new SupertypeDeclaration(member, false);
}
}
/**
* Is this a class or interface alias?
*/
public boolean isAlias() {
return false;
}
public void setSelfType(Type selfType) {
this.selfType = selfType;
}
public Type getSelfType() {
return selfType;
}
public Map<String,DeclarationWithProximity>
getImportableDeclarations(Unit unit, String startingWith,
List<Import> imports, int proximity) {
//TODO: fix copy/paste from below!
Map<String,DeclarationWithProximity> result =
new TreeMap<String,DeclarationWithProximity>();
for (Declaration dec: getMembers()) {
if (isResolvable(dec) &&
dec.isShared() &&
!isOverloadedVersion(dec) &&
isNameMatching(startingWith, dec) ) {
boolean already = false;
for (Import i: imports) {
if (i.getDeclaration().equals(dec)) {
already = true;
break;
}
}
if (!already) {
result.put(dec.getName(unit),
new DeclarationWithProximity(dec,
proximity));
}
}
}
return result;
}
@Override
public Map<String,DeclarationWithProximity>
getMatchingDeclarations(Unit unit, String startingWith,
int proximity) {
Map<String,DeclarationWithProximity> result =
super.getMatchingDeclarations(unit,
startingWith, proximity);
//Inherited declarations hide outer and imported declarations
result.putAll(getMatchingMemberDeclarations(unit,
null, startingWith, proximity));
//Local declarations always hide inherited declarations, even if non-shared
for (Declaration dec: getMembers()) {
if (isResolvable(dec) &&
!isOverloadedVersion(dec) ) {
if (isNameMatching(startingWith, dec)) {
result.put(dec.getName(unit),
new DeclarationWithProximity(dec,
proximity));
}
for(String alias : dec.getAliases()){
if(isNameMatching(startingWith, alias)){
result.put(alias,
new DeclarationWithProximity(
alias, dec, proximity));
}
}
}
}
return result;
}
public Map<String,DeclarationWithProximity>
getMatchingMemberDeclarations(Unit unit, Scope scope,
String startingWith, int proximity) {
Map<String,DeclarationWithProximity> result =
new TreeMap<String,DeclarationWithProximity>();
for (Type st: getSatisfiedTypes()) {
mergeMembers(result,
st.getDeclaration()
.getMatchingMemberDeclarations(unit,
scope, startingWith,
proximity+1));
}
Type et =
getExtendedType();
if (et!=null) {
mergeMembers(result,
et.getDeclaration()
.getMatchingMemberDeclarations(unit,
scope, startingWith,
proximity+1));
}
for (Declaration member: getMembers()) {
if (isResolvable(member) &&
!isOverloadedVersion(member) &&
(member.isShared() ||
ModelUtil.contains(member.getScope(),
scope))) {
if (isNameMatching(startingWith, member)) {
result.put(member.getName(unit),
new DeclarationWithProximity(
member, proximity));
}
for (String alias : member.getAliases()) {
if (isNameMatching(startingWith, alias)) {
result.put(alias,
new DeclarationWithProximity(
alias, member, proximity));
}
}
}
}
//premature optimization so that we don't have to
//call d.getName(unit) on *every* member
result.putAll(unit.getMatchingImportedDeclarations(
this, startingWith, proximity));
return result;
}
private void mergeMembers(
Map<String,DeclarationWithProximity> result,
Map<String,DeclarationWithProximity> etm) {
for (Map.Entry<String,DeclarationWithProximity> e:
etm.entrySet()) {
String name = e.getKey();
DeclarationWithProximity current =
e.getValue();
DeclarationWithProximity existing =
result.get(name);
if (existing==null ||
!existing.getDeclaration()
.refines(current.getDeclaration())) {
result.put(name, current);
}
}
}
/**
* implement the rule that Foo&Bar==Nothing if
* here exists some enumerated type Baz with
*
* Baz of Foo | Bar
*
* (the intersection of disjoint types is empty)
*
* @param type a type which might be disjoint from
* a list of other given types
* @param list the list of other types
* @param unit
*
* @return true of the given type was disjoint from
* the given list of types
*/
public boolean isDisjoint(TypeDeclaration td) {
if (this instanceof ClassOrInterface &&
td instanceof ClassOrInterface &&
equals(td)) {
return false;
}
if (this instanceof TypeParameter &&
td instanceof TypeParameter &&
equals(td)) {
return false;
}
List<Type> sts = getSatisfiedTypes();
for (int i=0, s=sts.size(); i<s; i++) {
Type st = sts.get(i);
if (isDisjoint(td, st)) {
return true;
}
}
Type et = getExtendedType();
if (et!=null) {
if (isDisjoint(td, et)) {
return true;
}
}
return false;
}
private boolean isDisjoint(TypeDeclaration td, Type st) {
TypeDeclaration std = st.getDeclaration();
List<Type> cts = std.getCaseTypes();
if (cts!=null) {
for (int i=0, s=cts.size(); i<s; i++) {
TypeDeclaration ctd =
cts.get(i)
.getDeclaration();
if (ctd.equals(this)) {
for (int j=0, l=cts.size(); j<l; j++) {
if (i!=j) {
TypeDeclaration octd =
cts.get(j)
.getDeclaration();
if (td.inherits(octd)) {
return true;
}
}
}
break;
}
}
}
if (std.isDisjoint(td)) {
return true;
}
return false;
}
// private List<TypeDeclaration> supertypeDeclarations;
public final List<TypeDeclaration> getSupertypeDeclarations() {
// if (TypeCache.isEnabled()) {
// if (supertypeDeclarations==null) {
// supertypeDeclarations =
// getSupertypeDeclarationsInternal();
// return supertypeDeclarations;
// else {
return getSupertypeDeclarationsInternal();
}
private List<TypeDeclaration> getSupertypeDeclarationsInternal() {
List<TypeDeclaration> results =
new ArrayList<TypeDeclaration>(
getSatisfiedTypes().size()+2);
results.add(unit.getAnythingDeclaration());
collectSupertypeDeclarations(results);
// results = unmodifiableList(results);
return results;
}
abstract void collectSupertypeDeclarations(
List<TypeDeclaration> results);
/**
* Clears the Type supertype caches for that declaration. Does nothing
* for Union/Intersection types since they are not cached. Only does something
* for ClassOrInterface, TypeAlias, TypeParameter.
*/
public void clearProducedTypeCache() {
// do nothing, work in subclasses
// supertypeDeclarations = null;
}
public boolean isAnything() {
return false;
}
public boolean isObject() {
return false;
}
public boolean isNull() {
return false;
}
public boolean isNullValue() {
return false;
}
public boolean isBasic() {
return false;
}
public boolean isBoolean() {
return false;
}
public boolean isString() {
return false;
}
public boolean isCharacter() {
return false;
}
public boolean isFloat() {
return false;
}
public boolean isInteger() {
return false;
}
public boolean isByte() {
return false;
}
public boolean isEmpty() {
return false;
}
boolean isEmptyValue() {
return false;
}
public boolean isEntry() {
return false;
}
public boolean isTuple() {
return false;
}
public boolean isIterable() {
return false;
}
public boolean isSequential() {
return false;
}
public boolean isSequence() {
return false;
}
public boolean isRange() {
return false;
}
public List<TypedDeclaration> getCaseValues() {
return caseValues;
}
public void setCaseValues(List<TypedDeclaration> caseValues) {
this.caseValues = caseValues;
}
public boolean isSequentialType() {
return false;
}
public boolean isSequenceType() {
return false;
}
public boolean isEmptyType() {
return false;
}
public boolean isTupleType() {
return false;
}
@Override
public Set<String> getScopedBackends() {
return super.getScopedBackends();
}
public ElementType[] getAnnotationTarget() {
return null;
}
} |
/*
* Thibaut Colar Aug 24, 2009
*/
package net.colar.netbeans.fan.debugger;
import java.net.URL;
import org.netbeans.api.debugger.jpda.LineBreakpoint;
import org.netbeans.api.java.classpath.ClassPath;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.filesystems.URLMapper;
/**
*
* @author thibautc
*/
public class FanBkptHelper
{
public static LineBreakpoint createFanBp(String url, int lineNb)
{
//TODO: finish this, all harcoded
//TODO: fan.podname.classname
//TODO: main method code -> fan.podname.Classname$main$0.class?
LineBreakpoint bp = LineBreakpoint.create(url, lineNb);
bp.setStratum("Fan");
bp.setHidden(false);
bp.setSourceName(getName(url));
bp.setPrintText(getName(url));
bp.setSourcePath("fan/Debug/Main.fan"/*getPath(url)*/);
bp.setPreferredClassName("fan.Debug.Main*"/*getClassFilter(url)*/);
//bp.setPreferredClassName(url);
bp.setSuspend(LineBreakpoint.SUSPEND_ALL);
System.out.println("bp class:" + bp.getPreferredClassName());
System.out.println("bp sourceName:" + bp.getSourceName());
System.out.println("bp lineNb:" + bp.getLineNumber());
System.out.println("bp cond:" + bp.getCondition());
System.out.println("bp printText:" + bp.getPrintText());
System.out.println("bp groupName:" + bp.getGroupName());
System.out.println("bp vMessage:" + bp.getValidityMessage());
System.out.println("bp sourcePath:" + bp.getSourcePath());
System.out.println("bp url:" + bp.getURL());
return bp;
}
private static String getName(String url)
{
FileObject fo = null;
try
{
fo = URLMapper.findFileObject(new URL(url));
} catch (Exception e)
{
e.printStackTrace();
}
if (fo != null)
{
System.err.println("Name: " + fo.getNameExt());
return fo.getNameExt();
}
System.err.println("Name: " + url);
return (url == null) ? null : url.toString();
}
private static String getPath(String url)
{
FileObject fo = null;
try
{
fo = URLMapper.findFileObject(new URL(url));
} catch (Exception e)
{
e.printStackTrace();
}
String relativePath = url;
if (fo != null)
{
FileObject root = ClassPath.getClassPath(fo, ClassPath.SOURCE).findOwnerRoot(fo);
relativePath = FileUtil.getRelativePath(root, fo);
}
System.err.println("sourcePath: " + relativePath);
return relativePath;
}
private static String getClassFilter(String url)
{
FileObject fo = null;
try
{
fo = URLMapper.findFileObject(new URL(url));
} catch (Exception e)
{
e.printStackTrace();
}
String relativePath = url;
if (fo != null)
{
ClassPath cp = ClassPath.getClassPath(fo, ClassPath.SOURCE);
if (cp == null)
{
System.err.println("No classpath for " + url);
return null;
}
FileObject root = cp.findOwnerRoot(fo);
if (root == null)
{
return null;
}
relativePath = FileUtil.getRelativePath(root, fo);
}
if (relativePath.endsWith(".fan") || relativePath.endsWith(".fwt"))
{ // NOI18N
relativePath = relativePath.substring(0, relativePath.length() - 4);
}
relativePath = relativePath.replace('/', '.') + "*";
System.err.println("filter: " + relativePath);
return relativePath;
}
} |
package com.sgrailways.giftidea.db;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import com.google.inject.Inject;
import com.sgrailways.giftidea.Clock;
import com.sgrailways.giftidea.HashTagLocator;
import com.sgrailways.giftidea.domain.Idea;
import com.sgrailways.giftidea.domain.MissingIdea;
import com.sgrailways.giftidea.domain.MissingRecipient;
import com.sgrailways.giftidea.domain.Recipient;
import org.apache.commons.lang3.StringUtils;
import java.util.LinkedHashSet;
import static com.sgrailways.giftidea.db.Database.IdeasTable.IS_DONE;
import static com.sgrailways.giftidea.db.Database.IdeasTable.TABLE_NAME;
public class Ideas {
private final SQLiteDatabase writeableDatabase;
private final Recipients recipients;
private final Clock clock;
private final HashTagLocator hashTagLocator;
private final static String[] COLUMNS = new String[]{Database.IdeasTable._ID, Database.IdeasTable.IDEA, Database.IdeasTable.IS_DONE};
@Inject
public Ideas(Database database, Recipients recipients, Clock clock, HashTagLocator hashTagLocator) {
this.hashTagLocator = hashTagLocator;
this.writeableDatabase = database.getWritableDatabase();
this.recipients = recipients;
this.clock = clock;
}
public Idea findById(long id) {
Cursor cursor = writeableDatabase.query(TABLE_NAME, COLUMNS, Database.IdeasTable._ID + "=?", new String[]{String.valueOf(id)}, null, null, null, "1");
if(!cursor.moveToFirst()) {
return new MissingIdea();
}
Idea idea = new Idea(cursor.getLong(0), cursor.getString(1));
cursor.close();
return idea;
}
public Cursor findAllForRecipientName(String name) {
String recipientId = String.valueOf(recipients.findByName(name).getId());
return writeableDatabase.query(TABLE_NAME, COLUMNS, Database.IdeasTable.RECIPIENT_ID + "=?", new String[]{recipientId}, null, null, IS_DONE + " ASC");
}
public Remaining delete(long id) {
Remaining ideasRemaining;
try {
writeableDatabase.beginTransaction();
Cursor cursor = writeableDatabase.query(TABLE_NAME, new String[]{Database.IdeasTable.RECIPIENT_ID}, Database.IdeasTable._ID + "=?", new String[]{String.valueOf(id)}, null, null, null);
cursor.moveToFirst();
long recipientId = cursor.getLong(0);
cursor.close();
writeableDatabase.delete(TABLE_NAME, Database.IdeasTable._ID + "=?", new String[]{String.valueOf(id)});
//TODO: remove this for api-10 compatibility
long ideasForRecipient = DatabaseUtils.queryNumEntries(writeableDatabase, TABLE_NAME, Database.IdeasTable.RECIPIENT_ID + "=?", new String[]{String.valueOf(recipientId)});
long activeIdeasForRecipient = DatabaseUtils.queryNumEntries(writeableDatabase, TABLE_NAME, Database.IdeasTable.RECIPIENT_ID + "=? AND " + Database.IdeasTable.IS_DONE + "=?", new String[]{String.valueOf(recipientId), String.valueOf(false)});
if (ideasForRecipient == 0) {
writeableDatabase.delete(Database.RecipientsTable.TABLE_NAME, Database.RecipientsTable._ID + "=?", new String[]{String.valueOf(recipientId)});
ideasRemaining = Remaining.NO;
} else if(activeIdeasForRecipient == 0) {
recipients.decrementIdeaCountFor(recipients.findById(recipientId));
ideasRemaining = Remaining.YES;
} else {
ideasRemaining = Remaining.YES;
}
writeableDatabase.setTransactionSuccessful();
return ideasRemaining;
} finally {
writeableDatabase.endTransaction();
}
}
public Remaining forRecipient(String recipientName) {
long recipientId = recipients.findByName(recipientName).getId();
//TODO: remove this for api-10 compatibility
long ideasCount = DatabaseUtils.queryNumEntries(writeableDatabase, TABLE_NAME, Database.IdeasTable.RECIPIENT_ID + "=?", new String[]{String.valueOf(recipientId)});
return ideasCount == 0 ? Remaining.NO : Remaining.YES;
}
public void update(long id, String idea) {
ContentValues ideaValues = new ContentValues();
ideaValues.put(Database.IdeasTable.IDEA, StringUtils.normalizeSpace(idea));
ideaValues.put(Database.IdeasTable.UPDATED_AT, clock.now());
try {
writeableDatabase.beginTransaction();
writeableDatabase.update(TABLE_NAME, ideaValues, Database.IdeasTable._ID + "=?", new String[]{String.valueOf(id)});
writeableDatabase.setTransactionSuccessful();
} finally {
writeableDatabase.endTransaction();
}
}
public void createFromText(String idea) {
String now = clock.now();
ContentValues ideaValues = new ContentValues();
ideaValues.put(Database.IdeasTable.IDEA, hashTagLocator.removeAllFrom(idea));
ideaValues.put(Database.IdeasTable.IS_DONE, String.valueOf(false));
ideaValues.put(Database.IdeasTable.CREATED_AT, now);
ideaValues.put(Database.IdeasTable.UPDATED_AT, now);
LinkedHashSet<String> hashTags = hashTagLocator.findAllIn(idea);
try {
writeableDatabase.beginTransaction();
for (String hashTag : hashTags) {
Recipient recipient = recipients.findByName(hashTag);
long recipientId;
if (recipient instanceof MissingRecipient) {
recipientId = recipients.createFromName(hashTag).getId();
} else {
recipientId = recipient.getId();
recipients.incrementIdeaCountFor(recipient);
}
ideaValues.put(Database.IdeasTable.RECIPIENT_ID, recipientId);
writeableDatabase.insert(Database.IdeasTable.TABLE_NAME, null, ideaValues);
}
writeableDatabase.setTransactionSuccessful();
} finally {
writeableDatabase.endTransaction();
}
}
public void gotIt(long id, String recipientName) {
ContentValues values = new ContentValues();
values.put(Database.IdeasTable.IS_DONE, String.valueOf(true));
values.put(Database.IdeasTable.UPDATED_AT, clock.now());
writeableDatabase.update(Database.IdeasTable.TABLE_NAME, values, Database.IdeasTable._ID + "=?", new String[]{String.valueOf(id)});
Recipient recipient = recipients.findByName(recipientName);
if(!(recipient instanceof MissingRecipient)) {
recipients.decrementIdeaCountFor(recipient);
}
}
public enum Remaining {
YES, NO
}
} |
package com.valkryst.VTerminal.builder.component;
import com.valkryst.VTerminal.component.TextField;
import com.valkryst.VTerminal.misc.JSONFunctions;
import lombok.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.Color;
import java.util.regex.Pattern;
@EqualsAndHashCode(callSuper=true)
@ToString
public class TextFieldBuilder extends ComponentBuilder<TextField> {
/** The width of the text field, in characters. */
@Getter @Setter private int width;
/** The maximum number of characters that the text field can contain. */
@Getter @Setter private int maxCharacters;
/** The foreground color of the caret. */
@Getter @Setter @NonNull private Color caretForegroundColor;
/** The background color of the caret. */
@Getter @Setter @NonNull private Color caretBackgroundColor;
/** The foreground color of non-caret characters. */
@Getter @Setter @NonNull private Color foregroundColor;
/** The background color of non-caret characters. */
@Getter @Setter @NonNull private Color backgroundColor;
/** Whether or not the field can be edited. */
@Getter @Setter private boolean editable;
/** Whether or not the HOME key can be used to move the caret to the first index of the field. */
@Getter @Setter private boolean homeKeyEnabled;
/** Whether or not the END key can be used to move the caret to the last index of the field. */
@Getter @Setter private boolean endKeyEnabled;
/** Whether or not the DELETE key can be used to erase the character that the caret is on. */
@Getter @Setter private boolean deleteKeyEnabled;
/** Whether or not the LEFT ARROW key can be used to move the caret one index to the left. */
@Getter @Setter private boolean leftArrowKeyEnabled;
/** Whether or not the RIGHT ARROW key can be used to move the caret one index to the right. */
@Getter @Setter private boolean rightArrowKeyEnabled;
/** Whether or not the BACK SPACE key can be used to erase the character before the caret and move the caret backwards. */
@Getter @Setter private boolean backSpaceKeyEnabled;
/** The pattern used to determine which typed characters can be entered into the field. */
@Getter @Setter @NonNull private Pattern allowedCharacterPattern;
@Override
public TextField build() {
checkState();
return new TextField(this);
}
protected void checkState() throws NullPointerException {
super.checkState();
if (width < 1) {
throw new IllegalArgumentException("The width cannot be less than one.");
}
if (maxCharacters < 1) {
throw new IllegalArgumentException("The maximum characters cannot be less than one.");
}
if (maxCharacters < width) {
maxCharacters = width;
}
}
/** Resets the builder to it's default state. */
public void reset() {
super.reset();
width = 4;
maxCharacters = 4;
caretForegroundColor = new Color(0xFF8E999E, true);
caretBackgroundColor = new Color(0xFF68D0FF, true);
foregroundColor = caretBackgroundColor;
backgroundColor = caretForegroundColor;
editable = true;
homeKeyEnabled = true;
endKeyEnabled = true;
deleteKeyEnabled = true;
leftArrowKeyEnabled = true;
rightArrowKeyEnabled = true;
backSpaceKeyEnabled = true;
allowedCharacterPattern = Pattern.compile("^[a-zA-z0-9$-/:-?{-~!\"^_`\\[\\]@
}
@Override
public void parseJSON(final JSONObject jsonObject) {
super.parseJSON(jsonObject);
final Integer width = JSONFunctions.getIntElement(jsonObject, "width");
final Integer maxCharacters = JSONFunctions.getIntElement(jsonObject, "maxCharacters");
final Color caretForegroundColor = super.loadColorFromJSON((JSONArray) jsonObject.get("caretForegroundColor"));
final Color caretBackgroundColor = super.loadColorFromJSON((JSONArray) jsonObject.get("caretBackgroundColor"));
final Color foregroundColor = super.loadColorFromJSON((JSONArray) jsonObject.get("foregroundColor"));
final Color backgroundColor = super.loadColorFromJSON((JSONArray) jsonObject.get("backgroundColor"));
final Boolean editable = (Boolean) jsonObject.get("editable");
final Boolean homeKeyEnabled = (Boolean) jsonObject.get("homeKeyEnabled");
final Boolean endKeyEnabled = (Boolean) jsonObject.get("endKeyEnabled");
final Boolean deleteKeyEnabled = (Boolean) jsonObject.get("deleteKeyEnabled");
final Boolean leftArrowKeyEnabled = (Boolean) jsonObject.get("leftArrowKeyEnabled");
final Boolean rightArrowKeyEnabled = (Boolean) jsonObject.get("rightArrowKeyEnabled");
final Boolean backSpaceKeyEnabled = (Boolean) jsonObject.get("backSpaceKeyEnabled");
final String allowedCharacterPattern = (String) jsonObject.get("allowedCharacterPattern");
if (width != null) {
this.width = width;
}
if (maxCharacters != null) {
this.maxCharacters = maxCharacters;
}
if (caretForegroundColor != null) {
this.caretForegroundColor = caretForegroundColor;
}
if (caretBackgroundColor != null) {
this.caretBackgroundColor = caretBackgroundColor;
}
if (foregroundColor != null) {
this.foregroundColor = foregroundColor;
}
if (backSpaceKeyEnabled != null) {
this.backgroundColor = backgroundColor;
}
if (editable != null) {
this.editable = editable;
}
if (homeKeyEnabled != null) {
this.homeKeyEnabled = homeKeyEnabled;
}
if (endKeyEnabled != null) {
this.endKeyEnabled = endKeyEnabled;
}
if (deleteKeyEnabled != null) {
this.deleteKeyEnabled = deleteKeyEnabled;
}
if (leftArrowKeyEnabled != null) {
this.leftArrowKeyEnabled = leftArrowKeyEnabled;
}
if (rightArrowKeyEnabled != null) {
this.rightArrowKeyEnabled = rightArrowKeyEnabled;
}
if (allowedCharacterPattern != null) {
this.allowedCharacterPattern = Pattern.compile(allowedCharacterPattern);
}
}
} |
/*
* SBitAlignment
*/
package net.maizegenetics.pal.alignment;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.maizegenetics.pal.ids.IdGroup;
import net.maizegenetics.pal.ids.SimpleIdGroup;
import net.maizegenetics.util.BitSet;
import net.maizegenetics.util.OpenBitSet;
import net.maizegenetics.util.UnmodifiableBitSet;
/**
* This data alignment is optimized for operations
* involving lots of SNPs from a taxon - imputation, genetic distance, kinship, diversity, etc.
* It is not optimized for LD or association mapping.
*
* @author terry
*/
public class SBitAlignment extends AbstractAlignment {
private OpenBitSet[][] myData;
private int myNumDataRows;
protected SBitAlignment(Alignment a, int maxNumAlleles, boolean retainRareAlleles) {
super(a, maxNumAlleles, retainRareAlleles);
long currentTime = System.currentTimeMillis();
loadAlleles(a);
long prevTime = currentTime;
currentTime = System.currentTimeMillis();
System.out.println("Time to load alleles: " + ((currentTime - prevTime) / 1000));
}
protected SBitAlignment(IdGroup idGroup, byte[][] data, GeneticMap map, byte[] reference, String[][] alleleStates, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
super(idGroup, data, map, reference, alleleStates, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
long currentTime = System.currentTimeMillis();
loadAlleles(data);
long prevTime = currentTime;
currentTime = System.currentTimeMillis();
System.out.println("Time to load alleles: " + ((currentTime - prevTime) / 1000));
}
// TESTING ONLY
public static SBitAlignment getInstance() {
int numTaxa = 11321;
int numSites = 72425;
String[] ids = new String[numTaxa];
for (int i = 0; i < numTaxa; i++) {
ids[i] = "Taxa" + i;
}
IdGroup idGroup = new SimpleIdGroup(ids);
byte[][] data = new byte[numTaxa][numSites];
Random random = new Random();
for (int t = 0; t < numTaxa; t++) {
for (int s = 0; s < numSites; s++) {
byte temp = (byte) random.nextInt(6);
byte value = (byte) ((temp << 4) | temp);
data[t][s] = value;
}
}
int[] variableSites = new int[numSites];
String[] snpIDs = new String[numSites];
for (int i = 0; i < numSites; i++) {
variableSites[i] = i;
snpIDs[i] = "SNPID_" + i;
}
return SBitAlignment.getNucleotideInstance(idGroup, data, null, null, variableSites, Alignment.DEFAULT_MAX_NUM_ALLELES, new Locus[]{new Locus("10", "10", 0, 0, null, null)}, new int[]{0}, snpIDs, true);
}
public static SBitAlignment getInstance(Alignment a) {
return SBitAlignment.getInstance(a, a.getMaxNumAlleles(), a.retainsRareAlleles());
}
public static SBitAlignment getInstance(Alignment a, int maxNumAlleles, boolean retainRareAlleles) {
if ((a instanceof SBitAlignment) && (a.getMaxNumAlleles() == maxNumAlleles) && (a.retainsRareAlleles() == retainRareAlleles)) {
return (SBitAlignment) a;
}
String[][] alleleStates = a.getAlleleEncodings();
if ((alleleStates == null) || (alleleStates.length == 0)) {
throw new IllegalStateException("SBitAlignment: init: allele states should not be empty.");
}
if ((a instanceof SBitNucleotideAlignment) || (a instanceof TBitNucleotideAlignment)) {
return new SBitNucleotideAlignment(a, maxNumAlleles, retainRareAlleles);
} else if (alleleStates.length == 1) {
return new SBitAlignment(a, maxNumAlleles, retainRareAlleles);
} else {
return new SBitTextAlignment(a, maxNumAlleles, retainRareAlleles);
}
}
public static SBitAlignment getInstance(IdGroup idGroup, byte[][] data, GeneticMap map, byte[] reference, String[][] alleleStates, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
if ((alleleStates == null) || (alleleStates.length == 0)) {
throw new IllegalArgumentException("SBitAlignment: init: allele states can not be empty.");
}
if (alleleStates.length == 1) {
return new SBitAlignment(idGroup, data, map, reference, alleleStates, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
} else {
return new SBitTextAlignment(idGroup, data, map, reference, alleleStates, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
}
}
public static SBitAlignment getNucleotideInstance(IdGroup idGroup, byte[][] data, GeneticMap map, byte[] reference, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
return new SBitNucleotideAlignment(idGroup, data, map, reference, NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
}
public static SBitAlignment getNucleotideInstance(IdGroup idGroup, String[][] data, GeneticMap map, byte[] reference, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
if ((maxNumAlleles < 1) || (maxNumAlleles > NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES)) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: max number of alleles must be between 1 and 14 inclusive: " + maxNumAlleles);
}
if ((data == null) || (data.length == 0)) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: data can not be empty.");
}
if (data.length != idGroup.getIdCount()) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: data rows not equal to number of identifers.");
}
byte[][] dataBytes = AlignmentUtils.getDataBytes(data, NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES, NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES);
return SBitAlignment.getNucleotideInstance(idGroup, dataBytes, map, reference, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
}
public static SBitAlignment getNucleotideInstance(IdGroup idGroup, String[] data, GeneticMap map, byte[] reference, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
if ((maxNumAlleles < 1) || (maxNumAlleles > NucleotideAlignmentConstants.NUMBER_NUCLEOTIDE_ALLELES)) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: max number of alleles must be between 1 and 14 inclusive: " + maxNumAlleles);
}
if ((data == null) || (data.length == 0)) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: data can not be empty.");
}
if (data.length != idGroup.getIdCount()) {
throw new IllegalArgumentException("SBitAlignment: getNucleotideInstance: data rows not equal to number of identifers.");
}
byte[][] dataBytes = AlignmentUtils.getDataBytes(data);
return SBitAlignment.getNucleotideInstance(idGroup, dataBytes, map, reference, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
}
public static SBitAlignment getInstance(IdGroup idGroup, String[][] data, GeneticMap map, byte[] reference, int[] variableSites, int maxNumAlleles, Locus[] loci, int[] lociOffsets, String[] snpIDs, boolean retainRareAlleles) {
if ((maxNumAlleles < 1) || (maxNumAlleles > 14)) {
throw new IllegalArgumentException("SBitAlignment: getInstance: max number of alleles must be between 1 and 14 inclusive: " + maxNumAlleles);
}
if ((data == null) || (data.length == 0)) {
throw new IllegalArgumentException("SBitAlignment: getInstance: data can not be empty.");
}
if (data.length != idGroup.getIdCount()) {
throw new IllegalArgumentException("SBitAlignment: getInstance: data rows not equal to number of identifers.");
}
String[][] alleleStates = AlignmentUtils.getAlleleStates(data, maxNumAlleles);
byte[][] dataBytes = AlignmentUtils.getDataBytes(data, alleleStates, maxNumAlleles);
return SBitAlignment.getInstance(idGroup, dataBytes, map, reference, alleleStates, variableSites, maxNumAlleles, loci, lociOffsets, snpIDs, retainRareAlleles);
}
private void loadAlleles(byte[][] data) {
myNumDataRows = myMaxNumAlleles;
if (retainsRareAlleles()) {
myNumDataRows++;
}
int numSeqs = getSequenceCount();
myData = new OpenBitSet[myNumDataRows][myNumSites];
for (int al = 0; al < myNumDataRows; al++) {
for (int s = 0; s < myNumSites; s++) {
myData[al][s] = new OpenBitSet(numSeqs);
}
}
//byte[] cb = new byte[2];
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int s = 0; s < myNumSites; s++) {
pool.execute(new ProcessSite(data, myData, s));
/*
for (int t = 0; t < numSeqs; t++) {
cb[0] = (byte) ((data[t][s] >>> 4) & 0xf);
cb[1] = (byte) (data[t][s] & 0xf);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
boolean isRare = true;
for (int j = 0; j < myMaxNumAlleles; j++) {
if (cb[i] == myAlleles[s][j]) {
myData[j][s].fastSet(t);
isRare = false;
break;
}
}
if (isRare && retainsRareAlleles()) {
myData[myMaxNumAlleles][s].fastSet(t);
}
}
}
}
*/
}
try {
pool.shutdown();
if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
throw new IllegalStateException("ImportUtils: readFromHapmap: processing threads timed out.");
}
} catch (Exception e) {
throw new IllegalStateException("ImportUtils: readFromHapmap: processing threads problem.");
}
}
private class ProcessSite implements Runnable {
private OpenBitSet[][] myData;
private byte[][] myOrigData;
private int mySite;
public ProcessSite(byte[][] origData, OpenBitSet[][] data, int site) {
myData = data;
myOrigData = origData;
mySite = site;
}
public void run() {
int numSeqs = getSequenceCount();
byte[] cb = new byte[2];
for (int t = 0; t < numSeqs; t++) {
cb[0] = (byte) ((myOrigData[t][mySite] >>> 4) & 0xf);
cb[1] = (byte) (myOrigData[t][mySite] & 0xf);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
boolean isRare = true;
for (int j = 0; j < myMaxNumAlleles; j++) {
if (cb[i] == myAlleles[mySite][j]) {
myData[j][mySite].fastSet(t);
isRare = false;
break;
}
}
if (isRare && retainsRareAlleles()) {
myData[myMaxNumAlleles][mySite].fastSet(t);
}
}
}
}
}
}
private void loadAlleles(Alignment a) {
myNumDataRows = myMaxNumAlleles;
if (retainsRareAlleles()) {
myNumDataRows++;
}
int numSeqs = getSequenceCount();
myData = new OpenBitSet[myNumDataRows][myNumSites];
for (int al = 0; al < myNumDataRows; al++) {
for (int s = 0; s < myNumSites; s++) {
myData[al][s] = new OpenBitSet(numSeqs);
}
}
for (int s = 0; s < myNumSites; s++) {
for (int t = 0; t < numSeqs; t++) {
byte[] cb = a.getBaseArray(t, s);
for (int i = 0; i < 2; i++) {
if (cb[i] != Alignment.UNKNOWN_ALLELE) {
boolean isRare = true;
for (int j = 0; j < myMaxNumAlleles; j++) {
if (cb[i] == myAlleles[s][j]) {
myData[j][s].fastSet(t);
isRare = false;
break;
}
}
if (isRare && retainsRareAlleles()) {
myData[myMaxNumAlleles][s].fastSet(t);
}
}
}
}
}
}
@Override
public byte getBase(int taxon, int site) {
byte[] temp = getBaseArray(taxon, site);
return (byte) ((temp[0] << 4) | temp[1]);
}
@Override
public byte[] getBaseArray(int taxon, int site) {
byte[] result = new byte[2];
result[0] = Alignment.UNKNOWN_ALLELE;
result[1] = Alignment.UNKNOWN_ALLELE;
try {
int count = 0;
for (int i = 0; i < myMaxNumAlleles; i++) {
if (myData[i][site].fastGet(taxon)) {
if (count == 0) {
result[1] = myAlleles[site][i];
}
result[count++] = myAlleles[site][i];
}
}
// Check For Rare Allele
if (retainsRareAlleles() && myData[myMaxNumAlleles][site].fastGet(taxon)) {
if (count == 0) {
result[1] = Alignment.RARE_ALLELE;
}
result[count] = Alignment.RARE_ALLELE;
}
} catch (IndexOutOfBoundsException e) {
throw new IllegalStateException("SBitAlignment: getBaseArray: bit sets indicate more than two alleles for taxon: " + taxon + " site: " + site);
}
return result;
}
@Override
public BitSet getAllelePresenceForAllTaxa(int site, int alleleNumber) {
return UnmodifiableBitSet.getInstance(myData[alleleNumber][site]);
}
@Override
public int getTotalGametesNotMissing(int site) {
OpenBitSet temp = new OpenBitSet(getSequenceCount());
for (int i = 0; i < myNumDataRows; i++) {
temp.or(myData[i][site]);
}
return ((int) temp.cardinality()) * 2;
}
@Override
public int getMinorAlleleCount(int site) {
OpenBitSet temp = new OpenBitSet(getSequenceCount());
for (int i = 0; i < myNumDataRows; i++) {
if (i != 1) {
temp.or(myData[i][site]);
}
}
temp.flip(0, temp.size());
temp.and(myData[1][site]);
return (int) temp.cardinality() + (int) myData[1][site].cardinality();
}
@Override
public double getMinorAlleleFrequency(int site) {
int minorAlleleCount = getMinorAlleleCount(site);
if (minorAlleleCount == 0) {
return 0.0;
}
return (double) minorAlleleCount / (double) getTotalGametesNotMissing(site);
}
@Override
public int getMajorAlleleCount(int site) {
OpenBitSet temp = new OpenBitSet(getSequenceCount());
for (int i = 1; i < myNumDataRows; i++) {
temp.or(myData[i][site]);
}
temp.flip(0, temp.size());
temp.and(myData[0][site]);
return (int) temp.cardinality() + (int) myData[0][site].cardinality();
}
@Override
public boolean isHeterozygous(int taxon, int site) {
int count = 0;
for (int i = 0; i < myNumDataRows; i++) {
if (myData[i][site].fastGet(taxon)) {
count++;
if (count == 2) {
return true;
}
}
}
return false;
}
@Override
public Map<String, Integer> getDiploidCounts() {
if (myAlleleStates.length != 1) {
return super.getDiploidCounts();
}
int[][] counts = new int[16][16];
for (int site = 0; site < myNumSites; site++) {
for (int i = 0; i < myMaxNumAlleles; i++) {
byte indexI = myAlleles[site][i];
counts[indexI][indexI] += (int) myData[i][site].cardinality();
for (int j = i + 1; j < myMaxNumAlleles; j++) {
byte indexJ = myAlleles[site][j];
int ijHet = (int) OpenBitSet.intersectionCount(myData[i][site], myData[j][site]);
if (indexI < indexJ) {
counts[indexI][indexJ] += ijHet;
} else {
counts[indexJ][indexI] += ijHet;
}
counts[indexI][indexI] -= ijHet;
counts[indexJ][indexJ] -= ijHet;
}
}
}
int unknownCount = getSequenceCount() * myNumSites;
Map<String, Integer> result = new HashMap<String, Integer>();
for (byte x = 0; x < 16; x++) {
for (byte y = x; y < 16; y++) {
if (counts[x][y] != 0) {
byte value = (byte) ((x << 4) | y);
result.put(getDiploidAsString(0, value), counts[x][y]);
unknownCount -= counts[x][y];
}
}
}
result.put(getDiploidAsString(0, UNKNOWN_DIPLOID_ALLELE), unknownCount);
return result;
}
@Override
public int[][] getAllelesSortedByFrequency(int site) {
int[] counts = new int[16];
for (int i = 0; i < myNumDataRows; i++) {
byte indexI;
if ((retainsRareAlleles()) && (i == myMaxNumAlleles)) {
indexI = Alignment.RARE_ALLELE;
} else {
indexI = myAlleles[site][i];
}
counts[indexI] += (int) myData[i][site].cardinality() * 2;
for (int j = i + 1; j < myNumDataRows; j++) {
byte indexJ;
if ((retainsRareAlleles()) && (j == myMaxNumAlleles)) {
indexJ = Alignment.RARE_ALLELE;
} else {
indexJ = myAlleles[site][j];
}
int ijHet = (int) OpenBitSet.intersectionCount(myData[i][site], myData[j][site]);
counts[indexI] -= ijHet;
counts[indexJ] -= ijHet;
}
}
int numAlleles = 0;
for (byte x = 0; x < Alignment.UNKNOWN_ALLELE; x++) {
if (counts[x] != 0) {
numAlleles++;
}
}
int current = 0;
int[][] result = new int[2][numAlleles];
for (byte x = 0; x < 15; x++) {
if (counts[x] != 0) {
result[0][current] = x;
result[1][current++] = counts[x];
}
}
boolean change = true;
while (change) {
change = false;
for (int k = 0; k < numAlleles - 1; k++) {
if (result[1][k] < result[1][k + 1]) {
int temp = result[0][k];
result[0][k] = result[0][k + 1];
result[0][k + 1] = temp;
int tempCount = result[1][k];
result[1][k] = result[1][k + 1];
result[1][k + 1] = tempCount;
change = true;
}
}
}
return result;
}
} |
package net.mcft.copy.betterstorage.item;
import java.util.List;
import net.mcft.copy.betterstorage.Config;
import net.mcft.copy.betterstorage.block.tileentity.TileEntityBackpack;
import net.mcft.copy.betterstorage.client.model.ModelBackpackArmor;
import net.mcft.copy.betterstorage.container.ContainerBetterStorage;
import net.mcft.copy.betterstorage.container.SlotArmorBackpack;
import net.mcft.copy.betterstorage.inventory.InventoryBackpackEquipped;
import net.mcft.copy.betterstorage.inventory.InventoryStacks;
import net.mcft.copy.betterstorage.misc.Constants;
import net.mcft.copy.betterstorage.misc.CurrentItem;
import net.mcft.copy.betterstorage.misc.PropertiesBackpack;
import net.mcft.copy.betterstorage.misc.Resources;
import net.mcft.copy.betterstorage.misc.handlers.KeyBindingHandler;
import net.mcft.copy.betterstorage.misc.handlers.PacketHandler;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.mcft.copy.betterstorage.utils.EntityUtils;
import net.mcft.copy.betterstorage.utils.LanguageUtils;
import net.mcft.copy.betterstorage.utils.PlayerUtils;
import net.mcft.copy.betterstorage.utils.RandomUtils;
import net.mcft.copy.betterstorage.utils.StackUtils;
import net.mcft.copy.betterstorage.utils.WorldUtils;
import net.minecraft.block.Block;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet103SetSlot;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
import net.minecraftforge.common.EnumHelper;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.ISpecialArmor;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemBackpack extends ItemArmor implements ISpecialArmor {
public static final EnumArmorMaterial material = EnumHelper.addArmorMaterial(
"backpack", 240, new int[]{ 0, 2, 0, 0 }, 15);
protected ItemBackpack(int id, EnumArmorMaterial material) {
super(id - 256, material, 0, 1);
}
public ItemBackpack(int id) {
this(id, EnumArmorMaterial.CLOTH);
setMaxDamage(240);
}
public String getName() { return Constants.containerBackpack; }
/** Returns the number of columns this backpack has. */
public int getColumns() { return 9; }
/** Returns the number of rows this backpack has. */
public int getRows() { return Config.backpackRows; }
protected IInventory getBackpackItemsInternal(EntityLivingBase carrier, EntityPlayer player) {
PropertiesBackpack backpackData = getBackpackData(carrier);
if (backpackData.contents == null)
backpackData.contents = new ItemStack[getColumns() * getRows()];
return new InventoryStacks(getName(), backpackData.contents);
}
public boolean canTake(PropertiesBackpack backpackData, ItemStack backpack) { return true; }
public boolean containsItems(PropertiesBackpack backpackData) {
return (backpackData.hasItems || ((backpackData.contents != null) && !StackUtils.isEmpty(backpackData.contents)));
}
// Item stuff
@Override
@SideOnly(Side.CLIENT)
public int getSpriteNumber() { return 0; }
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister iconRegister) { }
@Override
public String getUnlocalizedName() { return Block.blocksList[itemID].getUnlocalizedName(); }
@Override
public String getUnlocalizedName(ItemStack stack) { return getUnlocalizedName(); }
@Override
@SideOnly(Side.CLIENT)
public CreativeTabs getCreativeTab() { return Block.blocksList[itemID].getCreativeTabToDisplayOn(); }
@Override
public boolean isValidArmor(ItemStack stack, int armorType, Entity entity) { return false; }
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entity, ItemStack stack, int slot) {
return ModelBackpackArmor.instance;
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) {
return ((type == "overlay") ? Resources.backpackOverlayTexture : Resources.backpackTexture).toString();
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) {
if (getBackpack(player) == stack) {
PropertiesBackpack backpackData = getBackpackData(player);
boolean containsItems = containsItems(backpackData);
String reason = LanguageUtils.translateTooltip("backpack.containsItems");
if (ItemBackpack.isBackpackOpen(player)) {
if (containsItems) list.add(reason);
LanguageUtils.translateTooltip(list, "backpack.used");
} else if (containsItems)
LanguageUtils.translateTooltip(list, "backpack.unequipHint", "%REASON%", reason);
if (KeyBindingHandler.serverBackpackKeyEnabled) {
String str = GameSettings.getKeyDisplayString(Config.backpackOpenKey);
LanguageUtils.translateTooltip(list, "backpack.openHint", "%KEY%", str);
}
} else LanguageUtils.translateTooltip(list, "backpack.equipHint");
}
@Override
public void onArmorTickUpdate(World world, EntityPlayer player, ItemStack itemStack) {
// Replace the armor slot with a custom one, so the player
// can't unequip the backpack when there's items inside.
int index = 5 + armorType;
Slot slotBefore = player.inventoryContainer.getSlot(index);
if (slotBefore instanceof SlotArmorBackpack) return;
int slotIndex = player.inventory.getSizeInventory() - getChestSlotOffset(player) - armorType;
SlotArmorBackpack slot = new SlotArmorBackpack(player.inventory, slotIndex, 8, 8 + armorType * 18);
slot.slotNumber = index;
player.inventoryContainer.inventorySlots.set(index, slot);
}
// For compatibility with Galacticraft.
private int getChestSlotOffset(EntityPlayer player) {
return isExact(player.inventory, "micdoodle8.mods.galacticraft.core.inventory.GCCoreInventoryPlayer") ? 6 : 1;
}
private static boolean isExact(Object obj, String str) {
try { return obj.getClass().getName().equals(str); }
catch (Exception e) { return false; }
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) { return stack; }
@Override
public boolean onItemUse(ItemStack stack, EntityPlayer player,
World world, int x, int y, int z, int side,
float hitX, float hitY, float hitZ) {
ForgeDirection orientation = DirectionUtils.getOrientation(player).getOpposite();
return placeBackpack(player, player, stack, x, y, z, side, orientation);
}
// ISpecialArmor implementation
@Override
public ArmorProperties getProperties(EntityLivingBase entity, ItemStack armor,
DamageSource source, double damage, int slot) {
return new ArmorProperties(0, 2 / 25.0, armor.getMaxDamage() + 1 - armor.getItemDamage());
}
@Override
public int getArmorDisplay(EntityPlayer player, ItemStack armor, int slot) { return 2; }
@Override
public void damageArmor(EntityLivingBase entity, ItemStack stack,
DamageSource source, int damage, int slot) {
if (!takesDamage(stack, source)) return;
stack.damageItem(damage, entity);
if (stack.stackSize > 0) return;
PropertiesBackpack backpackData = ItemBackpack.getBackpackData(entity);
if (backpackData.contents != null)
for (ItemStack s : backpackData.contents)
WorldUtils.dropStackFromEntity(entity, s, 2.0F);
entity.renderBrokenItemStack(stack);
}
private static final String[] immuneToDamageType = {
"inWall", "drown", "starve", "catcus", "fall", "outOfWorld",
"generic", "wither", "anvil", "fallingBlock", "thrown"
};
protected boolean takesDamage(ItemStack stack, DamageSource source) {
// Backpacks don't get damaged from certain
// damage types (see above) and magic damage.
if (source.isMagicDamage()) return false;
for (String immune : immuneToDamageType)
if (immune == source.getDamageType()) return false;
// Protection enchantments protect the backpack
// from taking damage from that damage type.
return (!enchantmentProtection(stack, Enchantment.protection, 0.3, 0.35, 0.4, 0.45) &&
!(source.isProjectile() && enchantmentProtection(stack, Enchantment.projectileProtection, 0.4, 0.5, 0.6, 0.7)) &&
!(source.isFireDamage() && enchantmentProtection(stack, Enchantment.fireProtection, 0.55, 0.65, 0.75, 0.85)) &&
!(source.isExplosion() && enchantmentProtection(stack, Enchantment.blastProtection, 0.65, 0.75, 0.85, 0.95)));
}
private boolean enchantmentProtection(ItemStack stack, Enchantment ench, double... chance) {
int level = EnchantmentHelper.getEnchantmentLevel(ench.effectId, stack);
level = Math.min(level - 1, chance.length - 1);
return ((level >= 0) && RandomUtils.getBoolean(chance[level]));
}
// Helper functions
public static ItemStack getBackpack(EntityLivingBase entity) {
ItemStack backpack = entity.getCurrentItemOrArmor(CurrentItem.CHEST);
if ((backpack != null) &&
(backpack.getItem() instanceof ItemBackpack)) return backpack;
else return null;
}
public static void setBackpack(EntityLivingBase entity, ItemStack backpack, ItemStack[] contents) {
entity.setCurrentItemOrArmor(3, backpack);
PropertiesBackpack backpackData = getBackpackData(entity);
backpackData.contents = contents;
ItemBackpack.updateHasItems(entity, backpackData);
}
public static void removeBackpack(EntityLivingBase entity) {
setBackpack(entity, null, null);
}
public static IInventory getBackpackItems(EntityLivingBase carrier, EntityPlayer player) {
ItemStack backpack = getBackpack(carrier);
if (backpack == null) return null;
return ((ItemBackpack)backpack.getItem()).getBackpackItemsInternal(carrier, player);
}
public static IInventory getBackpackItems(EntityLivingBase carrier) {
return getBackpackItems(carrier, null);
}
public static void initBackpackData(EntityLivingBase entity) {
EntityUtils.createProperties(entity, PropertiesBackpack.class);
}
public static PropertiesBackpack getBackpackData(EntityLivingBase entity) {
PropertiesBackpack backpackData = EntityUtils.getOrCreateProperties(entity, PropertiesBackpack.class);
if (!backpackData.initialized) {
ItemBackpack.initBackpackOpen(entity);
updateHasItems(entity, backpackData);
backpackData.initialized = true;
}
return backpackData;
}
public static void updateHasItems(EntityLivingBase entity, PropertiesBackpack backpackData) {
if (entity.worldObj.isRemote || !(entity instanceof EntityPlayer)) return;
EntityPlayer player = (EntityPlayer)entity;
boolean hasItems = ((backpackData.contents != null) && !StackUtils.isEmpty(backpackData.contents));
if (backpackData.hasItems == hasItems) return;
Packet packet = PacketHandler.makePacket(PacketHandler.backpackHasItems, hasItems);
PacketDispatcher.sendPacketToPlayer(packet, (Player)player);
backpackData.hasItems = hasItems;
}
public static void initBackpackOpen(EntityLivingBase entity) {
entity.getDataWatcher().addObject(Config.backpackOpenDataWatcherId, (byte)0);
}
public static void setBackpackOpen(EntityLivingBase entity, boolean isOpen) {
entity.getDataWatcher().updateObject(Config.backpackOpenDataWatcherId, (byte)(isOpen ? 1 : 0));
}
public static boolean isBackpackOpen(EntityLivingBase entity) {
return (entity.getDataWatcher().getWatchableObjectByte(Config.backpackOpenDataWatcherId) != 0);
}
/** Opens the carrier's equipped backpack for the player. */
public static void openBackpack(EntityPlayer player, EntityLivingBase carrier) {
ItemStack backpack = ItemBackpack.getBackpack(carrier);
if (backpack == null) return;
ItemBackpack backpackType = (ItemBackpack)backpack.getItem();
IInventory inventory = ItemBackpack.getBackpackItems(carrier, player);
inventory = new InventoryBackpackEquipped(carrier, player, inventory);
if (!inventory.isUseableByPlayer(player)) return;
int columns = backpackType.getColumns();
int rows = backpackType.getRows();
Container container = new ContainerBetterStorage(player, inventory, columns, rows);
String title = StackUtils.get(backpack, "", "display", "Name");
PlayerUtils.openGui(player, inventory.getInvName(), columns, rows, title, container);
}
/** Places an equipped backpack when the player right clicks
* on the ground while sneaking and holding nothing. */
public static boolean onPlaceBackpack(EntityPlayer player, int x, int y, int z, int side) {
if (player.getCurrentEquippedItem() != null || !player.isSneaking()) return false;
ItemStack backpack = ItemBackpack.getBackpack(player);
if (backpack == null) return false;
if (!ItemBackpack.isBackpackOpen(player)) {
// Try to place the backpack as if it was being held and used by the player.
backpack.getItem().onItemUse(backpack, player, player.worldObj, x, y, z, side, 0, 0, 0);
if (backpack.stackSize <= 0) backpack = null;
}
// Send set slot packet to for the chest slot to make
// sure the client has the same information as the server.
// This is especially important when there's a large delay, the
// client might think it placed the backpack, but server didn't.
if (!player.worldObj.isRemote)
PacketDispatcher.sendPacketToPlayer(new Packet103SetSlot(0, 6, backpack), (Player)player);
boolean success = (backpack == null);
if (success) player.swingItem();
return success;
}
public static boolean placeBackpack(EntityLivingBase carrier, EntityPlayer player, ItemStack backpack, int x, int y, int z, int side, ForgeDirection orientation) {
if (backpack.stackSize == 0) return false;
World world = carrier.worldObj;
Block blockBackpack = Block.blocksList[backpack.itemID];
// If a replacable block was clicked, move on.
// Otherwise, check if the top side was clicked and adjust the position.
if (!WorldUtils.isBlockReplacable(world, x, y, z)) {
if (side != 1) return false;
y++;
}
// Return false if there's block is too low or too high.
if ((y <= 0) || (y >= world.getHeight() - 1)) return false;
// Return false if not placed on top of a solid block.
Block blockBelow = Block.blocksList[world.getBlockId(x, y - 1, z)];
if ((blockBelow == null) || !blockBelow.isBlockSolidOnSide(world, x, y - 1, z, ForgeDirection.UP)) return false;
// Return false if the player can't edit the block.
if ((player != null) && !player.canPlayerEdit(x, y, z, side, backpack)) return false;
// Return false if there's an entity blocking the placement.
if (!world.canPlaceEntityOnSide(blockBackpack.blockID, x, y, z, false, side, carrier, backpack)) return false;
// Actually place the block in the world,
// play place sound and decrease stack size if successful.
if (!world.setBlock(x, y, z, blockBackpack.blockID, orientation.ordinal(), 3))
return false;
if (world.getBlockId(x, y, z) != blockBackpack.blockID)
return false;
blockBackpack.onBlockPlacedBy(world, x, y, z, carrier, backpack);
blockBackpack.onPostBlockPlaced(world, x, y, z, orientation.ordinal());
TileEntityBackpack te = WorldUtils.get(world, x, y, z, TileEntityBackpack.class);
te.stack = backpack.copy();
if (ItemBackpack.getBackpack(carrier) == backpack)
te.unequip(carrier);
String sound = blockBackpack.stepSound.getPlaceSound();
float volume = (blockBackpack.stepSound.getVolume() + 1.0F) / 2.0F;
float pitch = blockBackpack.stepSound.getPitch() * 0.8F;
world.playSoundEffect(x + 0.5, y + 0.5, z + 0.5F, sound, volume, pitch);
backpack.stackSize
return true;
}
} |
package net.sf.jaer.eventio.ros;
import com.github.swrirobotics.bags.reader.BagFile;
import com.github.swrirobotics.bags.reader.BagReader;
import com.github.swrirobotics.bags.reader.TopicInfo;
import com.github.swrirobotics.bags.reader.exceptions.BagReaderException;
import com.github.swrirobotics.bags.reader.exceptions.UninitializedFieldException;
import com.github.swrirobotics.bags.reader.messages.serialization.ArrayType;
import com.github.swrirobotics.bags.reader.messages.serialization.BoolType;
import com.github.swrirobotics.bags.reader.messages.serialization.Field;
import com.github.swrirobotics.bags.reader.messages.serialization.Float32Type;
import com.github.swrirobotics.bags.reader.messages.serialization.Float64Type;
import com.github.swrirobotics.bags.reader.messages.serialization.Int32Type;
import com.github.swrirobotics.bags.reader.messages.serialization.MessageType;
import com.github.swrirobotics.bags.reader.messages.serialization.TimeType;
import com.github.swrirobotics.bags.reader.messages.serialization.UInt16Type;
import com.github.swrirobotics.bags.reader.messages.serialization.UInt32Type;
import com.google.common.collect.HashMultimap;
import eu.seebetter.ini.chips.davis.DavisBaseCamera;
import eu.seebetter.ini.chips.davis.imu.IMUSample;
import eu.seebetter.ini.chips.davis.imu.IMUSampleType;
import java.awt.Point;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.FileChannel;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ProgressMonitor;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEFileInputStreamInterface;
import net.sf.jaer.eventio.AEInputStream;
import org.apache.commons.lang3.mutable.MutableBoolean;
public class RosbagFileInputStream implements AEFileInputStreamInterface, RosbagTopicMessageSupport {
private static final Logger log = Logger.getLogger("RosbagFileInputStream");
private final PropertyChangeSupport support = new PropertyChangeSupport(this);
/**
* File name extension for ROS bag files, excluding ".", i.e. "bag". Note
* this lack of . is different than for AEDataFile.DATA_FILE_EXTENSION.
*/
public static final String DATA_FILE_EXTENSION = "bag";
// for converting ROS units to jAER units
private static final float DEG_PER_RAD = 180f / (float) Math.PI, G_PER_MPS2 = 1 / 9.8f;
/**
* The AEChip object associated with this stream. This field was added for
* supported jAER 3.0 format files to support translating bit locations in
* events.
*/
private AEChip chip = null;
private File file = null;
BagFile bagFile = null;
// the most recently read event timestamp, the first one in file, and the last one in file
private int mostRecentTimestamp, largestTimestamp = Integer.MIN_VALUE;
private long firstTimestamp, lastTimestamp;
private long firstTimestampUsAbsolute; // the absolute (ROS) first timestamp in us
private boolean firstTimestampWasRead = false;
// marks the present read time for packets
private int currentStartTimestamp;
private final ApsDvsEventPacket<ApsDvsEvent> eventPacket;
private AEPacketRaw aePacketRawBuffered = new AEPacketRaw(), aePacketRawOutput = new AEPacketRaw(), aePacketRawTmp = new AEPacketRaw();
private AEPacketRaw emptyPacket = new AEPacketRaw();
private int nextMessageNumber = 0, numMessages = 0;
private long absoluteStartingTimeMs = 0; // in system time since 1970 in ms
/** The ZoneID of this file; for ROS bag files there is no recorded time zone so the zoneId is systemDefault() */
private ZoneId zoneId=ZoneId.systemDefault();
private FileChannel channel = null;
// private static final String[] TOPICS = {"/dvs/events"};\
private static final String RPG_TOPIC_HEADER = "/dvs/", MVSEC_TOPIC_HEADER = "/davis/left/"; // TODO arbitrarily choose left camera for MVSEC for now
private static final String TOPIC_EVENTS = "events", TOPIC_IMAGE = "image_raw", TOPIC_IMU = "imu", TOPIC_EXPOSURE = "exposure";
private static String[] STANARD_TOPICS = {TOPIC_EVENTS, TOPIC_IMAGE, TOPIC_IMU, TOPIC_EXPOSURE};
// private static String[] TOPICS = {TOPIC_HEADER + TOPIC_EVENTS, TOPIC_HEADER + TOPIC_IMAGE};
private ArrayList<String> topicList = new ArrayList();
private ArrayList<String> topicFieldNames = new ArrayList();
private boolean wasIndexed = false;
private List<BagFile.MessageIndex> msgIndexes = new ArrayList();
private HashMultimap<String, PropertyChangeListener> msgListeners = HashMultimap.create();
private boolean firstReadCompleted = false;
private ArrayList<String> extraTopics = null; // extra topics that listeners can subscribe to
private boolean nonMonotonicTimestampExceptionsChecked = true;
private boolean nonMonotonicTimestampDetected = false; // flag set by nonmonotonic timestamp if detection enabled
private boolean rewindFlag = false;
// FIFOs to buffer data so that we only let out data from any stream if there is definitely later data from both other streams
private MutableBoolean hasDvs = new MutableBoolean(false), hasAps = new MutableBoolean(false), hasImu = new MutableBoolean(false); // flags to say what data is in this stream
private long lastDvsTimestamp = 0, lastApsTimestamp = 0, lastImuTimestamp = 0; // used to check monotonicity
private AEFifo dvsFifo = new AEFifo(), apsFifo = new AEFifo(), imuFifo = new AEFifo();
private MutableBoolean[] hasDvsApsImu = {hasDvs, hasAps, hasImu};
private AEFifo[] aeFifos = {dvsFifo, apsFifo, imuFifo};
private int MAX_RAW_EVENTS_BUFFER_SIZE=1000000;
private enum RosbagFileType {
RPG(RPG_TOPIC_HEADER), MVSEC(MVSEC_TOPIC_HEADER), Unknown("???");
private String header;
private RosbagFileType(String header) {
this.header = header;
}
}
// two types of topics depending on format of rosbag
RosbagFileType rosbagFileType = RosbagFileType.Unknown;
/**
* Interval for logging warnings about nonmonotonic timestamps.
*/
public static final int NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL = 1000000;
private int nonmonotonicTimestampCounter = 0;
private int lastExposureUs; // holds last exposure value (in us?) to use for creating SOE and EOE events for frames
private int markIn = 0;
private int markOut;
private boolean repeatEnabled = true;
/**
* Makes a new instance for a file and chip. A progressMonitor can pop up a
* dialog for the long indexing operation
*
* @param f the file
* @param chip the AEChip
* @param progressMonitor an optional ProgressMonitor, set to null if not
* desired
* @throws BagReaderException
* @throws java.lang.InterruptedException if constructing the stream which
* requires indexing the topics takes a long time and the operation is
* canceled
*/
public RosbagFileInputStream(File f, AEChip chip, ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException {
this.eventPacket = new ApsDvsEventPacket<>(ApsDvsEvent.class);
setFile(f);
this.chip = chip;
log.info("reading rosbag file " + f + " for chip " + chip);
bagFile = BagReader.readFile(file);
StringBuilder sb = new StringBuilder("Bagfile information:\n");
for (TopicInfo topic : bagFile.getTopics()) {
sb.append(topic.getName() + " \t\t" + topic.getMessageCount()
+ " msgs \t: " + topic.getMessageType() + " \t"
+ (topic.getConnectionCount() > 1 ? ("(" + topic.getConnectionCount() + " connections)") : "")
+ "\n");
if (topic.getName().contains(RosbagFileType.MVSEC.header)) {
rosbagFileType = RosbagFileType.MVSEC;
} else if (topic.getName().contains(RosbagFileType.RPG.header)) {
rosbagFileType = RosbagFileType.RPG;
}
}
sb.append("Duration: " + bagFile.getDurationS() + "s\n");
sb.append("Chunks: " + bagFile.getChunks().size() + "\n");
sb.append("Num messages: " + bagFile.getMessageCount() + "\n");
sb.append("File type is detected as " + rosbagFileType);
log.info(sb.toString());
for (String s : STANARD_TOPICS) {
String topic = rosbagFileType.header + s;
topicList.add(topic);
topicFieldNames.add(topic.substring(topic.lastIndexOf("/") + 1)); // strip off header to get to field name for the ArrayType
}
generateMessageIndexes(progressMonitor);
}
@Override
public Collection<String> getMessageListenerTopics() {
return msgListeners.keySet();
}
// // causes huge memory usage by building hashmaps internally, using index instead by prescanning file
// private MsgIterator getMsgIterator() throws BagReaderException {
//// messages=bagFile.getMessages();
// conns = bagFile.getConnections();
// ArrayList<Connection> myConnections = new ArrayList();
// for (Connection conn : conns) {
// String topic = conn.getTopic();
//// log.info("connection "+conn+" has topic "+topic);
// for (String t : TOPICS) {
// if (t.equals(topic)) {
//// log.info("topic matches " + t + "; adding this connection to myConnections. This message has definition " + conn.getMessageDefinition());
// log.info("topic matches " + t + "; adding this connection to myConnections");
// myConnections.appendCopy(conn);
// chunkInfos = bagFile.getChunkInfos();
// try {
// channel = bagFile.getChannel();
// } catch (IOException ex) {
// Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
// throw new BagReaderException(ex.toString());
// MsgIterator itr = new MsgIterator(chunkInfos, myConnections, channel);
// return itr;
/**
* Adds information to a message from the index entry for it
*/
public class MessageWithIndex {
public MessageType messageType;
public BagFile.MessageIndex messageIndex;
public MessageWithIndex(MessageType messageType, BagFile.MessageIndex messageIndex) {
this.messageType = messageType;
this.messageIndex = messageIndex;
}
}
synchronized private MessageWithIndex getNextMsg() throws BagReaderException, EOFException {
MessageType msg = null;
if (nextMessageNumber == markOut) { // TODO check exceptions here for markOut set before markIn
getSupport().firePropertyChange(AEInputStream.EVENT_EOF, null, position());
if (isRepeat()) {
try {
rewind();
} catch (IOException ex) {
Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
throw new BagReaderException("on reaching markOut, got " + ex);
}
return getNextMsg();
} else {
return null;
}
}
try {
msg = bagFile.getMessageFromIndex(msgIndexes, nextMessageNumber);
} catch (ArrayIndexOutOfBoundsException e) {
throw new EOFException();
}
MessageWithIndex rtn = new MessageWithIndex(msg, msgIndexes.get(nextMessageNumber));
nextMessageNumber++;
return rtn;
}
/**
* Given ROS Timestamp, this method computes the us timestamp relative to
* the first timestamp in the recording
*
* @param timestamp a ROS Timestamp from a Message, either header or DVS
* event
* @param updateLargestTimestamp true if we want to update the largest
* timestamp with this value, false if we leave it unchanged
*
* @return timestamp for jAER in us
*/
private int getTimestampUsRelative(Timestamp timestamp, boolean updateLargestTimestamp) {
updateLargestTimestamp = true; // TODO hack before removing
long tsNs = timestamp.getNanos(); // gets the fractional seconds in ns
long tsMs = timestamp.getTime(); // the time in ms including ns, i.e. time(s)*1000+ns/1000000.
long timestampUsAbsolute = (1000000 * (tsMs / 1000)) + tsNs / 1000; // truncate ms back to s, then turn back to us, then appendCopy fractional part of s in us
if (!firstTimestampWasRead) {
firstTimestampUsAbsolute = timestampUsAbsolute;
firstTimestampWasRead = true;
}
int ts = (int) (timestampUsAbsolute - firstTimestampUsAbsolute);
// if (ts == 0) {
// log.warning("zero timestamp detected for Image ");
if (updateLargestTimestamp && ts > largestTimestamp) {
largestTimestamp = ts;
}
final int dt = ts - mostRecentTimestamp;
if (dt < 0 && nonMonotonicTimestampExceptionsChecked) {
if (nonmonotonicTimestampCounter % NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL == 0) {
log.warning("Nonmonotonic timestamp=" + timestamp + " with dt=" + dt + "; replacing with largest timestamp=" + largestTimestamp + "; skipping next " + NONMONOTONIC_TIMESTAMP_WARNING_INTERVAL + " warnings");
}
nonmonotonicTimestampCounter++;
ts = largestTimestamp; // replace actual timestamp with largest one so far
nonMonotonicTimestampDetected = true;
} else {
nonMonotonicTimestampDetected = false;
}
mostRecentTimestamp = ts;
return ts;
}
/**
* Typical file info about contents of a bag file recorded on Traxxas slash
* platform INFO: Bagfile information:
* /davis_ros_driver/parameter_descriptions 1 msgs :
* dynamic_reconfigure/ConfigDescription /davis_ros_driver/parameter_updates
* 1 msgs : dynamic_reconfigure/Config /dvs/events 8991 msgs :
* dvs_msgs/EventArray /dvs/exposure 4751 msgs : std_msgs/Int32
* /dvs/image_raw 4758 msgs : sensor_msgs/Image /dvs/imu 298706 msgs :
* sensor_msgs/Imu /dvs_accumulated_events 124 msgs : sensor_msgs/Image
* /dvs_accumulated_events_edges 124 msgs : sensor_msgs/Image /dvs_rendering
* 4034 msgs : sensor_msgs/Image /events_off_mean_1 186 msgs :
* std_msgs/Float32 /events_off_mean_5 56 msgs : std_msgs/Float32
* /events_on_mean_1 186 msgs : std_msgs/Float32 /events_on_mean_5 56 msgs :
* std_msgs/Float32 /raw_pwm 2996 msgs : rally_msgs/Pwm /rosout 12 msgs :
* rosgraph_msgs/Log (4 connections) /rosout_agg 12 msgs : rosgraph_msgs/Log
* duration: 299.578s Chunks: 0 Num messages: 324994
*/
/**
* Gets the next raw packet. The packets are buffered to ensure that all the
* data is monotonic in time.
*
* @return the packet
*/
synchronized private AEPacketRaw getNextRawPacket() throws EOFException, BagReaderException {
DavisBaseCamera davisCamera = null;
if (chip instanceof DavisBaseCamera) {
davisCamera = (DavisBaseCamera) chip;
}
OutputEventIterator<ApsDvsEvent> outItr = eventPacket.outputIterator(); // to hold output events
ApsDvsEvent e = new ApsDvsEvent();
try {
boolean gotEventsOrFrame = false;
while (!gotEventsOrFrame) {
MessageWithIndex message = getNextMsg();
// send to listeners if topic is one we have subscribers for
String topic = message.messageIndex.topic;
Set<PropertyChangeListener> listeners = msgListeners.get(topic);
if (!listeners.isEmpty()) {
for (PropertyChangeListener l : listeners) {
l.propertyChange(new PropertyChangeEvent(this, topic, null, message));
}
}
// now deal with standard DAVIS data
String pkg = message.messageType.getPackage();
String type = message.messageType.getType();
switch (pkg) {
case "std_msgs": { // exposure
MessageType messageType = message.messageType;
// List<String> fieldNames = messageType.getFieldNames();
try {
int exposureUs = messageType.<Int32Type>getField("data").getValue();
lastExposureUs = (int) (exposureUs);
} catch (Exception ex) {
float exposureUs = messageType.<Float32Type>getField("data").getValue();
lastExposureUs = (int) (exposureUs); // hack to deal with recordings made with pre-Int32 version of rpg-ros-dvs
}
}
break;
case "sensor_msgs":
switch (type) {
case "Image": {
// Make sure the image is from APS, otherwise some other image topic will be also processed here.
if (!(topic.equalsIgnoreCase("/davis/left/image_raw") || topic.equalsIgnoreCase("/dvs/image_raw"))) {
continue;
}
hasAps.setTrue();
MessageType messageType = message.messageType;
// List<String> fieldNames = messageType.getFieldNames();
MessageType header = messageType.getField("header");
ArrayType data = messageType.<ArrayType>getField("data");
// int width = (int) (messageType.<UInt32Type>getField("width").getValue()).intValue();
// int height = (int) (messageType.<UInt32Type>getField("height").getValue()).intValue();
Timestamp timestamp = header.<TimeType>getField("stamp").getValue();
int ts = getTimestampUsRelative(timestamp, true); // don't update largest timestamp with frame time
gotEventsOrFrame = true;
byte[] bytes = data.getAsBytes();
final int sizey1 = chip.getSizeY() - 1, sizex = chip.getSizeX();
// construct frames as events, so that reconstuction as raw packet results in frame again.
// what a hack...
// start of frame
e.setReadoutType(ApsDvsEvent.ReadoutType.SOF);
e.x = (short) 0;
e.y = (short) 0;
e.setTimestamp(ts);
maybePushEvent(e, apsFifo, outItr);
// start of exposure
e.setReadoutType(ApsDvsEvent.ReadoutType.SOE);
e.x = (short) 0;
e.y = (short) 0;
e.setTimestamp(ts);
maybePushEvent(e, apsFifo, outItr);
Point firstPixel = new Point(0, 0), lastPixel = new Point(chip.getSizeX() - 1, chip.getSizeY() - 1);
if (davisCamera != null) {
firstPixel.setLocation(davisCamera.getApsFirstPixelReadOut());
lastPixel.setLocation(davisCamera.getApsLastPixelReadOut());
}
int xinc = firstPixel.x < lastPixel.x ? 1 : -1;
int yinc = firstPixel.y < lastPixel.y ? 1 : -1;
// see AEFrameChipRenderer for putting event streams into textures to be drawn,
// in particular AEFrameChipRenderer.renderApsDvsEvents
// and AEFrameChipRenderer.updateFrameBuffer for how cooked event stream is interpreted
// see ChipRendererDisplayMethodRGBA for OpenGL drawing of textures of frames
// see DavisBaseCamera.DavisEventExtractor for extraction of event stream
// See specific chip classes, e.g. Davis346mini for setup of first and last pixel adddresses for readout order of APS images
// The order is important because in AEFrameChipRenderer the frame buffer is cleared at the first
// pixel and copied to output after the last pixel, so the pixels must be written in correct order
// to the packet...
// Also, y is flipped for the rpg-dvs driver which is based on libcaer where the frame starts at
// upper left corner as in most computer vision,
// unlike jaer that starts like in cartesian coordinates at lower left.
for (int f = 0; f < 2; f++) { // reset/signal pixels samples
// now we start at
for (int y = firstPixel.y; (yinc > 0 ? y <= lastPixel.y : y >= lastPixel.y); y += yinc) {
for (int x = firstPixel.x; (xinc > 0 ? x <= lastPixel.x : x >= lastPixel.x); x += xinc) {
// above x and y are in jAER image space
final int yrpg = sizey1 - y; // flips y to get to rpg from jaer coordinates (jaer uses 0,0 as lower left, rpg-dvs uses 0,0 as upper left)
final int idx = yrpg * sizex + x;
e.setReadoutType(f == 0 ? ApsDvsEvent.ReadoutType.ResetRead : ApsDvsEvent.ReadoutType.SignalRead);
e.x = (short) x;
e.y = (short) y;
e.setAdcSample(f == 0 ? 255 : (255 - (0xff & bytes[idx])));
if (davisCamera == null) {
e.setTimestamp(ts);
} else {
if (davisCamera.lastFrameAddress((short) x, (short) y)) {
e.setTimestamp(ts + lastExposureUs); // set timestamp of last event written out to the frame end timestamp, TODO complete hack to have 1 pixel with larger timestamp
} else {
e.setTimestamp(ts);
}
}
maybePushEvent(e, apsFifo, outItr);
// debug
// if(x==firstPixel.x && y==firstPixel.y){
// log.info("pushed first frame pixel event "+e);
// }else if(x==lastPixel.x && y==lastPixel.y){
// log.info("pushed last frame pixel event "+e);
}
}
}
// end of exposure event
// e = outItr.nextOutput();
e.setReadoutType(ApsDvsEvent.ReadoutType.EOE);
e.x = (short) 0;
e.y = (short) 0;
e.setTimestamp(ts + lastExposureUs); // TODO should really be end of exposure timestamp, have to get that from last exposure message
maybePushEvent(e, apsFifo, outItr);
// end of frame event
// e = outItr.nextOutput();
e.setReadoutType(ApsDvsEvent.ReadoutType.EOF);
e.x = (short) 0;
e.y = (short) 0;
e.setTimestamp(ts + lastExposureUs);
maybePushEvent(e, apsFifo, outItr);
}
break;
case "Imu": {
hasImu.setTrue();
MessageType messageType = message.messageType;
// List<String> fieldNames = messageType.getFieldNames();
// for(String s:fieldNames){
// System.out.println("fieldName: "+s);
// List<String> fieldNames = messageType.getFieldNames();
MessageType header = messageType.getField("header");
Timestamp timestamp = header.<TimeType>getField("stamp").getValue();
int ts = getTimestampUsRelative(timestamp, false); // do update largest timestamp with IMU time
MessageType angular_velocity = messageType.getField("angular_velocity");
// List<String> angvelfields=angular_velocity.getFieldNames();
// for(String s:angvelfields){
// System.out.println("angular_velocity field: "+s);
float xrot = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue());
float yrot = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue());
float zrot = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue());
MessageType linear_acceleration = messageType.getField("linear_acceleration");
// List<String> linaccfields=linear_acceleration.getFieldNames();
// for(String s:linaccfields){
// System.out.println("linaccfields field: "+s);
float xacc = (float) (angular_velocity.<Float64Type>getField("x").getValue().doubleValue());
float yacc = (float) (angular_velocity.<Float64Type>getField("y").getValue().doubleValue());
float zacc = (float) (angular_velocity.<Float64Type>getField("z").getValue().doubleValue());
short[] buf = new short[7];
buf[IMUSampleType.ax.code] = (short) (G_PER_MPS2 * xacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb()); // TODO set these scales from caer parameter messages in stream
buf[IMUSampleType.ay.code] = (short) (G_PER_MPS2 * yacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb());
buf[IMUSampleType.az.code] = (short) (G_PER_MPS2 * zacc / IMUSample.getAccelSensitivityScaleFactorGPerLsb());
buf[IMUSampleType.gx.code] = (short) (DEG_PER_RAD * xrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb());
buf[IMUSampleType.gy.code] = (short) (DEG_PER_RAD * yrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb());
buf[IMUSampleType.gz.code] = (short) (DEG_PER_RAD * zrot / IMUSample.getGyroSensitivityScaleFactorDegPerSecPerLsb());
// ApsDvsEvent e = null;
// e = outItr.nextOutput();
IMUSample imuSample = new IMUSample(ts, buf);
e.setImuSample(imuSample);
e.setTimestamp(ts);
maybePushEvent(e, imuFifo, outItr);
}
break;
}
break;
case "dvs_msgs":
hasDvs.setTrue();
switch (type) {
case "EventArray":
MessageType messageType = message.messageType;
ArrayType data = messageType.<ArrayType>getField("events");
if (data == null) {
log.warning("got null data for field events in message " + message);
continue;
}
List<Field> eventFields = data.getFields();
gotEventsOrFrame = true;
int sizeY = chip.getSizeY();
int eventIdxThisPacket = 0;
// int nEvents = eventFields.size();
for (Field eventField : eventFields) {
MessageType eventMsg = (MessageType) eventField;
int x = eventMsg.<UInt16Type>getField("x").getValue();
int y = eventMsg.<UInt16Type>getField("y").getValue();
boolean pol = eventMsg.<BoolType>getField("polarity").getValue(); // false==off, true=on
Timestamp timestamp = (Timestamp) eventMsg.<TimeType>getField("ts").getValue();
int ts = getTimestampUsRelative(timestamp, true); // sets nonMonotonicTimestampDetected flag, faster than throwing exception, updates largest timestamp
// ApsDvsEvent e = outItr.nextOutput();
e.setReadoutType(ApsDvsEvent.ReadoutType.DVS);
e.timestamp = ts;
e.x = (short) x;
e.y = (short) (sizeY - y - 1);
e.polarity = pol ? PolarityEvent.Polarity.Off : PolarityEvent.Polarity.On;
e.type = (byte) (pol ? 0 : 1);
maybePushEvent(e, dvsFifo, outItr);
eventIdxThisPacket++;
}
}
break;
}
}
} catch (UninitializedFieldException ex) {
Logger.getLogger(ExampleRosBagReader.class.getName()).log(Level.SEVERE, null, ex);
throw new BagReaderException(ex);
}
if (nonMonotonicTimestampExceptionsChecked) {
// now pop events in time order from the FIFOs to the output packet and then reconstruct the raw packet
ApsDvsEvent ev;
while ((ev = popOldestEvent()) != null) {
ApsDvsEvent oe = outItr.nextOutput();
oe.copyFrom(ev);
}
}
AEPacketRaw aePacketRawCollecting = chip.getEventExtractor().reconstructRawPacket(eventPacket);
fireInitPropertyChange();
return aePacketRawCollecting;
}
/**
* Either pushes event to fifo or just directly writes it to output packet,
* depending on flag nonMonotonicTimestampExceptionsChecked.
*
* @param ev the event
* @param fifo the fifo to write to
* @param outItr the output packet iterator, if events are directly written
* to output
*/
private void maybePushEvent(ApsDvsEvent ev, AEFifo fifo, OutputEventIterator<ApsDvsEvent> outItr) {
if (nonMonotonicTimestampExceptionsChecked) {
fifo.pushEvent(ev);
} else {
ApsDvsEvent oe = outItr.nextOutput();
oe.copyFrom(ev);
}
}
/**
* returns the oldest event (earliest in time) from all of the fifos if
* there are younger events in all other fifos
*
* @return oldest valid event (and first one pushed to any one particular
* sub-fifo for identical timestamps) or null if there is none
*/
private ApsDvsEvent popOldestEvent() {
// find oldest event over all fifos
ApsDvsEvent ev = null;
int ts = Integer.MAX_VALUE;
int fifoIdx = -1;
int numStreamsWithData = 0;
for (int i = 0; i < 3; i++) {
boolean hasData = hasDvsApsImu[i].isTrue();
if (hasData) {
numStreamsWithData++;
}
int t;
if (hasData && !aeFifos[i].isEmpty() && (t = aeFifos[i].peekNextTimestamp()) <= /* check <= */ ts) {
fifoIdx = i;
ts = t;
}
}
if (fifoIdx < 0) {
return null; // no fifo has event
}
// if only one stream has data then just return it
if (numStreamsWithData == 1) {
ev = aeFifos[fifoIdx].popEvent();
} else {// if any of the other fifos for which we actually have sensor data don't have younger event then return null
for (int i = 0; i < 3; i++) {
if (i == fifoIdx) { // don't compare with ourselves
continue;
}
if (hasDvsApsImu[i].isTrue()
&& (!aeFifos[i].isEmpty()) // if other stream ever has had data but none is available now
&& aeFifos[i].getLastTimestamp() <= ts // or if last event in other stream data is still older than we are
) {
return null;
}
}
ev = aeFifos[fifoIdx].popEvent();
}
return ev;
}
/**
* Called to signal first read from file. Fires PropertyChange
* AEInputStream.EVENT_INIT, with new value this.
*/
protected void fireInitPropertyChange() {
if (firstReadCompleted) {
return;
}
getSupport().firePropertyChange(AEInputStream.EVENT_INIT, null, this);
firstReadCompleted = true;
}
@Override
synchronized public AEPacketRaw readPacketByNumber(int numEventsToRead) throws IOException {
int oldPosition = nextMessageNumber;
if (numEventsToRead < 0) {
return emptyPacket;
}
aePacketRawOutput.setNumEvents(0);
while (aePacketRawBuffered.getNumEvents() < numEventsToRead && aePacketRawBuffered.getNumEvents() < AEPacketRaw.MAX_PACKET_SIZE_EVENTS) {
try {
aePacketRawBuffered.append(getNextRawPacket());
} catch (EOFException ex) {
rewind();
return readPacketByNumber(numEventsToRead);
} catch (BagReaderException ex) {
throw new IOException(ex);
}
}
AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, numEventsToRead); // copy over collected events
// now use tmp packet to copy rest of buffered to, and then make that the new buffered
aePacketRawTmp.setNumEvents(0);
AEPacketRaw.copy(aePacketRawBuffered, numEventsToRead, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - numEventsToRead);
AEPacketRaw tmp = aePacketRawBuffered;
aePacketRawBuffered = aePacketRawTmp;
aePacketRawTmp = tmp;
getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, position());
if (aePacketRawOutput.getNumEvents() > 0) {
currentStartTimestamp = aePacketRawOutput.getLastTimestamp();
}
maybeSendRewoundEvent(oldPosition);
return aePacketRawOutput;
}
@Override
synchronized public AEPacketRaw readPacketByTime(int dt) throws IOException {
int oldPosition = nextMessageNumber;
if (dt < 0) {
return emptyPacket;
}
int newEndTime = currentStartTimestamp + dt; // problem is that time advances even when the data time might not.
while (aePacketRawBuffered.isEmpty()
|| (aePacketRawBuffered.getLastTimestamp() < newEndTime
&& aePacketRawBuffered.getNumEvents() < MAX_RAW_EVENTS_BUFFER_SIZE)) {
try {
aePacketRawBuffered.append(getNextRawPacket()); // reaching EOF here will throw EOFException
} catch (EOFException ex) {
aePacketRawBuffered.clear();
rewind();
return readPacketByTime(dt);
} catch (BagReaderException ex) {
if (ex.getCause() instanceof ClosedByInterruptException) { // ignore, caussed by interrupting ViewLoop to change rendering mode
return emptyPacket;
}
throw new IOException(ex);
}
}
int[] ts = aePacketRawBuffered.getTimestamps();
int idx = aePacketRawBuffered.getNumEvents() - 1;
while (idx > 0 && ts[idx] > newEndTime) {
idx
}
aePacketRawOutput.clear();
//public static void copy(AEPacketRaw src, int srcPos, AEPacketRaw dest, int destPos, int length) {
AEPacketRaw.copy(aePacketRawBuffered, 0, aePacketRawOutput, 0, idx); // copy over collected events
// now use tmp packet to copy rest of buffered to, and then make that the new buffered
aePacketRawTmp.setNumEvents(0);
AEPacketRaw.copy(aePacketRawBuffered, idx, aePacketRawTmp, 0, aePacketRawBuffered.getNumEvents() - idx);
AEPacketRaw tmp = aePacketRawBuffered;
aePacketRawBuffered = aePacketRawTmp;
aePacketRawTmp = tmp;
if (aePacketRawOutput.isEmpty()) {
currentStartTimestamp = newEndTime;
} else {
currentStartTimestamp = aePacketRawOutput.getLastTimestamp();
}
getSupport().firePropertyChange(AEInputStream.EVENT_POSITION, oldPosition, nextMessageNumber);
maybeSendRewoundEvent(oldPosition);
return aePacketRawOutput;
}
@Override
public boolean isNonMonotonicTimeExceptionsChecked() {
return nonMonotonicTimestampExceptionsChecked;
}
/**
* If this option is set, then non-monotonic timestamps are replaced with
* the newest timestamp in the file, ensuring monotonicity. It seems that
* the frames and IMU samples are captured or timestamped out of order in
* the file, resulting in DVS packets that contain timestamps younger than
* earlier frames or IMU samples.
*
* @param yes to guarantee monotonicity
*/
@Override
public void setNonMonotonicTimeExceptionsChecked(boolean yes) {
nonMonotonicTimestampExceptionsChecked = yes;
}
/** Returns starting time of file since epoch, in UTC time
*
* @return the time in ms since epoch (1970)
*/
@Override
public long getAbsoluteStartingTimeMs() {
return bagFile.getStartTime().getTime();
}
@Override
public ZoneId getZoneId() {
return zoneId; // TODO implement setting time zone from file
}
@Override
public int getDurationUs() {
return (int) (bagFile.getDurationS() * 1e6);
}
@Override
public int getFirstTimestamp() {
return (int) firstTimestamp;
}
@Override
public PropertyChangeSupport getSupport() {
return support;
}
@Override
public float getFractionalPosition() {
return (float) mostRecentTimestamp / getDurationUs();
}
@Override
public long position() {
return nextMessageNumber;
}
@Override
public void position(long n) {
// TODO, will be hard
}
@Override
synchronized public void rewind() throws IOException {
nextMessageNumber = (int) (isMarkInSet() ? getMarkInPosition() : 0);
currentStartTimestamp = (int) firstTimestamp;
clearAccumulatedEvents();
rewindFlag = true;
}
private void maybeSendRewoundEvent(long oldPosition) {
if (rewindFlag) {
getSupport().firePropertyChange(AEInputStream.EVENT_REWOUND, oldPosition, position());
rewindFlag = false;
}
}
private void clearAccumulatedEvents() {
largestTimestamp = Integer.MIN_VALUE;
aePacketRawBuffered.clear();
for (AEFifo f : aeFifos) {
f.clear();
}
}
@Override
synchronized public void setFractionalPosition(float frac) {
nextMessageNumber = (int) (frac * numMessages); // must also clear partially accumulated events in collecting packet and reset the timestamp
clearAccumulatedEvents();
try {
aePacketRawBuffered.append(getNextRawPacket()); // reaching EOF here will throw EOFException
} catch (EOFException ex) {
try {
aePacketRawBuffered.clear();
rewind();
} catch (IOException ex1) {
Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex1);
}
} catch (BagReaderException ex) {
Logger.getLogger(RosbagFileInputStream.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public long size() {
return 0;
}
@Override
public void clearMarks() {
markIn = -1;
markOut = -1;
getSupport().firePropertyChange(AEInputStream.EVENT_MARKS_CLEARED, null, null);
}
@Override
public long setMarkIn() {
int old = markIn;
markIn = nextMessageNumber;
getSupport().firePropertyChange(AEInputStream.EVENT_MARK_IN_SET, old, markIn);
return markIn;
}
@Override
public long setMarkOut() {
int old = markOut;
markOut = nextMessageNumber;
getSupport().firePropertyChange(AEInputStream.EVENT_MARK_OUT_SET, old, markOut);
return markOut;
}
@Override
public long getMarkInPosition() {
return markIn;
}
@Override
public long getMarkOutPosition() {
return markOut;
}
@Override
public boolean isMarkInSet() {
return markIn > 0;
}
@Override
public boolean isMarkOutSet() {
return markOut <= numMessages;
}
@Override
public void setRepeat(boolean repeat) {
this.repeatEnabled = repeat;
}
@Override
public boolean isRepeat() {
return repeatEnabled;
}
/**
* Returns the File that is being read, or null if the instance is
* constructed from a FileInputStream
*/
public File getFile() {
return file;
}
/**
* Sets the File reference but doesn't open the file
*/
public void setFile(File f) {
this.file = f;
}
@Override
public int getLastTimestamp() {
return (int) lastTimestamp; // TODO, from last DVS event timestamp
}
@Override
public int getMostRecentTimestamp() {
return (int) mostRecentTimestamp;
}
@Override
public int getTimestampResetBitmask() {
return 0; // TODO
}
@Override
public void setTimestampResetBitmask(int timestampResetBitmask) {
// TODO
}
@Override
synchronized public void close() throws IOException {
if (channel != null && channel.isOpen()) {
try {
channel.close();
} catch (IOException e) {
// ignore this error
}
}
bagFile = null;
file = null;
System.gc();
}
@Override
public int getCurrentStartTimestamp() {
return (int) lastTimestamp;
}
@Override
synchronized public void setCurrentStartTimestamp(int currentStartTimestamp) {
this.currentStartTimestamp = currentStartTimestamp;
nextMessageNumber = (int) (numMessages * (float) currentStartTimestamp / getDurationUs());
aePacketRawBuffered.clear();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
close();
}
private void generateMessageIndexes(ProgressMonitor progressMonitor) throws BagReaderException, InterruptedException {
if (wasIndexed) {
return;
}
log.info("creating index for all topics");
if (!maybeLoadCachedMsgIndexes(progressMonitor)) {
msgIndexes = bagFile.generateIndexesForTopicList(topicList, progressMonitor);
cacheMsgIndexes();
}
numMessages = msgIndexes.size();
markIn = 0;
markOut = numMessages;
firstTimestamp = getTimestampUsRelative(msgIndexes.get(0).timestamp, true);
lastTimestamp = getTimestampUsRelative(msgIndexes.get(numMessages - 1).timestamp, false); // don't update largest timestamp with last timestamp
wasIndexed = true;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
this.support.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
this.support.removePropertyChangeListener(listener);
}
/**
* Adds a topic for which listeners should be informed. The PropertyChange
* has this as the source and the new value is the MessageType message.
*
* @param topics a string topic, e.g. "/dvs/events"
* @param listener a PropertyChangeListener that gets the messages
* @throws java.lang.InterruptedException since generating the topic index
* is a long-running process, the method throws
* @throws com.github.swrirobotics.bags.reader.exceptions.BagReaderException
* if there is an exception for the BagFile
* @see MessageType
*/
@Override
synchronized public void addSubscribers(List<String> topics, PropertyChangeListener listener, ProgressMonitor progressMonitor) throws InterruptedException, BagReaderException {
List<String> topicsToAdd = new ArrayList();
for (String topic : topics) {
if (msgListeners.containsKey(topic) && msgListeners.get(topic).contains(listener)) {
log.warning("topic " + topic + " and listener " + listener + " already added, ignoring");
continue;
}
topicsToAdd.add(topic);
}
if (topicsToAdd.isEmpty()) {
log.warning("nothing to add");
return;
}
addPropertyChangeListener(listener);
List<BagFile.MessageIndex> idx = bagFile.generateIndexesForTopicList(topicsToAdd, progressMonitor);
msgIndexes.addAll(idx);
for (String topic : topics) {
msgListeners.put(topic, listener);
}
Collections.sort(msgIndexes);
}
/**
* Removes a topic
*
* @param topic
* @param listener
*/
@Override
public void removeTopic(String topic, PropertyChangeListener listener) {
log.warning("cannot remove topic parsing, just removing listener");
if (msgListeners.containsValue(listener)) {
log.info("removing listener " + listener);
removePropertyChangeListener(listener);
}
}
/**
* Set if nonmonotonic timestamp was detected. Cleared at start of
* collecting each new packet.
*
* @return the nonMonotonicTimestampDetected true if a nonmonotonic
* timestamp was detected.
*/
public boolean isNonMonotonicTimestampDetected() {
return nonMonotonicTimestampDetected;
}
synchronized private void cacheMsgIndexes() {
try {
File file = new File(messageIndexesCacheFileName());
if (file.exists() && file.canRead() && file.isFile()) {
log.info("cached indexes " + file + " for file " + getFile() + " already exists, not storing it again");
return;
}
log.info("caching the index for rosbag file " + getFile() + " in " + file);
FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(msgIndexes);
oos.flush();
log.info("cached the index for rosbag file " + getFile() + " in " + file);
} catch (Exception e) {
log.warning("could not cache the message index to disk: " + e.toString());
}
}
synchronized private boolean maybeLoadCachedMsgIndexes(ProgressMonitor progressMonitor) {
try {
File file = new File(messageIndexesCacheFileName());
if (!file.exists() || !file.canRead() || !file.isFile()) {
log.info("cached indexes " + file + " for file " + getFile() + " does not exist");
return false;
}
log.info("reading cached index for rosbag file " + getFile() + " from " + file);
long startTime = System.currentTimeMillis();
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
progressMonitor.setNote("canceling");
throw new InterruptedException("canceled loading caches");
}
progressMonitor.setNote("reading cached index from " + file);
}
FileInputStream in = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(in));
List<BagFile.MessageIndex> tmpIdx = (List<BagFile.MessageIndex>) ois.readObject();
msgIndexes = tmpIdx;
long ms = System.currentTimeMillis() - startTime;
log.info("done after " + ms + "ms with reading cached index for rosbag file " + getFile() + " from " + file);
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
progressMonitor.setNote("canceling");
throw new InterruptedException("canceled loading caches");
}
progressMonitor.setNote("done reading cached index");
progressMonitor.setProgress(progressMonitor.getMaximum());
}
return true;
} catch (Exception e) {
log.warning("could load cached message index from disk: " + e.toString());
return false;
}
}
private String messageIndexesCacheFileName() {
return System.getProperty("java.io.tmpdir") + File.separator + getFile().getName() + ".rosbagidx";
}
/**
* A FIFO for ApsDvsEvent events.
*/
private final class AEFifo extends ApsDvsEventPacket {
private final int MAX_EVENTS = 1 << 24;
int nextToPopIndex = 0;
private boolean full = false;
public AEFifo() {
super(ApsDvsEvent.class);
}
/**
* Adds a new event to end
*
* @param event
*/
public final void pushEvent(ApsDvsEvent event) {
if (full) {
return;
}
if (size == MAX_EVENTS) {
full = true;
log.warning("FIFO has reached capacity " + MAX_EVENTS + ": " + toString());
return;
}
appendCopy(event);
}
@Override
public boolean isEmpty() {
return size == 0 || nextToPopIndex >= size; //To change body of generated methods, choose Tools | Templates.
}
@Override
public void clear() {
super.clear();
nextToPopIndex = 0;
full = false;
}
/**
* @return next event, or null if there are no more
*/
public final ApsDvsEvent popEvent() {
if (isEmpty()) {
clear();
return null;
}
ApsDvsEvent event = (ApsDvsEvent) getEvent(nextToPopIndex++);
if (isEmpty()) {
clear();
}
return event;
}
public final int peekNextTimestamp() {
return getEvent(nextToPopIndex).timestamp;
}
@Override
final public String toString() {
return "AEFifo with capacity " + MAX_EVENTS + " nextToPopIndex=" + nextToPopIndex + " holding " + super.toString();
}
}
} |
package net.sourceforge.android.sdk;
import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.os.Build;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
public class CameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {
private CameraSupport mCamera;
private SurfaceHolder mHolder;
private PreviewCallback mPreviewCallback;
private AutoFocusCallback mAutoFocusCallback;
@SuppressWarnings("deprecation")
@SuppressLint("InlinedApi")
public CameraSurfaceView(Context context, Camera camera,
PreviewCallback previewCallback, AutoFocusCallback autoFocusCallback) {
super(context);
mCamera = new CameraSupport(camera);
mPreviewCallback = previewCallback;
mAutoFocusCallback = autoFocusCallback;
mCamera.setContinuousFocus(true);
mHolder = getHolder();
mHolder = getHolder();
mHolder.addCallback(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
}
public CameraSurfaceView(Context context) {
this(context, null);
setVisibility(View.GONE);
}
public CameraSurfaceView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
setVisibility(View.GONE);
}
public CameraSurfaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mHolder = getHolder();
mHolder.addCallback(this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
setVisibility(View.GONE);
}
public void open(PreviewCallback previewCallback,
AutoFocusCallback autoFocusCallback) {
mCamera = CameraSupport.open();
mPreviewCallback = previewCallback;
mAutoFocusCallback = autoFocusCallback;
mCamera.setContinuousFocus(true);
setVisibility(View.VISIBLE);
}
public void release() {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCamera == null || !mCamera.isValid()) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
Size size = getBestPreviewSize(height, width, mCamera.getParameters());
float aspectRatio = (float) size.height / (float) size.width;
if (width < height * aspectRatio) {
width = (int) (height * aspectRatio + .5);
} else {
height = (int) (width / aspectRatio + .5);
}
setMeasuredDimension(width, height);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (mHolder.getSurface() == null || mCamera == null
|| !mCamera.isValid()) {
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
try {
// Hard code camera surface rotation 90 degs to match Activity view
// in portrait
mCamera.setDisplayOrientation(90);
Size bestFit = getBestPreviewSize(width, height,
mCamera.getParameters());
mCamera.getParameters().setPreviewSize(bestFit.width,
bestFit.height);
mCamera.setPreviewDisplay(mHolder);
mCamera.setPreviewCallback(mPreviewCallback);
mCamera.startPreview();
mCamera.autoFocus(mAutoFocusCallback);
} catch (Exception e) {
}
}
Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;
float dr = Float.MAX_VALUE;
float ratio = (float) width / (float) height;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
float r = (float) size.width / (float) size.height;
if (Math.abs(r - ratio) < dr && size.width <= width
&& size.height <= height) {
dr = Math.abs(r - ratio);
result = size;
}
}
return result;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera == null) {
return;
}
try {
mCamera.setPreviewDisplay(holder);
} catch (Exception e) {
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
public CameraSupport getCameraSupport() {
return mCamera;
}
} |
package edu.uiowa.icts.spring;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.QueryException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import edu.uiowa.icts.criterion.CastAsVarcharLike;
import edu.uiowa.icts.criterion.DateLike;
import edu.uiowa.icts.criterion.IntegerLike;
import edu.uiowa.icts.sql.Alias;
import edu.uiowa.icts.util.SortColumn;
@Transactional
public class GenericDao<Type> implements GenericDaoInterface<Type> {
private static final Log log = LogFactory.getLog( GenericDao.class );
public SessionFactory sessionFactory;
private String domainName;
private Class<?> domainClass;
public void setSessionFactory( boolean usesf ) {
if ( usesf ) {
sessionFactory = SessionFactoryUtil.getInstance();
}
}
public Session getSession() {
return sessionFactory.getCurrentSession();
}
@Autowired
public void setSessionFactory( SessionFactory sessionFactory ) {
this.sessionFactory = sessionFactory;
}
public SessionFactory getSessionFactory() {
return this.sessionFactory;
}
@Transactional( readOnly = true )
@SuppressWarnings( "unchecked" )
public List<Type> search( String property, String search, Integer limit ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.add( Restrictions.ilike( property, search + "%" ) );
criteria.setMaxResults( limit == null ? 25 : limit );
return criteria.list();
}
@Transactional
public void saveOrUpdate( Type obj ) {
getSession().saveOrUpdate( obj );
}
@Transactional
public void save( Type obj ) {
getSession().save( obj );
}
@Transactional
public void justSave( Type obj ) {
getSession().save( obj );
}
@Transactional
public void persist( Type obj ) {
getSession().persist( obj );
}
@Transactional
public void merge( Type obj ) {
getSession().merge( obj );
}
@Transactional
public void flush() {
getSession().flush();
}
@Transactional
public void close() {
getSession().close();
}
@Transactional
public void refresh( Object obj ) {
getSession().refresh( obj );
}
@Transactional
public long count() {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.setProjection( Projections.rowCount() );
return ( (Number) criteria.uniqueResult() ).longValue();
}
@Transactional
@SuppressWarnings( "unchecked" )
public void delete( int id ) {
Type obj = (Type) getSession().get( getDomainClass(), id );
getSession().delete( obj );
}
@Transactional
@SuppressWarnings( "unchecked" )
public void delete( long id ) {
Type obj = (Type) getSession().get( getDomainClass(), id );
getSession().delete( obj );
}
public void delete( Type obj ) {
getSession().delete( obj );
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public Type findByProperty( String propertyName, Object value ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.add( Restrictions.eq( propertyName, value ) );
return (Type) criteria.uniqueResult();
}
@Override
@SuppressWarnings( "unchecked" )
public Type findByProperties( HashMap<String, Object> propertyValues ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
for ( String property : propertyValues.keySet() ) {
criteria.add( Restrictions.eq( property, propertyValues.get( property ) ) );
}
return (Type) criteria.uniqueResult();
}
@Transactional( readOnly = true )
public Integer countByProperty( String propertyName, Object value ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.add( Restrictions.eq( propertyName, value ) );
criteria.setProjection( Projections.rowCount() );
return ( (Number) criteria.uniqueResult() ).intValue();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public List<Type> listByProperty( String propertyName, Object value ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.add( Restrictions.eq( propertyName, value ) );
return (List<Type>) criteria.list();
}
@Override
public Integer countByProperties( HashMap<String, Object> propertyValues ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
criteria.setProjection( Projections.rowCount() );
for ( String prp : propertyValues.keySet() ) {
criteria.add( Restrictions.eq( prp, propertyValues.get( prp ) ) );
}
return ( (Number) criteria.uniqueResult() ).intValue();
}
@SuppressWarnings( "unchecked" )
@Override
public List<Type> listByProperties( HashMap<String, Object> propertyValues ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
for ( String property : propertyValues.keySet() ) {
criteria.add( Restrictions.eq( property, propertyValues.get( property ) ) );
}
return (List<Type>) criteria.list();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public Type findByQuery( String s ) {
return (Type) getSession().createQuery( s ).uniqueResult();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public List<Type> listByQuery( String s ) {
return getSession().createQuery( s ).list();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public List<Type> list() {
return getSession().createCriteria( getDomainClass() ).list();
}
@Override
public void update( Type obj ) {
getSession().update( obj );
}
@Override
@SuppressWarnings( "unchecked" )
public List<Type> list( Comparator<Type> comparator ) {
List<Type> list = getSession().createCriteria( getDomainClass() ).list();
Collections.sort( list, comparator );
return list;
}
@Transactional( readOnly = true )
public String dump() {
String result = "Dumping " + getDomainClass() + "\n";
for ( Type item : list() ) {
try {
Method[] methods = getDomainClass().getMethods();
for ( Method method : methods ) {
try {
if ( method.getName().startsWith( "get" ) ) {
result = result + method.invoke( item ) + "\t";
log.debug( method.invoke( item ) + "\t" );
}
} catch ( Exception e ) {
log.error( "error calling dump", e );
continue;
}
}
result = result + "\n";
} catch ( Exception e ) {
log.error( "error calling dump", e );
continue;
}
}
return result;
}
@Transactional
@SuppressWarnings( "unchecked" )
public List<Type> exec( String sql ) {
Query query = getSession().createSQLQuery( sql );
query.setResultTransformer( Transformers.aliasToBean( getDomainClass() ) );
return query.list();
}
@Transactional
public void execute( String sql ) {
Query query = getSession().createSQLQuery( sql );
query.executeUpdate();
}
@Transactional
public void clean() {
log.debug( "Cleanning..." + getDomainClass() );
for ( Type item : list() ) {
getSession().delete( item );
}
}
@Transactional( readOnly = true )
public List<Type> list( Integer start, Integer limit ) {
return list( start, limit, null, new ArrayList<String>(), new ArrayList<SortColumn>(), new HashMap<String, Object>() );
}
@Transactional( readOnly = true )
public List<Type> list( Integer start, Integer limit, ArrayList<SortColumn> sorts ) {
return list( start, limit, null, new ArrayList<String>(), sorts, new HashMap<String, Object>() );
}
@Transactional( readOnly = true )
public List<Type> list( Integer start, Integer limit, String search, ArrayList<String> searchColumns, ArrayList<SortColumn> sorts ) {
return list( start, limit, search, searchColumns, sorts, new HashMap<String, Object>() );
}
public Integer count( String search, ArrayList<String> searchColumns ) {
GenericDaoListOptions options = new GenericDaoListOptions();
options.setSearch( search );
options.setSearchColumns( searchColumns );
return count( options );
}
public Integer count( String search, ArrayList<String> searchColumns, HashMap<String, Object> properties ) {
GenericDaoListOptions options = new GenericDaoListOptions();
options.setSearch( search );
options.setSearchColumns( searchColumns );
options.setIndividualEquals( properties );
return count( options );
}
@Override
public List<Type> list( Integer start, Integer limit, String search, ArrayList<String> searchColumns, ArrayList<SortColumn> sorts, HashMap<String, Object> individualLikes ) {
return list( start, limit, search, searchColumns, sorts, individualLikes, null );
}
@Override
public Integer count( String search, ArrayList<String> searchColumns, HashMap<String, Object> individualLikes, HashMap<String, Object> individualEquals ) {
GenericDaoListOptions options = new GenericDaoListOptions();
options.setSearch( search );
options.setSearchColumns( searchColumns );
options.setIndividualLikes( individualLikes );
options.setIndividualEquals( individualEquals );
return count( options );
}
@Transactional( readOnly = true )
public Integer count( GenericDaoListOptions options ) {
Criteria criteria = criteria( options );
criteria.setProjection( Projections.rowCount() );
return ( (Number) criteria.uniqueResult() ).intValue();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public List<Type> list( GenericDaoListOptions options ) {
try {
Criteria criteria = criteria( options );
addSorts( criteria, options );
if ( options.getStart() != null ) {
criteria.setFirstResult( options.getStart() );
}
if ( options.getLimit() != null && options.getLimit() != -1 ) { // datatable sets iDisplayLength = -1 when bPaginate = false
criteria.setMaxResults( options.getLimit() );
}
return criteria.list();
} catch ( Exception e ) {
log.error( "Error getting List with options", e );
log.debug( "options: " + options.toString() );
return new ArrayList<Type>();
}
}
@Transactional( readOnly = true )
protected Criteria criteria( GenericDaoListOptions options ) {
Criteria criteria = null;
if ( options.getAlias() != null && !StringUtils.equals( options.getAlias().trim(), "" ) ) {
criteria = getSession().createCriteria( getDomainClass(), options.getAlias().trim() );
} else {
criteria = getSession().createCriteria( getDomainClass() );
}
Dialect dialect = ( (SessionFactoryImplementor) getSessionFactory() ).getDialect();
ClassMetadata classMetaData = getSessionFactory().getClassMetadata( getDomainClass() );
applyGenericDaoListOptions( criteria, options, classMetaData, dialect );
return criteria;
}
public void applyGenericDaoListOptions( Criteria criteria, GenericDaoListOptions options, ClassMetadata classMetaData, Dialect dialect ) {
processAliases( criteria, options );
addIndividualEquals( criteria, options );
addJunctions( criteria, options );
addLikeCriteria( criteria, options, classMetaData, dialect );
addNotEquals( criteria, options );
addSearchCriteria( criteria, options, classMetaData, dialect );
addCriterion( criteria, options );
}
private void addCriterion( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getCriterion() != null && !options.getCriterion().isEmpty() ) {
for ( Criterion criterion : options.getCriterion() ) {
criteria.add( criterion );
}
}
}
public void addNotEquals( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getNotEquals() != null && !options.getNotEquals().isEmpty() ) {
for ( String key : options.getNotEquals().keySet() ) {
criteria.add( Restrictions.ne( key, options.getNotEquals().get( key ) ) );
}
}
}
public void addIndividualEquals( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getIndividualEquals() != null && !options.getIndividualEquals().isEmpty() ) {
for ( String key : options.getIndividualEquals().keySet() ) {
criteria.add( Restrictions.eq( key, options.getIndividualEquals().get( key ) ) );
}
}
}
/**
* @author rrlorent
* @param criteria
* @param options
*/
public void addJunctions( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getJunctions() != null && !options.getJunctions().isEmpty() ) {
for ( Junction junction : options.getJunctions() ) {
criteria.add( junction );
}
}
}
/**
* @author rrlorent
* @date May 28, 2014
* @param criteria
* @param options
*/
public void addSorts( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getSorts() != null ) {
for ( SortColumn sortColumn : options.getSorts() ) {
if ( options.getPropertyNameMap() != null && options.getPropertyNameMap().get( sortColumn.getColumn() ) != null && !options.getPropertyNameMap().get( sortColumn.getColumn() ).isEmpty() ) {
for ( String alternateName : options.getPropertyNameMap().get( sortColumn.getColumn() ) ) {
if ( "asc".equals( sortColumn.getDirection() ) ) {
criteria.addOrder( Order.asc( alternateName ) );
} else if ( "desc".equals( sortColumn.getDirection() ) ) {
criteria.addOrder( Order.desc( alternateName ) );
}
}
} else {
if ( "asc".equals( sortColumn.getDirection() ) ) {
criteria.addOrder( Order.asc( sortColumn.getColumn() ) );
} else if ( "desc".equals( sortColumn.getDirection() ) ) {
criteria.addOrder( Order.desc( sortColumn.getColumn() ) );
}
}
}
}
}
/**
* @param criteria
* @param options
*/
public void processAliases( Criteria criteria, GenericDaoListOptions options ) {
if ( options.getAliases() != null ) {
for ( Alias alias : options.getAliases() ) {
criteria.createAlias( alias.getAssociationPath(), alias.getAlias(), alias.getJoinType() );
}
}
}
/**
* @param criteria
* @param options
* @param dialect
* @param classMetaData
*/
public void addSearchCriteria( Criteria criteria, GenericDaoListOptions options, ClassMetadata classMetaData, Dialect dialect ) {
if ( options.getSearch() != null && !"".equals( options.getSearch() ) && options.getSearchColumns() != null && !options.getSearchColumns().isEmpty() ) {
for ( String theSearch : StringUtils.split( options.getSearch().trim(), ' ' ) ) {
Disjunction disj = Restrictions.disjunction();
for ( String propertyName : options.getSearchColumns() ) {
disj.add( createLikeCriterion( options, classMetaData, dialect, propertyName, theSearch ) );
}
criteria.add( disj );
}
}
}
/**
* @param criteria
* @param options
* @param dialect
* @param classMetaData
*/
public void addLikeCriteria( Criteria criteria, GenericDaoListOptions options, ClassMetadata classMetaData, Dialect dialect ) {
if ( options.getLikes() != null && !options.getLikes().isEmpty() ) {
for ( String propertyName : options.getLikes().keySet() ) {
if ( options.getLikes().get( propertyName ) != null && !options.getLikes().get( propertyName ).isEmpty() ) {
Disjunction disjunction = Restrictions.disjunction();
if ( options.getPropertyNameMap() != null && options.getPropertyNameMap().get( propertyName ) != null && !options.getPropertyNameMap().get( propertyName ).isEmpty() ) {
for ( String alternate : options.getPropertyNameMap().get( propertyName ) ) {
for ( Object value : options.getLikes().get( propertyName ) ) {
disjunction.add( createLikeCriterion( options, classMetaData, dialect, alternate, value ) );
}
}
} else {
for ( Object value : options.getLikes().get( propertyName ) ) {
disjunction.add( createLikeCriterion( options, classMetaData, dialect, propertyName, value ) );
}
}
criteria.add( disjunction );
}
}
} else if ( options.getIndividualLikes() != null && !options.getIndividualLikes().isEmpty() ) {
for ( String propertyName : options.getIndividualLikes().keySet() ) {
if ( options.getPropertyNameMap() != null && options.getPropertyNameMap().get( propertyName ) != null && !options.getPropertyNameMap().get( propertyName ).isEmpty() ) {
Disjunction disjunction = Restrictions.disjunction();
for ( String alternate : options.getPropertyNameMap().get( propertyName ) ) {
disjunction.add( createLikeCriterion( options, classMetaData, dialect, alternate, options.getIndividualLikes().get( propertyName ) ) );
}
criteria.add( disjunction );
} else {
criteria.add( createLikeCriterion( options, classMetaData, dialect, propertyName, options.getIndividualLikes().get( propertyName ) ) );
}
}
}
}
/**
* @param options
* @param classMetaData
* @param dialect
* @param propertyName
* @param value
* @return {@link Criterion}
*/
private Criterion createLikeCriterion( GenericDaoListOptions options, ClassMetadata classMetaData, Dialect dialect, String propertyName, Object value ) {
boolean fail = false;
String propertyType = null;
if ( classMetaData == null ) {
log.debug( "classMetaData is null for " + getDomainClass() );
fail = true;
} else {
try {
org.hibernate.type.Type propertyTypeOb = classMetaData.getPropertyType( propertyName );
if ( propertyTypeOb != null ) {
propertyType = propertyTypeOb.getName();
} else {
log.debug( "property type is null for " + propertyName );
fail = true;
}
} catch ( QueryException e ) {
fail = true;
}
}
Criterion criterion = null;
if ( fail ) {
// cast it to varchar to avoid errors
criterion = new CastAsVarcharLike( propertyName, ( options.isDoubleWildCard() ? "%" : "" ) + value + "%" );
} else {
if ( StringUtils.equalsIgnoreCase( propertyType, "integer" ) || StringUtils.equalsIgnoreCase( propertyType, "boolean" ) || StringUtils.equalsIgnoreCase( propertyType, "float" ) ) {
criterion = new IntegerLike( propertyName, ( options.isDoubleWildCard() ? "%" : "" ) + value + "%" );
} else if ( StringUtils.equalsIgnoreCase( propertyType, "date" ) || StringUtils.equalsIgnoreCase( propertyType, "time" ) || StringUtils.equalsIgnoreCase( propertyType, "timestamp" ) || StringUtils.equalsIgnoreCase( propertyType, "calendar" ) || StringUtils.equalsIgnoreCase( propertyType, "calendar_date" ) ) {
criterion = new DateLike( propertyName, ( options.isDoubleWildCard() ? "%" : "" ) + value + "%", dialect );
} else if ( StringUtils.equalsIgnoreCase( propertyType, "string" ) ) {
criterion = Restrictions.ilike( propertyName, ( options.isDoubleWildCard() ? "%" : "" ) + value + "%" );
} else {
log.error( propertyType + " not supported in individual likes for " + getDomainClass() + " : " + propertyName );
// cast it to varchar to avoid errors
criterion = new CastAsVarcharLike( propertyName, ( options.isDoubleWildCard() ? "%" : "" ) + value + "%" );
}
}
return criterion;
}
@Transactional( readOnly = true )
public List<Type> list( Integer start, Integer limit, String search, ArrayList<String> searchColumns, ArrayList<SortColumn> sorts, HashMap<String, Object> individualLikes, HashMap<String, Object> individualEquals ) {
GenericDaoListOptions options = new GenericDaoListOptions();
options.setIndividualLikes( individualLikes );
options.setIndividualEquals( individualEquals );
options.setSearch( search );
options.setSearchColumns( searchColumns );
options.setLimit( limit );
options.setSorts( sorts );
options.setStart( start );
return list( options );
}
public void save( Collection<Type> list ) {
StatelessSession session = this.getSessionFactory().openStatelessSession();
session.beginTransaction();
for ( Object o : list ) {
session.insert( o );
}
session.getTransaction().commit();
session.close();
}
public void saveOrUpdate( Collection<Type> list ) {
StatelessSession session = getSessionFactory().openStatelessSession();
session.beginTransaction();
for ( Object o : list ) {
session.update( o );
}
session.getTransaction().commit();
session.close();
}
@SuppressWarnings( "unchecked" )
@Transactional( readOnly = true )
public List<Type> listOrdered( String order, String direction ) {
Criteria criteria = getSession().createCriteria( getDomainClass() );
if ( "desc".equalsIgnoreCase( direction ) ) {
criteria.addOrder( Order.desc( order ) );
} else {
criteria.addOrder( Order.asc( order ) );
}
return criteria.list();
}
@Transactional
@SuppressWarnings( "unchecked" )
public List<Type[]> query( String st ) {
return getSession().createQuery( st ).list();
}
@Transactional
public Integer maxOf( String s ) {
return (Integer) getSession().createQuery( "select max(" + s + ") from " + getDomainName() + " " ).uniqueResult();
}
public String getDomainName() {
return domainName;
}
public void setDomainName( String domainName ) {
this.domainName = domainName;
try {
this.domainClass = Class.forName( domainName );
} catch ( ClassNotFoundException e ) {
throw new RuntimeException( "error setting domain name to " + domainName, e );
}
}
public Class<?> getDomainClass() {
return domainClass;
}
// public void setDomainClass( Class<?> domainClass ) {
// this.domainClass = domainClass;
} |
package graphql.execution;
import graphql.GraphQLException;
import graphql.language.Argument;
import graphql.language.ArrayValue;
import graphql.language.NullValue;
import graphql.language.ObjectField;
import graphql.language.ObjectValue;
import graphql.language.Value;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLEnumType;
import graphql.schema.GraphQLInputObjectField;
import graphql.schema.GraphQLInputObjectType;
import graphql.schema.GraphQLList;
import graphql.schema.GraphQLNonNull;
import graphql.schema.GraphQLScalarType;
import graphql.schema.GraphQLSchema;
import graphql.schema.GraphQLType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ValuesResolver {
public Map<String, Object> getVariableValues(GraphQLSchema schema, List<VariableDefinition> variableDefinitions, Map<String, Object> args) {
Map<String, Object> result = new LinkedHashMap<>();
for (VariableDefinition variableDefinition : variableDefinitions) {
String varName = variableDefinition.getName();
// we transfer the variable as field arguments if its present as value
if (args.containsKey(varName)) {
Object arg = args.get(varName);
Object variableValue = getVariableValue(schema, variableDefinition, arg);
result.put(varName, variableValue);
}
}
return result;
}
public Map<String, Object> getArgumentValues(List<GraphQLArgument> argumentTypes, List<Argument> arguments, Map<String, Object> variables) {
if (argumentTypes.isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> result = new LinkedHashMap<>();
Map<String, Argument> argumentMap = argumentMap(arguments);
for (GraphQLArgument fieldArgument : argumentTypes) {
String argName = fieldArgument.getName();
Argument argument = argumentMap.get(argName);
Object value;
if (argument != null) {
value = coerceValueAst(fieldArgument.getType(), argument.getValue(), variables);
} else {
value = fieldArgument.getDefaultValue();
}
// only put an arg into the result IF they specified a variable at all or
// the default value ended up being something non null
if (argumentMap.containsKey(argName) || value != null) {
result.put(argName, value);
}
}
return result;
}
private Map<String, Argument> argumentMap(List<Argument> arguments) {
Map<String, Argument> result = new LinkedHashMap<>();
for (Argument argument : arguments) {
result.put(argument.getName(), argument);
}
return result;
}
private Object getVariableValue(GraphQLSchema schema, VariableDefinition variableDefinition, Object inputValue) {
GraphQLType type = TypeFromAST.getTypeFromAST(schema, variableDefinition.getType());
//noinspection ConstantConditions
if (!isValid(type, inputValue)) {
throw new GraphQLException("Invalid value for type");
}
if (inputValue == null && variableDefinition.getDefaultValue() != null) {
return coerceValueAst(type, variableDefinition.getDefaultValue(), null);
}
return coerceValue(type, inputValue);
}
private boolean isValid(GraphQLType type, Object inputValue) {
return true;
}
private Object coerceValue(GraphQLType graphQLType, Object value) {
if (graphQLType instanceof GraphQLNonNull) {
Object returnValue = coerceValue(((GraphQLNonNull) graphQLType).getWrappedType(), value);
if (returnValue == null) {
throw new NonNullableValueCoercedAsNullException(graphQLType);
}
return returnValue;
}
if (value == null) return null;
if (graphQLType instanceof GraphQLScalarType) {
return coerceValueForScalar((GraphQLScalarType) graphQLType, value);
} else if (graphQLType instanceof GraphQLEnumType) {
return coerceValueForEnum((GraphQLEnumType) graphQLType, value);
} else if (graphQLType instanceof GraphQLList) {
return coerceValueForList((GraphQLList) graphQLType, value);
} else if (graphQLType instanceof GraphQLInputObjectType && value instanceof Map) {
//noinspection unchecked
return coerceValueForInputObjectType((GraphQLInputObjectType) graphQLType, (Map<String, Object>) value);
} else if (graphQLType instanceof GraphQLInputObjectType) {
return value;
} else {
throw new GraphQLException("unknown type " + graphQLType);
}
}
private Object coerceValueForInputObjectType(GraphQLInputObjectType inputObjectType, Map<String, Object> input) {
Map<String, Object> result = new LinkedHashMap<>();
List<GraphQLInputObjectField> fields = inputObjectType.getFields();
List<String> fieldNames = fields.stream().map(GraphQLInputObjectField::getName).collect(Collectors.toList());
for (String inputFieldName : input.keySet()) {
if (!fieldNames.contains(inputFieldName)) {
throw new InputMapDefinesTooManyFieldsException(inputObjectType, inputFieldName);
}
}
for (GraphQLInputObjectField inputField : fields) {
if (input.containsKey(inputField.getName()) || alwaysHasValue(inputField)) {
Object value = coerceValue(inputField.getType(), input.get(inputField.getName()));
result.put(inputField.getName(), value == null ? inputField.getDefaultValue() : value);
}
}
return result;
}
private boolean alwaysHasValue(GraphQLInputObjectField inputField) {
return inputField.getDefaultValue() != null
|| inputField.getType() instanceof GraphQLNonNull;
}
private Object coerceValueForScalar(GraphQLScalarType graphQLScalarType, Object value) {
return graphQLScalarType.getCoercing().parseValue(value);
}
private Object coerceValueForEnum(GraphQLEnumType graphQLEnumType, Object value) {
return graphQLEnumType.getCoercing().parseValue(value);
}
private List coerceValueForList(GraphQLList graphQLList, Object value) {
if (value instanceof Iterable) {
List<Object> result = new ArrayList<>();
for (Object val : (Iterable) value) {
result.add(coerceValue(graphQLList.getWrappedType(), val));
}
return result;
} else {
return Collections.singletonList(coerceValue(graphQLList.getWrappedType(), value));
}
}
private Object coerceValueAst(GraphQLType type, Value inputValue, Map<String, Object> variables) {
if (inputValue instanceof VariableReference) {
return variables.get(((VariableReference) inputValue).getName());
}
if (inputValue instanceof NullValue) {
return null;
}
if (type instanceof GraphQLScalarType) {
return ((GraphQLScalarType) type).getCoercing().parseLiteral(inputValue);
}
if (type instanceof GraphQLNonNull) {
return coerceValueAst(((GraphQLNonNull) type).getWrappedType(), inputValue, variables);
}
if (type instanceof GraphQLInputObjectType) {
return coerceValueAstForInputObject((GraphQLInputObjectType) type, (ObjectValue) inputValue, variables);
}
if (type instanceof GraphQLEnumType) {
return ((GraphQLEnumType) type).getCoercing().parseLiteral(inputValue);
}
if (type instanceof GraphQLList) {
return coerceValueAstForList((GraphQLList) type, inputValue, variables);
}
return null;
}
private Object coerceValueAstForList(GraphQLList graphQLList, Value value, Map<String, Object> variables) {
if (value instanceof ArrayValue) {
ArrayValue arrayValue = (ArrayValue) value;
List<Object> result = new ArrayList<>();
for (Value singleValue : arrayValue.getValues()) {
result.add(coerceValueAst(graphQLList.getWrappedType(), singleValue, variables));
}
return result;
} else {
return Collections.singletonList(coerceValueAst(graphQLList.getWrappedType(), value, variables));
}
}
private Object coerceValueAstForInputObject(GraphQLInputObjectType type, ObjectValue inputValue, Map<String, Object> variables) {
Map<String, Object> result = new LinkedHashMap<>();
Map<String, ObjectField> inputValueFieldsByName = mapObjectValueFieldsByName(inputValue);
for (GraphQLInputObjectField inputTypeField : type.getFields()) {
if (inputValueFieldsByName.containsKey(inputTypeField.getName())) {
boolean putObjectInMap = true;
ObjectField field = inputValueFieldsByName.get(inputTypeField.getName());
Value fieldInputValue = field.getValue();
Object fieldObject = null;
if (fieldInputValue instanceof VariableReference) {
String varName = ((VariableReference) fieldInputValue).getName();
if (!variables.containsKey(varName)) {
putObjectInMap = false;
} else {
fieldObject = variables.get(varName);
}
} else {
fieldObject = coerceValueAst(inputTypeField.getType(), fieldInputValue, variables);
}
if (fieldObject == null) {
if (!field.getValue().isEqualTo(NullValue.Null)) {
fieldObject = inputTypeField.getDefaultValue();
}
}
if (putObjectInMap) {
result.put(field.getName(), fieldObject);
} else {
assertNonNullInputField(inputTypeField);
}
} else if (inputTypeField.getDefaultValue() != null) {
result.put(inputTypeField.getName(), inputTypeField.getDefaultValue());
} else {
assertNonNullInputField(inputTypeField);
}
}
return result;
}
private void assertNonNullInputField(GraphQLInputObjectField inputTypeField) {
if (inputTypeField.getType() instanceof GraphQLNonNull) {
throw new NonNullableValueCoercedAsNullException(inputTypeField.getType());
}
}
private Map<String, ObjectField> mapObjectValueFieldsByName(ObjectValue inputValue) {
Map<String, ObjectField> inputValueFieldsByName = new LinkedHashMap<>();
for (ObjectField objectField : inputValue.getObjectFields()) {
inputValueFieldsByName.put(objectField.getName(), objectField);
}
return inputValueFieldsByName;
}
} |
package imagej.patcher;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Map;
import java.util.jar.Attributes.Name;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* Encapsulates an ImageJ 1.x "instance".
* <p>
* This class is a partner to the {@link LegacyClassLoader}, intended to make
* sure that the ImageJ 1.x contained in a given class loader is patched and can
* be accessed conveniently.
* </p>
*
* @author "Johannes Schindelin"
*/
public class LegacyEnvironment {
final private boolean headless;
private ClassLoader loader;
private Method setOptions, run, runMacro, runPlugIn, main;
private Field _hooks;
/**
* Constructs a new legacy environment.
*
* @param loader the {@link ClassLoader} to use for loading the (patched)
* ImageJ 1.x classes; if {@code null}, a {@link LegacyClassLoader}
* is constructed.
* @param headless whether to patch in support for headless operation
* (compatible only with "well-behaved" plugins, i.e. plugins that do
* not use graphical components directly)
* @throws ClassNotFoundException
*/
public LegacyEnvironment(final ClassLoader loader, boolean headless)
throws ClassNotFoundException
{
this.headless = headless;
this.loader = loader;
}
private boolean isInitialized() {
return _hooks != null;
}
private synchronized void initialize() {
if (isInitialized()) return;
if (loader != null) {
new LegacyInjector().injectHooks(loader, headless);
}
try {
this.loader = loader != null ? loader : new LegacyClassLoader(headless);
final Class<?> ij = this.loader.loadClass("ij.IJ");
final Class<?> imagej = this.loader.loadClass("ij.ImageJ");
final Class<?> macro = this.loader.loadClass("ij.Macro");
_hooks = ij.getField("_hooks");
setOptions = macro.getMethod("setOptions", String.class);
run = ij.getMethod("run", String.class, String.class);
runMacro = ij.getMethod("runMacro", String.class, String.class);
runPlugIn = ij.getMethod("runPlugIn", String.class, String.class);
main = imagej.getMethod("main", String[].class);
}
catch (Exception e) {
throw new RuntimeException("Found incompatible ij.IJ class", e);
}
// TODO: if we want to allow calling IJ#run(ImagePlus, String, String), we
// will need a data translator
}
/**
* Adds the class path of a given {@link ClassLoader} to the plugin class
* loader.
* <p>
* This method is intended to be used in unit tests as well as interactive
* debugging from inside an Integrated Development Environment where the
* plugin's classes are not available inside a {@code .jar} file.
* </p>
* <p>
* At the moment, the only supported parameters are {@link URLClassLoader}s.
* </p>
*
* @param fromClassLoader the class path donor
*/
public void addPluginClasspath(final ClassLoader fromClassLoader) {
if (fromClassLoader == null) return;
initialize();
for (ClassLoader loader = fromClassLoader; loader != null; loader =
loader.getParent())
{
if (loader == this.loader || loader == this.loader.getParent()) {
break;
}
if (!(loader instanceof URLClassLoader)) {
if (loader != fromClassLoader) continue;
throw new IllegalArgumentException(
"Cannot add class path from ClassLoader of type " +
fromClassLoader.getClass().getName());
}
for (final URL url : ((URLClassLoader) loader).getURLs()) {
if (!"file".equals(url.getProtocol())) {
throw new RuntimeException("Not a file URL! " + url);
}
addPluginClasspath(new File(url.getPath()));
final String path = url.getPath();
if (path.matches(".*/target/surefire/surefirebooter[0-9]*\\.jar")) try {
final JarFile jar = new JarFile(path);
Manifest manifest = jar.getManifest();
if (manifest != null) {
final String classPath =
manifest.getMainAttributes().getValue(Name.CLASS_PATH);
if (classPath != null) {
for (final String element : classPath.split(" +"))
try {
final URL url2 = new URL(element);
if (!"file".equals(url2.getProtocol())) continue;
addPluginClasspath(new File(url2.getPath()));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}
catch (final IOException e) {
System.err
.println("Warning: could not add plugin class path due to ");
e.printStackTrace();
}
}
}
}
/**
* Adds extra elements to the class path of ImageJ 1.x' plugin class loader.
* <p>
* The typical use case for a {@link LegacyEnvironment} is to run specific
* plugins in an encapsulated environment. However, in the case of multiple
* one wants to use multiple legacy environments with separate sets of plugins
* enabled, it becomes impractical to pass the location of the plugins'
* {@code .jar} files via the {@code plugins.dir} system property (because of
* threading issues).
* </p>
* <p>
* In other cases, the plugins' {@code .jar} files are not located in a single
* directory, or worse: they might be contained in a directory among
* {@code .jar} files one might <i>not</i> want to add to the plugin class
* loader's class path.
* </p>
* <p>
* This method addresses that need by allowing to add individual {@code .jar}
* files to the class path of the plugin class loader and ensuring that their
* {@code plugins.config} files are parsed.
* </p>
*
* @param classpathEntries the class path entries containing ImageJ 1.x
* plugins
*/
public void addPluginClasspath(final File... classpathEntries) {
initialize();
try {
final LegacyHooks hooks =
(LegacyHooks) loader.loadClass("ij.IJ").getField("_hooks").get(null);
for (final File file : classpathEntries) {
hooks._pluginClasspath.add(file);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Sets the macro options.
* <p>
* Both {@link #run(String, String)} and {@link #runMacro(String, String)}
* take an argument that is typically recorded by the macro recorder. For
* {@link #runPlugIn(String, String)}, however, only the {@code arg} parameter
* that is to be passed to the plugins {@code run()} or {@code setup()} method
* can be specified. For those use cases where one wants to call a plugin
* class directly, but still provide macro options, this method is the
* solution.
* </p>
*
* @param options the macro options to use for the next call to
* {@link #runPlugIn(String, String)}
*/
public void setMacroOptions(final String options) {
try {
setOptions.invoke(null, options);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Runs {@code IJ.run(command, options)} in the legacy environment.
*
* @param command the command to run
* @param options the options to pass to the command
*/
public void run(final String command, final String options) {
initialize();
final Thread thread = Thread.currentThread();
final ClassLoader savedLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
try {
run.invoke(null, command, options);
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setContextClassLoader(savedLoader);
}
}
/**
* Runs {@code IJ.runMacro(macro, arg)} in the legacy environment.
*
* @param macro the macro code to run
* @param arg an optional argument (which can be retrieved in the macro code
* via {@code getArgument()})
*/
public void runMacro(final String macro, final String arg) {
initialize();
final Thread thread = Thread.currentThread();
final String savedName = thread.getName();
thread.setName("Run$_" + savedName);
final ClassLoader savedLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
try {
runMacro.invoke(null, macro, arg);
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setName(savedName);
thread.setContextClassLoader(savedLoader);
}
}
/**
* Runs {@code IJ.runPlugIn(className, arg)} in the legacy environment.
*
* @param className the plugin class to run
* @param arg an optional argument (which get passed to the {@code run()} or
* {@code setup()} method of the plugin)
*/
public Object runPlugIn(final String className, final String arg) {
initialize();
final Thread thread = Thread.currentThread();
final String savedName = thread.getName();
thread.setName("Run$_" + savedName);
final ClassLoader savedLoader = thread.getContextClassLoader();
thread.setContextClassLoader(loader);
try {
return runPlugIn.invoke(null, className, arg);
}
catch (Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setName(savedName);
thread.setContextClassLoader(savedLoader);
}
}
/**
* Runs {@code ImageJ.main(args)} in the legacy environment.
*
* @param args the arguments to pass to the main() method
*/
public void main(final String... args) {
initialize();
Thread.currentThread().setContextClassLoader(loader);
try {
main.invoke(null, (Object) args);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Gets the class loader containing the ImageJ 1.x classes used in this legacy
* environment.
*
* @return the class loader
*/
public ClassLoader getClassLoader() {
initialize();
return loader;
}
/**
* Gets the ImageJ 1.x menu structure as a map
*/
public Map<String, String> getMenuStructure() {
initialize();
try {
final LegacyHooks hooks = (LegacyHooks) _hooks.get(null);
return hooks.getMenuStructure();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Launches a fully-patched, self-contained ImageJ 1.x.
*
* @throws ClassNotFoundException
*/
public static LegacyEnvironment getPatchedImageJ1()
throws ClassNotFoundException
{
boolean headless = GraphicsEnvironment.isHeadless();
return new LegacyEnvironment(new LegacyClassLoader(headless), headless);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.